<?php
/*------------------------------------------------------------------------
# plg_adminbrandingreloaded - System - Admin Branding Reloaded
# ------------------------------------------------------------------------
# author    MetaKave
# copyright Copyright (C) 2014 MetaKave.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://joomlakave.com
# Technical Support:  Forum -http://www.joomlakave.com/joomla-plugins/item/41-admin-branding-for-joomla
-------------------------------------------------------------------------*/

//error_reporting(E_ALL);
ini_set("display_errors", 0);

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
JHtml::_('jquery.framework');
jimport( 'joomla.plugin.plugin' );
 
/**
 * AdminbrandingReloaded system plugin
 */
class plgSystemAdminbrandingReloaded extends JPlugin
{
    /**
     * Constructor.
     *
     * @access  protected
     * @param   object  $subject The object to observe
     * @param   array   $config  An array that holds the plugin configuration
     * @since   1.0
     */
    public function __construct( &$subject, $config )
    {
            parent::__construct( $subject, $config );
            //global $mainframe;

            // Do some extra initialisation in this constructor if required
            // load plugin parameters
            //$this->_plugin = JPluginHelper::getPlugin( 'system', 'adminbranding' );
            //$this->params = new JParameter( $this->_plugin->params );
            // return if params are empty
            if(!$this->params) return;
            
            
            
            $this->_joomla32ge     = false; 

            if ( version_compare( JVERSION, '3.2', '>=' ) == 1) {  

                $this->_joomla32ge = true;
            }

            //change admin header portion
            $this->_hidelogo        = $this->params->get('hidelogo',0);  //Hide Joomla logo
            //$this->_headercolor     = $this->params->get('headercolor','h_green');
            $this->_headercolor     = '';
            $this->_showlogintitle   = $this->params->get('showlogintitle',1); //default show login title
            $this->_customtitle   = $this->params->get('customtitle','');
            
            $this->_showslogo       = $this->params->get('showslogo',0); //show custom logo in place of joomla logo
            $this->_customlogo      = $this->params->get('customlogo',''); //custom logo image
            $this->_customlogow     = $this->params->get('customlogow','143'); //default image width
            $this->_customlogoh     = $this->params->get('customlogoh','30'); //default image height
            $this->_headerheight    = $this->params->get('headerheight','36'); //custom header height

            $this->_titleleftmargin = $this->params->get('titleleftmargin','0'); //header title left margin
           //
            $this->_showfooter      = $this->params->get('showfooter', 1); //default show 
            $this->_customfooter      = $this->params->get('customfooter', 1); //default show 
            $this->_title_cust_clr      = $this->params->get('title_cust_clr',''); //default show 
            $this->_footertxtlnk      = $this->params->get('footertxtlnk',''); //default show 
            
            
            // admin login page
            
            
            $app = JFactory::getApplication(); //global $mainframe;  in j1.5
            // Dont run in admin if preview is not enabled
            if (!$app->isAdmin()) return;

            $user = JFactory::getUser();
            if($user->guest) $this->_loginpage = true;
            else $this->_loginpage = false;
            
            $this->_usebrandlogo    = $this->params->get('usebrandlogo',0);
            $this->_brandlogo       = $this->params->get('brandlogo','');

            if($this->_joomla32ge){
                $this->_brandlogow      = $this->params->get('brandlogow','15');
            }
            else{
                $this->_brandlogow      = $this->params->get('brandlogow','150');    
            }
            
            $this->_brandlogoh      = $this->params->get('brandlogoh','20');
            
            //login image
            $this->_showcllogo       = $this->params->get('showcllogo',0); //show custom login logo
            $this->_customlogologin  = $this->params->get('customlogologin',''); //custom logo
            $this->_customlogologinh = $this->params->get('customlogologinh','75'); //custom logo height
            //footer joomla icon 
            $this->_lfootericon      = $this->params->get('lfootericon', 1); //Hide footer joomla icon
            
            //background color for login page
            $this->_lbodycolor       = $this->params->get('lbodycolor', 0 );  
            $this->_lbodycolorval    = $this->params->get('lbodycolorval','#E0DEDF');  //default login page background color
            
            //login body background image 
            
            $this->_lbodyimage       = $this->params->get('lbodyimage',0);
            $this->_lbodyimageval    = $this->params->get('lbodyimageval','');
            $this->_lbodyimagecvr    = $this->params->get('lbodyimagecvr');
            $this->_lbodyimagetile   = $this->params->get('lbodyimagetile',1);
            $this->_lbodyimageposx   = $this->params->get('lbodyimageposx','center'); //horizontal position of background image
            $this->_lbodyimageposy   = $this->params->get('lbodyimageposy','center'); //vertical position of background image
            
            $this->_headrchnge       = intval($this->params->get('headrchnge',0));
            $this->_headrgrad        = intval($this->params->get('headrgrad',0));
            $this->_headerbg         = $this->params->get('headerbg','#184A7D');
            $this->_headergradstart  = $this->params->get('headergradstart','#17568c');
            $this->_headergradend    = $this->params->get('headergradend','#1a3867');
            $this->waterwave         = $this->params->get('waterwave','0');
            $this->loginbxbg         = $this->params->get('loginbxbg','1');
            $this->loginbgclr        = $this->params->get("loginbgclr","#f5f5f5");
            $this->adminbg           = $this->params->get("adminbg","2");
            $this->adminbgclr        = $this->params->get("adminbgclr","#ffffff");
            $this->adminbgimg        = $this->params->get("adminbgimg");
            $this->tableclr          = $this->params->get("tableclr","0");
            $this->tableclrodd       = $this->params->get("tableclrodd","#f5f5f5");
            $this->tableclreven      = $this->params->get("tableclreven","#cdcdcd");
            $this->cngloginbtn       = $this->params->get("cngloginbtn");
            
            //var_dump($this->params);
    }
 
    /**
     * Do something onAfterInitialise 
     */
    function onAfterInitialise()
    {
        //$doc = JFactory::getDocument();
        
             
    
    }
 
    /**
     * Do something onAfterRoute 
     */
    function onAfterRoute()
    {
    
    }
 
    /**
     * Do something onAfterDispatch 
     */
    function onAfterDispatch()
    {
            $version = new JVersion();
           
            $app = JFactory::getApplication(); //global $mainframe;  in j1.5
            // Dont run in admin if preview is not enabled
            if (!$app->isAdmin()) return;
            $doc = JFactory::getDocument();            
            
            $extracss       = '';            
            

            $hidelogo = 'display:none  !important;';
             //if hide joomla logo, variable name may be confusing   
            if(intval($this->_hidelogo)) {
                if($this->_joomla32ge){                                
                    $extracss .= '.header img.logo{'.$hidelogo.'}';    
                }
                else{
                    //less than 3.2
                    $extracss .= 'body a.log img{'.$hidelogo.'}';
                }                
                
            }
            
            
            if($this->_showslogo && $this->_customlogo != ''){
                if($this->_joomla32ge){
                    $extracss .= '.header{height:'.$this->_headerheight.'px !important;}'; 
                    $extracss .= '.header img.logo{'.$hidelogo.'}';    
                    $extracss .= '.header .container-logo{ display:block  !important; max-width:'.$this->_customlogow.'px  !important; width:'.$this->_customlogow.'px  !important; height:'.$this->_customlogoh.'px  !important; background: url("'.JURI::root().$this->_customlogo.'") 0 0 no-repeat  !important;}';
                }
                else{
                    $extracss .= 'body a.logo img{ display:none  !important;}';
                    $extracss .= 'body a.logo{ display:block  !important; max-width:'.$this->_customlogow.'px  !important; width:'.$this->_customlogow.'px  !important; height:'.$this->_customlogoh.'px  !important; background: url("'.JURI::root().$this->_customlogo.'") 0 0 no-repeat  !important;}';
                }                
                
            }
            
            if(intval($this->_usebrandlogo) && $this->_brandlogo != ''){
                if($this->_joomla32ge){   
                    $extracss .= ' body a.admin-logo span.icon-joomla{ background: none none !important;}';
                    $extracss .= 'body a.admin-logo{ background: url("'.JURI::root().$this->_brandlogo.'") 0 0 no-repeat !important; text-indent:-99999px !important; height:'.$this->_brandlogoh.'px  !important; width:'.$this->_brandlogow.'px  !important; }';
                    // hathor template
                    $extracss .= 'body #header{ background: url("'.JURI::root().$this->_brandlogo.'") 0 0 no-repeat !important; text-indent:-99999px !important; height:'.$this->_brandlogoh.'px  !important; width:'.$this->_brandlogow.'px  !important;padding-bottom:10px; }';
                }
                else{
                    $extracss .= 'body .navbar .brand{ background: url("'.JURI::root().$this->_brandlogo.'") 0 0 no-repeat !important; text-indent:-99999px !important; height:'.$this->_brandlogoh.'px  !important; width:'.$this->_brandlogow.'px  !important; }';     
                }
                
            }
            
            if(intval($this->_titleleftmargin) > 0 ){
                $extracss .= ' body .page-title{margin-left:'.$this->_titleleftmargin.'px !important;}';
            }
            
            //var_dump($this->_headrchnge);
            if($this->_headrchnge){
                //var_dump('change header backgrund');
                $extracss .= " .header {
                                    background-color: $this->_headerbg !important;
                                }";
                if($this->_headrgrad ){
                    $extracss .= " .header {    
                                    background-image: -moz-linear-gradient(top,$this->_headergradstart,$this->_headergradend)  !important;
                                    background-image: -webkit-gradient(linear,0 0,0 100%,from($this->_headergradstart),to($this->_headergradend))  !important;
                                    background-image: -webkit-linear-gradient(top,$this->_headergradstart,$this->_headergradend)  !important;
                                    background-image: -o-linear-gradient(top,$this->_headergradstart,$this->_headergradend)  !important;
                                    background-image: linear-gradient(to bottom,$this->_headergradstart,$this->_headergradend)  !important;
                                    background-repeat: repeat-x;
                                    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='$this->_headergradstart', endColorstr='$this->_headergradend', GradientType=0)  !important;
                                    
                                 }";
                }else{
                    $extracss .= " .header {    
                                        background-image: none  !important;                                        
                                        filter: none  !important;
                                    
                                   }";
                }
                
            }
            //admin background
            if($this->adminbg== '0'){
            $extracss .= '.admin{ background-color:'.$this->adminbgclr.' !important; }';
            }
            elseif ($this->adminbg== '1') {
                $extracss .= '.admin{ background-image: url('.JURI::root().$this->adminbgimg.') !important; background-size:cover;background-repeat:none;background-attachment: fixed;}';
            }
            else{
                $extracss .= ' '; 
            }
            if ($this->tableclr == "1") {
                $extracss.=".table-striped tbody > tr:nth-child(odd) > td, .table-striped tbody > tr:nth-child(odd) > th{
                background-color:".$this->tableclrodd." !important;
            }
            .table-striped tbody > tr:nth-child(even) > td, .table-striped tbody > tr:nth-child(even) > th{
                background-color:".$this->tableclreven." !important;
            }";
            }
            
            //jQuery('.loginform button').removeClass('btn-info').addClass('btn-success');

            if(intval($this->_loginpage)){
                //hurrah we are in login page
                
                if($this->_showcllogo && $this->_customlogologin != ''){
                    $extracss .= ' #element-box img{ display:none  !important;}';
                    $extracss .= ' #element-box hr{ display:block  !important; width:260px  !important; background: url("'.JURI::root().$this->_customlogologin.'")50% 50% no-repeat  !important; height:'.$this->_customlogologinh.'px  !important;}';
                    // Hathor template
                     $extracss .= ' .login #lock{height:137px  !important; width:150px  !important; background: url("'.JURI::root().$this->_customlogologin.'") no-repeat  !important;}';
                     // $extracss .= ' .pagetitle{display:none;}';
                     //$extracss .= ' .pagetitle:before {content: "Joes Task"}';
                      $extracss .= '#header{height:30px  !important; width:50px  !important; background: url("'.JURI::root().$this->_customlogologin.'") no-repeat  !important;}';
                }
                
                if($this->_lfootericon){
                    //var_dump('tst here');
                    $extracss .= ' .view-login .login-joomla{ display:none !important;}';
                }
                
                if($this->_lbodycolor == '1'){
                    $extracss .= ' .view-login{ background:'.$this->_lbodycolorval.' !important;}';
                    //$extracss .= ' #login-page,#content{ background:'.$this->_lbodycolorval.' !important;}';

                }

                if ($this->loginbxbg=='1') {
                    
                    $extracss .= ' #login-page,#content{ background:'.$this->loginbgclr.' !important;}';
                    $extracss .= ' #content .well{ background:'.$this->loginbgclr.' !important;}';
                }
                else{
                    $extracss .= ' #login-page,#content{ background:transparent !important;}';
                    $extracss .= ' #content .well{ background:transparent !important;}';
                }
                 // var_dump("Ámi tumi");.well
                if($this->_lbodyimage && $this->_lbodyimageval != ''){
                    if ($this->_lbodyimagecvr==2) {
                        $extracss .= ' .view-login{ background:'.$this->_lbodycolorval.' url("'.JURI::root().$this->_lbodyimageval.'") !important;background-size:cover !important;}';
                   
                    }
                    else{

                        if($this->_lbodyimagetile){
                            //let's repeat +0 0 no-repeat+
                            $extracss .= ' .view-login{ background:'.$this->_lbodycolorval.' url("'.JURI::root().$this->_lbodyimageval.'") 0 0 repeat !important;}';
                        }
                        else{
                            $extracss .= ' .view-login{ background:'.$this->_lbodycolorval.' url("'.JURI::root().$this->_lbodyimageval.'") '.$this->_lbodyimageposx.' '.$this->_lbodyimageposy.' no-repeat !important;}';
                        }
                    }
                    
                }                                
            }//end login page  
            if(intval($this->_showfooter) == 0){

                $extracss .= ' body .navbar-fixed-bottom p{display:none  !important; text-indent:-99999px  !important;}';
                //$extracss .= ' body #footerdiv{display:none  !important; text-indent:-99999px  !important;}';
            }
            if(intval($this->_showfooter) == 2){

                $extracss .= ' body .navbar-fixed-bottom p{display:none  !important; text-indent:-99999px  !important;}';
                // hathor template
                $extracss .= ' body #footer p{display:none  !important; text-indent:-99999px  !important;}';
                
            }

            $doc->addStyleDeclaration($extracss); 

            if (!empty($this->cngloginbtn)) {
                var_dump("hobe");
                $doc->addScriptDeclaration('
                    jQuery(document).ready(function(){
                    jQuery(".loginform button").removeClass("btn-primary").addClass("'.$this->cngloginbtn.'");
                    });
                ');
            }

            if ($this->waterwave=='1') {
                
            
            $doc->addScript(JURI::root().'/plugins/system/adminbrandingreloaded/adminbrandingreloaded/js/jquery.ripples.js');
            
            $doc->addScriptDeclaration('
                    jQuery(document).ready(function(){
                        jQuery(".view-login").ripples({
                            resolution: 306,
                            dropRadius: 20, 
                            perturbance: 0.04,
                        });
                    });
                ');
            }
            //$custom_footer = $params->get('customfooter', 1);
            
            $document = JFactory::getDocument();
            
            
            if($this->_showlogintitle == 2){
            $document->addScriptDeclaration('
                jQuery(document).ready(function(){
                jQuery( ".loginform" ).before( "<h3 style=\"text-align:center; color:'.$this->_title_cust_clr.';\">'.$this->_customtitle.'</h3>" );
            });
            ');
            }
            
            if(intval($this->_showfooter) == 2){
            $document->addScriptDeclaration('
                jQuery(document).ready(function(){
                jQuery( ".navbar-fixed-bottom p" ).after( "<span style=\"float:right;\"><a href=\"'.$this->_footertxtlnk.'\" target=\"_blank\">'.$this->_customfooter.'</a></span>" );
            });
            ');
            
            $document->addScriptDeclaration('
                jQuery(document).ready(function(){
                jQuery( "#footer p" ).after( "<span style=\"float:right;\"><a href=\"'.$this->_footertxtlnk.' \" target=\"_blank\">'.$this->_customfooter.' </a></span>" );
            });
            ');
            }
    }
 
    /**
     * Do something onAfterRender 
     */
    function onAfterRender(){
            $app = JFactory::getApplication(); //global $mainframe;  in j1.5
            // Dont run in admin if preview is not enabled
            if (!$app->isAdmin()) return;
            $doc = JFactory::getDocument();
            //
            /*$output            ='<div style="position: absolute;bottom: 10px;right: 50px;font-size:14px;color: #333333;text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);">'.$this->_customfooter.'</div>';*/

            //writing file
            //define('JPATH_BASE', dirname(__FILE__) );
            if(intval($this->_showlogintitle)==1)
            {                   
                $base=JPATH_BASE;
                $FilePath = "$base/language/en-GB/en-GB.com_login.ini";
                $NewText="\rCOM_LOGIN_JOOMLA_ADMINISTRATION_LOGIN=\"Joomla! Administration Login\"";
                $file=file("$base/language/en-GB/en-GB.com_login.ini");
                $a = preg_grep("/COM_LOGIN_JOOMLA_ADMINISTRATION_LOGIN/",$file,PREG_GREP_INVERT );
                file_put_contents($FilePath, $a);
                file_put_contents($FilePath, $NewText, FILE_APPEND | LOCK_EX);
            }
                        
            if(intval($this->_showlogintitle)==2 && $this->_customtitle !='')
            {
                $base=JPATH_BASE;
                $FilePath = "$base/language/en-GB/en-GB.com_login.ini";
                $NewText="\rCOM_LOGIN_JOOMLA_ADMINISTRATION_LOGIN=\"".$this->_customtitle."\"";
                $file=file("$base/language/en-GB/en-GB.com_login.ini");
                $a = preg_grep("/COM_LOGIN_JOOMLA_ADMINISTRATION_LOGIN/",$file,PREG_GREP_INVERT );
                file_put_contents($FilePath, $a);
                file_put_contents($FilePath, $NewText, FILE_APPEND | LOCK_EX);
            //var_dump($this->_customtitle);
            }
            
                /*if($output){
                   JResponse::appendBody($output);      
                }*/
            //
            
            $export_val= $this->params->get('dexport',0);        
            if(intval($export_val)==1)
                        {
            $database = JFactory::getDBO();
                $pluginsql = 'SELECT `params` FROM `#__extensions` WHERE `folder`="system" AND `element`="adminskinstylewithbg"';
                $database->setQuery($pluginsql);
                if($plg = $database->loadObject()){
                    $parameters = $plg->params;
                    //var_dump($parameters);                    
                    $json = json_decode($parameters, true);
                    //var_dump($json['dexport']);
                    }
            // db params export and import
            //var_dump($parameters);
            $base1=JURI::root();
            $temp = tmpfile();
            $file_out = $parameters;
                $filename = "admin_branding_setting.txt";
                $out = strlen($file_out);
                if (isset($file_out)) {
                    /*header("Content-Length: $out");
                    header("Content-type: application/json");
                    header("Content-Disposition: attachment; filename=$filename");
                    readfile($temp, $parameters);*/
                    $handle = fopen($filename, "w");
                    fwrite($handle, $parameters);
                    //echo $handle;
                    fclose($handle);
                    
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment/txt; filename='.basename($filename));
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($filename));
                    readfile($filename);
                    
                }
                
                fclose($temp); // this removes the file
            }
            //$runimport= $this->params->get('runimport',0);
            //if($runimport==1)
            // data import from images/admin_branding_setting.txt
            if(intval($export_val)==2)
            {
                $path=JURI::root()."images/admin_branding_setting.txt";
                //var_dump($path);
                $file = file_get_contents("$path", true);
                //var_dump($file);
                $searchfor = '1';   
                $replace = '0';
                $pos = strrpos($file,$searchfor,-9);
                $newstring = substr_replace($file,$replace,$pos,strlen($searchfor));
                //var_dump($newstring);             
                //file_put_contents($path,$file);       
                
                if(!empty($file))
                {
                    $database = JFactory::getDBO();
                    $pluginsql = 'SELECT `extension_id` FROM `#__extensions` WHERE `folder`="system" AND `element`="adminbrandingreloaded"';        $database->setQuery($pluginsql);                
                    if($plg = $database->loadObject()){
                        $extid = $plg->extension_id;                
                        }
                        //var_dump($file);
                    $plgsql = "UPDATE `#__extensions` SET `params`='$newstring' WHERE `extension_id`= $extid";                  
                    $database->setQuery($plgsql);
                    $result = $database->execute();
                    //var_dump($plgsql);
                   $url1=$_SERVER['REQUEST_URI'];
                   header("Refresh: 2; URL=$url1");
                    
                }
            }
            
            
    }
}