<?php

/**
 * @package		SP Download
 * @subpackage	Plugins
 * @copyright	SP CYEND - All rights reserved.
 * @author		SP CYEND
 * @link		http://www.cyend.com
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
// no direct access
defined('_JEXEC') or die;

jimport('joomla.plugin.plugin');

/**
 * Vote plugin.
 *
 * @package		Joomla.Plugin
 * @subpackage	SP Staging login
 */
class plgSystemSpStgSrv extends JPlugin {

    /**
     * Constructor
     *
     * @access      protected
     * @param       object  $subject The object to observe
     * @param       array   $config  An array that holds the plugin configuration
     * @since       1.5
     */
    public function __construct(& $subject, $config) {
        parent::__construct($subject, $config);
        $this->loadLanguage();

        JFactory::getLanguage()->load('com_spstgsrv', JPATH_SITE);

        //import SP CYEND libraries and language
        JFactory::getLanguage()->load('lib_spcyend', JPATH_SITE);
        jimport('spcyend.utilities.factory');        
    }

    function onAfterInitialise() {

        // Get the application object.
        $app = JFactory::getApplication();
        $app_site = JFactory::getApplication('site');

        if ($app->isSite()) {
            return;
        }

        //check url structure
        $option = JRequest::getVar('option', null);
        if (!is_null($option)) {
            if ($option != 'com_spstgsrv')
                return;
        } else
            return;

        $tmpl = JRequest::getVar('view', null);
        if (!is_null($tmpl)) {
            if ($tmpl != 'redirect')
                return;
        } else
            return;

        $tmpl = JRequest::getVar('tmpl', null);
        if (!is_null($tmpl)) {
            if ($tmpl != 'component')
                return;
        } else
            return;

        $format = JRequest::getVar('format_cyend', null);
        if (!is_null($format)) {
            if (($format != 'install') && ($format != 'transfer'))
                return;
        } else
            return;

        $sec = JRequest::getString('sec', null);
        if (is_null($sec))
            return;

        /*
          $package_name = JRequest::getString('package_name', null);
          if (is_null($package_name))
          return;
         * 
         */

        $task = JRequest::getString('task_cyend', null);
        if (is_null($task))
            return;

        //authenticate
        JLoader::import('joomla.application.component.model');
        JLoader::import('installer', JPATH_ADMINISTRATOR . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_spstgsrv' . DIRECTORY_SEPARATOR . 'models');
        $model = CYENDFactory::getModel('installer', 'SPStgSrvModel');

        //authorize IP
        $ip = $model->getIP();
        if (!$model->authorizeIP($ip)) {
            $app_site->redirect(JURI::root() . 'index.php?option=com_spstgsrv&tmpl=component&view=fail&message=' . JText::_('COM_SPSTGSRV_UNAUTHORIZED_IP'));
            return false;
        }

        //authorize password                
        if (!$model->authorizeSEC($sec)) {
            $app_site->redirect(JURI::root() . 'index.php?option=com_spstgsrv&tmpl=component&view=fail&message=' . JText::_('COM_SPSTGSRV_FAILED_DECRYPTION'));
            return false;
        }

        /*
          // Get the log in credentials.
          $credentials = array();
          $credentials['username'] = 'username';
          $credentials['password'] = 'password';

          $options = array();
          $result = $app->login($credentials, $options);

          return;
         * 
         */

        /////////////////////////////////////////
        //$app = JFactory::getApplication();
        //$app = JFactory::getApplication('administrator');

        $db = & JFactory::getDBO();
        $query = 'SELECT `user_id`'
                . ' FROM `#__user_usergroup_map`'
                . ' WHERE group_id = 8';
        $db->setQuery($query);
        $user_id = $db->loadResult();

        $query = 'SELECT `username`, `password`'
                . ' FROM `#__users`'
                . ' WHERE id = ' . (int) $user_id;
        $db->setQuery($query);
        $result = $db->loadRow();
        $username = $result[0];
        $password = $result[1];

        JPluginHelper::importPlugin('user');

        $options = array();
        //$options['action'] = 'core.login.site';
        $options['action'] = 'core.login.admin';

        $response = new stdClass();
        $response->username = $username;
        $response->password = $password;
        $app->triggerEvent('onUserLogin', array((array) $response, $options));
    }

    function onAfterRender() {
        $config = JComponentHelper::getParams('com_spstgsrv');
        $activate_notification = $config->get('activate_notification', 0);
        if ($activate_notification == 0) {
            return true;
        }

        $file = JPATH_ROOT . '/plugins/system/spstgsrv/timestamp.txt';
        if (!is_file($file)) {
            $handle = fopen($file, "w");
            fclose($handle);
        }
        $time = filemtime($file);
        $curtime = time();
        $diff = $curtime - $time;
        if ($diff > 86400) {
            $updates = $this->find();
            $this->inform($updates);
            unlink($file);
            $handle = fopen($file, "w");
            fclose($handle);
        }
        return true;
    }

    private function find() {
        // Find updates
        include_once JPATH_ADMINISTRATOR . '/components/com_spstgsrv/models/installer.php';
        $model = CYENDFactory::getModel('Installer', 'SpStgSrvModel');
        $updates = @$model->find(null);
        return $updates;
    }

    private function inform($updates) {
        unset($updates['result']);
        if (count($updates) == 0) {
            return true;
        }

        $app = JFactory::getApplication();
        //setup mailer
        $mailer = JFactory::getMailer();
        $config = JComponentHelper::getParams('com_spstgsrv');

        // Build email message format.   
        $mailer->isHTML(true);
        $mailer->setSender(array($app->getCfg('mailfrom'), $app->getCfg('fromname')));
        $mailer->setSubject(JText::plural('PLG_SPSTGSRV_MAIL_SUBJECT', $app->getCfg('sitename')));
        $body = JText::plural('PLG_SPSTGSRV_MAIL_BODY_1', $app->getCfg('sitename'));
        foreach ($updates as $update) {
            $body .= '<ul>';
            $body .= '<li>Name: <b>' . $update->name . '</b></li>';
            $body .= '<li>Version: <b>' . $update->version . '</b></li>';
            if (!empty($update->description)) {
                $body .= '<li>Description: ' . $update->description . '</li>';
            }
            if (!empty($update->infourl)) {
                $body .= '<li>Info URL: ' . $update->infourl . '</li>';
            }
            $body .= '</ul><hr/>';
        }
        $body .= JText::plural('PLG_SPSTGSRV_MAIL_BODY_2', $config->get('package_path'));
        $mailer->setBody($body);
        $mailer->addRecipient($config->get('notification_email'));
        $mailer->Send();
    }

}
