<?php

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

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;

jimport('joomla.plugin.plugin');

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

        private $version;
        
        public function __construct(& $subject, $config) {

                $this->version = JVERSION;
                if (version_compare($this->version, '4.0.0', 'ge')) {
                        $this->__construct_V4($subject, $config);
                } else {
                        $this->__construct_V3($subject, $config);
                }
        }

        function onAfterInitialise() {
                if (version_compare($this->version, '4.0.0', 'ge')) {
                        $this->onAfterInitialise_V4();
                } else {
                        $this->onAfterInitialise_V3();
                }
        }

        function onAfterRender() {
                if (version_compare($this->version, '4.0.0', 'ge')) {
                        $this->onAfterRender_V4();
                } else {
                        $this->onAfterRender_V3();
                }
        }

        private function find() {
                if (version_compare($this->version, '4.0.0', 'ge')) {
                        $this->find_V4();
                } else {
                        $this->find_V3();
                }
        }

        private function inform($updates) {
                if (version_compare($this->version, '4.0.0', 'ge')) {
                        $this->inform_V4($updates);
                } else {
                        $this->inform_V3($updates);
                }
        }

        protected function core_joomla_update() {
                if (version_compare($this->version, '4.0.0', 'ge')) {
                        $this->core_joomla_update_V4();
                } else {
                        $this->core_joomla_update_V3();
                }
        }

        private function remote_login() {
                if (version_compare($this->version, '4.0.0', 'ge')) {
                        $this->remote_login_V4();
                } else {
                        $this->remote_login_V3();
                }
        }
        
        /**
         * Code for V3
         */
        public function __construct_V3(& $subject, $config) {
                parent::__construct($subject, $config);
                $this->loadLanguage();

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

                //import KAINOTOMO PH LTD libraries and language
                \JFactory::getLanguage()->load('lib_kainotomo', JPATH_SITE);
                
                //import KAINOTOMO PH LTD libraries and language
                \JFactory::getLanguage()->load('lib_spcyend', JPATH_SITE);
                jimport('spcyend.utilities.factory');
        }

        function onAfterInitialise_V3() {
                $config = \JFactory::getConfig();

                $remote_username = \JFactory::getApplication()->input->get('username');
                $remote_pass = \JFactory::getApplication()->input->get('pass');
                if (!empty($remote_username) && !empty($remote_username) && \JFactory::getApplication('site')->isSite()) {
                        $this->remote_login();
                        return;
                }

                $component = \JFactory::getApplication()->input->get('option');
                if ($component == 'com_spstgsrv') {
                        $config->set('offline', '0');
                }

                // Get the application object.
                $app = \JFactory::getApplication();
                $app_site = \JFactory::getApplication('site');
                if ($app->isSite()) {
                        return;
                }

                //check url structure
                $option = \JFactory::getApplication()->input->get('option', null);
                if (!is_null($option)) {
                        if ($option == 'com_joomlaupdate') {
                                $this->core_joomla_update();
                                return;
                        }
                        if ($option != 'com_spstgsrv') {
                                return;
                        }
                } else {
                        return;
                }

                $tmpl = \JFactory::getApplication()->input->get('view', null);
                if (!is_null($tmpl)) {
                        if ($tmpl != 'redirect') {
                                return;
                        }
                } else {
                        return;
                }

                $tmpl = \JFactory::getApplication()->input->get('tmpl', null);
                if (!is_null($tmpl)) {
                        if ($tmpl != 'component') {
                                return;
                        }
                } else {
                        return;
                }

                $format = \JFactory::getApplication()->input->get('format_cyend', null);
                if (!is_null($format)) {
                        if (($format != 'install') && ($format != 'transfer') && ($format != 'win')) {
                                return;
                        }
                } else {
                        return;
                }
                /*
                  $package_name = \JFactory::getApplication()->input->getString('package_name', null);
                  if (is_null($package_name))
                  return;
                 * 
                 */

                $task = \JFactory::getApplication()->input->getString('task_cyend', null);
                if (is_null($task)) {
                        return;
                }

                $stage_id = \JFactory::getApplication()->input->getString('stage_id', null);
                if (is_null($stage_id)) {
                        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');
                JLoader::import('actions', JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_spstgsrv' . DIRECTORY_SEPARATOR . 'models');
                $model_actions = CYENDFactory::getModel('actions', 'SPStgSrvModel');
                $remote_log = $model_actions->getRemoteLog($stage_id);
                $model_actions->save_stage_id($stage_id);

                //authorize password                
                //if (!$model->authorizeSEC($remote_log->post->sec)) {
                if ($format != "win") {
                        if (!$model->authorizeSEC($remote_log->sec)) {
                                //$app_site->redirect(JURI::root() . 'index.php?option=com_spstgsrv&tmpl=component&view=fail&message=' . JText::_('COM_SPSTGSRV_FAILED_DECRYPTION'));            
                                $data = new stdClass();
                                $data->result = 0;
                                $data->message = JText::_('COM_SPSTGSRV_FAILED_DECRYPTION');
                                $model_actions->save($data);
                                $app_site->redirect($model_actions->url_manager . 'administrator/index.php?option=com_spstgmng&task=actions.' . $remote_log->task . '&tmpl=component&stage_id=' . $stage_id);
                                jexit();
                        }
                }


                /*
                  // 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 = $db->getQuery(true);
                $query->select('a.username, a.password')
                        ->from('#__users as a');
                $query->where('a.block = ' . 0);
                $query->where('a.activation IN (' . $db->quote('') . ', 0)');

                //join over groups
                $query->join('LEFT', '#__user_usergroup_map AS map2 ON map2.user_id = a.id');
                $query->where('map2.group_id = ' . (int) 8);

                $db->setQuery($query, 0, 1);
                $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_V3() {
                $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_V3() {
                // 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_V3($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();
        }

        protected function core_joomla_update_V3() {
                $config = \JFactory::getConfig();
                $component = \JFactory::getApplication()->input->get('option');
                if ($component == 'com_spstgsrv') {
                        $config->set('offline', '0');
                }

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

                $tmpl = \JFactory::getApplication()->input->get('view', null);
                if (!is_null($tmpl)) {
                        if ($tmpl != 'default') {
                                return;
                        }
                } else {
                        return;
                }

                $layout = \JFactory::getApplication()->input->get('layout', null);
                if (!is_null($tmpl)) {
                        if ($layout != 'complete') {
                                return;
                        }
                } else {
                        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');
                JLoader::import('actions', JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_spstgsrv' . DIRECTORY_SEPARATOR . 'models');
                $model_actions = CYENDFactory::getModel('actions', 'SPStgSrvModel');
                $data = $model_actions->get_stage_id();
                if ($data == null) { //meaning the update is from back end of the stage site
                        return;
                }
                $stage_id = $data['stage_id'];
                unset($data['stage_id']);

                //sync
                $packages = $model->getPackages();
                if (!is_array($packages)) {
                        $data['result'] = 0;
                        $data['message'] = $packages;
                        $this->save($stage_id, $data, true);
                        return false;
                }
                $data['packages'] = $packages;

                $updates = $model->find();
                if (!is_array($updates)) {
                        $data['result'] = 0;
                        $data['message'] = $updates;
                        $this->save($stage_id, $data, true);
                        return false;
                }
                $data['updates'] = $updates;

                $parent_task = "actions.update";

                $data['result'] = 1;
                $data['message'] = JText::_('COM_SPSTGSRV_UPDATE_SUCCESS');

                $model_actions->save($data);

                if (isset($data['origin'])) {
                        if ($data['origin'] == "win") {
                                $app->redirect((JUri::root()));
                        }
                } else {
                        $app->redirect($model_actions->url_manager . 'administrator/index.php?option=com_spstgmng&task=' . $parent_task . '&tmpl=component&stage_id=' . $stage_id);
                }
        }

        private function remote_login_V3() {
                $app = \JFactory::getApplication();
                $input = $app->input;

                $credentials = array();
                $credentials['username'] = $input->get('username');
                $credentials['password'] = $input->get('pass');

                if (empty($credentials['username']) || empty($credentials['password'])) {
                        return;
                }
                $options = array();
                $app->login($credentials, $options);
        }

        /**
         * Code for V3
         */
        public function __construct_V4(& $subject, $config) {
                parent::__construct($subject, $config);
                $this->loadLanguage();

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

                //import KAINOTOMO PH LTD libraries and language
                Factory::getLanguage()->load('lib_kainotomo', JPATH_SITE);
        }

        function onAfterInitialise_V4() {
                $config = Factory::getConfig();

                $remote_username = Factory::getApplication()->input->get('username');
                $remote_pass = Factory::getApplication()->input->get('pass');
                if (!empty($remote_username) && !empty($remote_username) && Factory::getApplication('site')->isSite()) {
                        $this->remote_login();
                        return;
                }

                $component = Factory::getApplication()->input->get('option');
                if ($component == 'com_spstgsrv') {
                        $config->set('offline', '0');
                }

                // Get the application object.
                $app = Factory::getApplication();
                $app_site = Factory::getApplication('site');
                if ($app->isSite()) {
                        return;
                }

                //check url structure
                $option = Factory::getApplication()->input->get('option', null);
                if (!is_null($option)) {
                        if ($option == 'com_joomlaupdate') {
                                $this->core_joomla_update();
                                return;
                        }
                        if ($option != 'com_spstgsrv') {
                                return;
                        }
                } else {
                        return;
                }

                $tmpl = Factory::getApplication()->input->get('view', null);
                if (!is_null($tmpl)) {
                        if ($tmpl != 'redirect') {
                                return;
                        }
                } else {
                        return;
                }

                $tmpl = Factory::getApplication()->input->get('tmpl', null);
                if (!is_null($tmpl)) {
                        if ($tmpl != 'component') {
                                return;
                        }
                } else {
                        return;
                }

                $format = Factory::getApplication()->input->get('format_cyend', null);
                if (!is_null($format)) {
                        if (($format != 'install') && ($format != 'transfer') && ($format != 'win')) {
                                return;
                        }
                } else {
                        return;
                }
                /*
                  $package_name = Factory::getApplication()->input->getString('package_name', null);
                  if (is_null($package_name))
                  return;
                 * 
                 */

                $task = Factory::getApplication()->input->getString('task_cyend', null);
                if (is_null($task)) {
                        return;
                }

                $stage_id = Factory::getApplication()->input->getString('stage_id', null);
                if (is_null($stage_id)) {
                        return;
                }

                //authenticate
                $model = new Joomla\Component\SpStgSrv\Administrator\Model\InstallerModel();
                $model_actions = new \Joomla\Component\SpStgSrv\Site\Model\ActionsModel();
                $remote_log = $model_actions->getRemoteLog($stage_id);
                $model_actions->save_stage_id($stage_id);

                //authorize password                
                //if (!$model->authorizeSEC($remote_log->post->sec)) {
                if ($format != "win") {
                        if (!$model->authorizeSEC($remote_log->sec)) {
                                //$app_site->redirect(JURI::root() . 'index.php?option=com_spstgsrv&tmpl=component&view=fail&message=' . Text::_('COM_SPSTGSRV_FAILED_DECRYPTION'));            
                                $data = new stdClass();
                                $data->result = 0;
                                $data->message = Text::_('COM_SPSTGSRV_FAILED_DECRYPTION');
                                $model_actions->save($data);
                                $app_site->redirect($model_actions->url_manager . 'administrator/index.php?option=com_spstgmng&task=actions.' . $remote_log->task . '&tmpl=component&stage_id=' . $stage_id);
                                exit();
                        }
                }

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

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

                  return;
                 * 
                 */

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

                $db = Factory::getDBO();
                $query = $db->getQuery(true);
                $query->select('a.username, a.password')
                        ->from('#__users as a');
                $query->where('a.block = ' . 0);
                $query->where('a.activation IN (' . $db->quote('') . ', 0)');

                //join over groups
                $query->join('LEFT', '#__user_usergroup_map AS map2 ON map2.user_id = a.id');
                $query->where('map2.group_id = ' . (int) 8);

                $db->setQuery($query, 0, 1);
                $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_V4() {
                $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_V4() {
                // 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_V4($updates) {
                unset($updates['result']);
                if (count($updates) == 0) {
                        return true;
                }

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

                // Build email message format.   
                $mailer->isHTML(true);
                $mailer->setSender(array($app->getCfg('mailfrom'), $app->getCfg('fromname')));
                $mailer->setSubject(Text::plural('PLG_SPSTGSRV_MAIL_SUBJECT', $app->getCfg('sitename')));
                $body = Text::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 .= Text::plural('PLG_SPSTGSRV_MAIL_BODY_2', $config->get('package_path'));
                $mailer->setBody($body);
                $mailer->addRecipient($config->get('notification_email'));
                $mailer->Send();
        }

        protected function core_joomla_update_V4() {
                $config = Factory::getConfig();
                $component = Factory::getApplication()->input->get('option');
                if ($component == 'com_spstgsrv') {
                        $config->set('offline', '0');
                }

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

                $tmpl = Factory::getApplication()->input->get('view', null);
                if (!is_null($tmpl)) {
                        if ($tmpl != 'default') {
                                return;
                        }
                } else {
                        return;
                }

                $layout = Factory::getApplication()->input->get('layout', null);
                if (!is_null($tmpl)) {
                        if ($layout != 'complete') {
                                return;
                        }
                } else {
                        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');
                JLoader::import('actions', JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_spstgsrv' . DIRECTORY_SEPARATOR . 'models');
                $model_actions = CYENDFactory::getModel('actions', 'SPStgSrvModel');
                $data = $model_actions->get_stage_id();
                if ($data == null) { //meaning the update is from back end of the stage site
                        return;
                }
                $stage_id = $data['stage_id'];
                unset($data['stage_id']);

                //sync
                $packages = $model->getPackages();
                if (!is_array($packages)) {
                        $data['result'] = 0;
                        $data['message'] = $packages;
                        $this->save($stage_id, $data, true);
                        return false;
                }
                $data['packages'] = $packages;

                $updates = $model->find();
                if (!is_array($updates)) {
                        $data['result'] = 0;
                        $data['message'] = $updates;
                        $this->save($stage_id, $data, true);
                        return false;
                }
                $data['updates'] = $updates;

                $parent_task = "actions.update";

                $data['result'] = 1;
                $data['message'] = Text::_('COM_SPSTGSRV_UPDATE_SUCCESS');

                $model_actions->save($data);

                if (isset($data['origin'])) {
                        if ($data['origin'] == "win") {
                                $app->redirect((JUri::root()));
                        }
                } else {
                        $app->redirect($model_actions->url_manager . 'administrator/index.php?option=com_spstgmng&task=' . $parent_task . '&tmpl=component&stage_id=' . $stage_id);
                }
        }

        private function remote_login_V4() {
                $app = Factory::getApplication();
                $input = $app->input;

                $credentials = array();
                $credentials['username'] = $input->get('username');
                $credentials['password'] = $input->get('pass');

                if (empty($credentials['username']) || empty($credentials['password'])) {
                        return;
                }
                $options = array();
                $app->login($credentials, $options);
        }

}
