Your IP : 216.73.217.6


Current Path : /home/smartconb/www/armencom33/modules/mod_jmailalerts/
Upload File :
Current File : /home/smartconb/www/armencom33/modules/mod_jmailalerts/helper.php

<?php

/**
 * User: zaven
 * Date: 23.09.2019
 * Time: 12:29
 * Project: dev.armencom.be
 **/
class ModJMailAlertsHelper
{
    /**
     * Retrieves the hello message
     * @param array $params An object containing the module parameters
     * @access public
     */

    /*
    $lang   = JFactory::getLanguage();
	$languages	= JLanguageHelper::getLanguages();
	$app	= JFactory::getApplication();
    */

    public static function doTask(JInput $params)
    {
        $uri = JFactory::getURI();
        $pageURL = "index.php" . $uri->toString(array('query'));
        $app = JFactory::getApplication();
        $my = JFactory::getUser();
        $db = JFactory::getDbo();

        $alt = $params->get('mod_jmailalerts_alt', array(), 'ARRAY');
        $user_email = $params->getString('mod_jmailalerts_user_email');
        $user_name = $params->getString('mod_jmailalerts_user_name');

        if (count($alt) > 0) {
            $query_string = array();
            if ($user_email != '')
                $query_string[] = " `email_id`='" . $user_email . "' ";
            if ($my->id) {
                $query_string[] = " `user_id`=" . $my->id . " ";
            }

            if (count($query_string) > 0) {
                if ($params->get('mod_jmailalerts_action') === 'subscribe') {

                    $query = "SELECT * FROM #__jma_alerts WHERE state = 1 AND id IN (" . join(',', $alt) . ")";
                    $db->setQuery($query);
                    $rows = $db->loadAssocList();

                    if ($rows) {
                        foreach ($rows as $row) {

                            $pluginArray = self::alertqryconcat();
                            $pluginText = '';

                            if (count($pluginArray) > 0) {
                                foreach ($pluginArray as $plugin) {
                                    $pluginDatas = self::getPluginData($plugin);
                                    if (count($pluginDatas) > 0) {
                                        foreach ($pluginDatas as $pluginData) {
                                            $element = $pluginData->element;
                                            $pluginParams = json_decode($pluginData->params, true);

                                            foreach ($pluginParams as $key => $value) {
                                                if (is_array($value)) {
                                                    $pluginText .= $element . '|' . $key . '=' . join(',', $value) . "\n";
                                                } else {
                                                    $pluginText .= $element . '|' . $key . '=' . $value . "\n";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            $query = "SELECT count(id) FROM `#__jma_subscribers` WHERE alert_id=" . $row['id'] . " AND (" . join(' OR ', $query_string) . ")";
                            $db->setQuery($query);
                            $altIdCount = $db->loadResult();
                            if ($altIdCount > 0) {
                                $query = "UPDATE `#__jma_subscribers` SET `state`=1" .
                                    ", `plugins_subscribed_to` = " . $db->Quote($pluginText) .
                                    ", `date` = NOW()" .
                                    " WHERE (" . join(' OR ', $query_string) . ") AND alert_id=" . $db->Quote($row['id']);
                                $db->setQuery($query);
                                $db->execute();
                            } else {

                                $user_id = 0;
                                if ($my->id) {
                                    $user_id = $my->id;
                                }

                                $query = "INSERT INTO `#__jma_subscribers`(`user_id`,`name`,`email_id`,`alert_id`,`frequency`,`date`,`plugins_subscribed_to`)
							 VALUES (
							 	" . $db->Quote($user_id) . ",
							 	" . $db->Quote($user_name) . ",
							 	" . $db->Quote($user_email) . ",
							 	" . $db->Quote($row['id']) . ",
							 	" . $db->Quote($row['default_freq']) . ", NOW(),
							 	" . $db->Quote($pluginText) . "
							)";

                                $db->setQuery($query);
                                $db->execute();
                            }
                        }
                    }

                    $app->enqueueMessage(JText::_('MOD_JMAILALERTS_SUCCESSFULLY_SUBSCRIBED'), 'success');

                } else if ($params->get('mod_jmailalerts_action') === 'unsubscribe') {


                    $delquery = "UPDATE `#__jma_subscribers` SET `state`=0 WHERE (" . join(' OR ', $query_string) . ") AND alert_id IN (" . join(',', $alt) . ")";
                    $db->setQuery($delquery);
                    $db->execute();
                    print_r($delquery);
                    $app->enqueueMessage(JText::_('MOD_JMAILALERTS_SUCCESSFULLY_UNSUBSCRIBED'), 'success');
                }
            } else {
                //todo: what to do if no e-mail is specified?
            }
        } else {
            //todo: what to do if no alert is available?
        }

        $app->redirect(JRoute::_($pageURL));

    }

    public static function gettotalalertcount()
    {
        $lang_code = self::getCurrentLanguageShortCode();
        $db = JFactory::getDbo();
        // get translated path if exist
        $query = $db->getQuery(true);
        $query->select('count(*)')
            ->from('#__jma_alerts')
            ->where('right(title, 2) = \'' . $lang_code . '\'')
            ->where('state = 1');
        $db->setQuery($query);
        $altid = $db->loadResult();
        return $altid;
    }

    public static function get_all_alertid()
    {
        $lang_code = self::getCurrentLanguageShortCode();
        $db = JFactory::getDbo();
        // get translated path if exist
        $query = $db->getQuery(true);
        $query->select('id')
            ->from('#__jma_alerts')
            ->where('right(title, 2) = \'' . $lang_code . '\'')
            ->where('state = 1');
        $db->setQuery($query);
        $altid = $db->loadColumn();
        return $altid;

    }


    public static function getFreq($altid)
    {
        $user = JFactory::getUser();

        $db = JFactory::getDbo();
        // get translated path if exist
        $query = $db->getQuery(true);
        $query->select('title,allowed_freq,default_freq ,allow_users_select_plugins,description')
            ->from('#__jma_alerts')
            ->where('id = ' . (int)$altid);
        $db->setQuery($query);

        $resultfrq = $db->loadObjectList();
        $allow_frq = $resultfrq[0]->allowed_freq;

        // $allow_frq = explode(',', $allow_frq);
        $allow_frq = str_replace('[', '', $allow_frq);
        $allow_frq = str_replace(']', '', $allow_frq);
        $allow_frq = str_replace('"', '', $allow_frq);
        $allow_frq = explode(',', $allow_frq);

        // Get frequency name for each allowed frequency.
        foreach ($allow_frq as $key => $value) {
            $query = $db->getQuery(true);
            $query->select('name')
                ->from('#__jma_frequencies')
                ->where('id = ' . (int)$value);
            $db->setQuery($query);

            $frequency_name[$value] = JText::_($db->loadResult());
        }

        $query = $db->getQuery(true);
        $query->select('`frequency`')
            ->from('#__jma_subscribers')
            ->where('alert_id = ' . (int)$altid)
            ->where('user_id = ' . (int)$user->id);
        $db->setQuery($query);

        $uerselfrq = $db->loadResult();

        if ($uerselfrq) {
            $default_freq = $uerselfrq;
        } else {
            $default_freq = $resultfrq[0]->default_freq;
        }

        $setfrqname = 'c' . $altid;
        $alertfrqdta[] = JHtml::_("select.genericlist", $frequency_name, "$setfrqname", "class='input' ", "value", "text", $default_freq);
        $alertfrqdta[] = $resultfrq[0]->title;
        $alertfrqdta[] = $resultfrq[0]->description;
        $alertfrqdta[] = $resultfrq[0]->allow_users_select_plugins;

        return $alertfrqdta;
    }

    public static function savePref()
    {
        $app = JFactory::getApplication();
        $input = JFactory::getApplication()->input;
        $user_freq = $input->get('c');
        $unsubscribe_chk_box_status = $input->get('unsubscribe_chk_box');
        $my = JFactory::getUser();
        $user_state = 1;

        $db = JFactory::getDbo();

        if ($unsubscribe_chk_box_status) {
            $user_freq = 0;
            $user_state = 0;
        }

        $post = JRequest::get('post');
        $alt = $input->get('alt', array(), 'ARRAY');

        // Gt all alert id
        $query = "SELECT id FROM #__jma_alerts";
        $db->setQuery($query);
        $delaltuser = $db->loadColumn();

        $delalt = array();

        for ($i = 0; $i < count($delaltuser); $i++) {
            if (!in_array($delaltuser[$i], $alt)) {
                $delalt[] = $delaltuser[$i];
            }
        }

        // Query construct for delete
        $tmpdel = '';

        for ($i = 0; $i < count($delalt); $i++) {
            $tmpdel .= " `alert_id` =" . $delalt[$i];

            if ($i != (count($delalt) - 1)) {
                $tmpdel .= " OR ";
            }
        }

        if ($tmpdel) {
            $tmpdel = "(" . $tmpdel . ") ";
        }

        if ($tmpdel != "" && ($my->id || $post['user_email'])) {
            // Changed in 2.4.3
            // $delquery = " DELETE FROM #__jma_subscribers WHERE user_id = {$my->id} AND $tmpdel";

            if ($my->id) {
                $query_string = " `user_id`=" . $my->id;
            } else {
                $query_string = " `email_id`='" . $post['user_email'] . "' ";
            }

            $delquery = "UPDATE `#__jma_subscribers` SET `state`=0 WHERE " . $query_string . " AND " . $tmpdel;
            $db->setQuery($delquery);
            $db->execute();
        }

        for ($i = 0; $i < count($alt); $i++) {
            $db_plugentry = "";

            if (isset($post['alt'])) {
                $tmp = 'ch' . $alt[$i];

                if (count($input->get($tmp)) != 0) {
                    $user_set_plug = array_values($post["$tmp"]);
                }

                $plug_name = array_keys($post);

                // Code for converting the plugin params to store in the database
                foreach ($plug_name as $plug_name) {
                    if (count($input->get($tmp)) != 0) {
                        if (in_array($plug_name, $user_set_plug)) {
                            foreach ($post[$plug_name] as $key => $val) {
                                if (is_array($val)) {
                                    $val = implode(',', $val);
                                }

                                $db_plugentry .= $plug_name . '|' . $key . '=' . $val . "\n";
                            }
                        }
                    }
                }
            } else {
                // Space is important
                $db_plugentry = " ";
            }

            $db_plugentry = str_replace("_$alt[$i]", "", $db_plugentry);

            $today = date('Y-m-d H:i:s');

            // For registered user
            if ($my->id) {
                $query = "SELECT * FROM #__jma_subscribers WHERE user_id=" . $my->id . " AND alert_id = $alt[$i]";
            } else {
                $query = "SELECT * FROM #__jma_subscribers WHERE email_id=" . $db->Quote($post['user_email']) . " AND alert_id = " . $alt[$i];
            }

            $db->setQuery($query);
            $result = $db->loadAssoc();

            if (empty($result)) {
                $isNew = true;

                if ($db_plugentry == '') {
                    $db_plugentry = '';
                } else {
                    // For registered user
                    if ($my->id) {
                        $get_name_email = self::getname_email($my->id);
                        $query = "INSERT INTO `#__jma_subscribers`(`user_id`,`name`,`email_id`,`alert_id`,`frequency`,`date`,`plugins_subscribed_to`)
							 VALUES (
							 	" . $db->Quote($my->id) . ",
							 	" . $db->Quote($get_name_email['username']) . ",
							 	" . $db->Quote($get_name_email['email']) . ",
							 	" . $db->Quote($alt[$i]) . ",
							 	" . $input->get("c$alt[$i]") . ",
							 	" . $db->Quote($today) . ",
							 	" . $db->Quote($db_plugentry) . "
							)";
                    } else {
                        // For guest user...
                        $query = "INSERT INTO `#__jma_subscribers` (`user_id`,`alert_id`,`name`,`email_id`,`frequency`,`date`,`plugins_subscribed_to`)
							 VALUES (
							 	0,
							 	" . $db->Quote($alt[$i]) . ",
							 	" . $db->Quote($post['user_name']) . ",
							 	" . $db->Quote($post['user_email']) . ",
							 	" . $input->get("c$alt[$i]") . ",
							 	" . $db->Quote($today) . ",
							 	" . $db->Quote($db_plugentry) . "
							 )";
                    }
                }
            } else {
                $isNew = false;
                $update_query_string = '';

                if ($db_plugentry != '') {
                    $update_query_string = ", `plugins_subscribed_to` =" . $db->Quote($db_plugentry);

                    if ($my->id) {
                        $query = "UPDATE `#__jma_subscribers`
							 SET `state`= " . $user_state . ",`frequency` = " . $input->get("c$alt[$i]") . "" . $update_query_string . "
							  WHERE `user_id` = {$my->id} " . "AND `alert_id` = $alt[$i]";
                    } else {
                        $query = "UPDATE `#__jma_subscribers`
							 SET `state`= " . $user_state . ",`frequency` = " . $input->get("c$alt[$i]") . "" . $update_query_string . "
							  WHERE `email_id` = {$db->Quote($post['user_email'])} " . "AND `alert_id` = $alt[$i]";
                    }
                } else {
                    if ($my->id) {
                        $query = "DELETE FROM #__jma_subscribers WHERE `alert_id` = $alt[$i] AND `user_id` = {$my->id}";
                    } else {
                        $query = "DELETE FROM #__jma_subscribers WHERE `alert_id` = $alt[$i] AND `email_id` = " . $db->Quote($post['user_email']);
                    }
                }
            }

            // @echo $query;
            $db->setQuery($query);
            $db->execute();

            $data = array();
            $data['id'] = $result['id'] ? $result['id'] : 0;
            $data['user_id'] = $my->id ? $my->id : 0;

            // New Subscription
            if ($isNew) {
                // Register User
                if ($my->id) {
                    $getNameEmail = self::getname_email($my->id);
                    $data['name'] = $getNameEmail['username'];
                    $data['email_id'] = $getNameEmail['email'];
                } else {
                    $data['name'] = $post['user_name'];
                    $data['email_id'] = $post['user_email'];
                }

                $data['date'] = $today;
                $data['state'] = $user_state;
                $data['alert_id'] = $alt[$i];
                $data['frequency'] = $input->get("c$alt[$i]");
                $data['plugins_subscribed_to'] = $db_plugentry;
                $data['state'] = $user_state;
                $data['subscriptionId'] = $db->insertid();

                $dispatcher = JDispatcher::getInstance();
                JPluginHelper::importPlugin('jmailalert');
                $dispatcher->trigger('jmaOnAfterAlertSubscriptionSave', array($data, $isNew));
            } // Edit Subscription
            else {
                if ($user_state != $result['state'] || $result['frequency'] != $input->get("c$alt[$i]")) {
                    $data['name'] = $result['name'];
                    $data['email_id'] = $result['email_id'];
                    $data['date'] = $today;
                    $data['state'] = $user_state;
                    $data['alert_id'] = $alt[$i];
                    $data['frequency'] = $input->get("c$alt[$i]");
                    $data['plugins_subscribed_to'] = $db_plugentry;
                    $data['state'] = $user_state;
                    $data['subscriptionId'] = $result['id'];

                    $dispatcher = JDispatcher::getInstance();
                    JPluginHelper::importPlugin('jmailalert');
                    $dispatcher->trigger('jmaOnAfterAlertSubscriptionSave', array($data, $isNew));
                }
            }
        }

        $msg = JText::_('COM_JMAILALERTS_SETTINGS_SAVED_SUCCESSFULLY');
        $jmailalertsModelEmails = new jmailalertsModelEmails;
        $itemid = $jmailalertsModelEmails->getItemid();
        //$app->redirect(JRoute::_('index.php?option=com_jmailalerts&view=emails&Itemid=' . $itemid, false), $msg);
    }

    public function getname_email($user_id)
    {
        $db = JFactory::getDBO();
        $query = "SELECT username, email
				FROM #__users
				WHERE id=" . $user_id;
        $db->setQuery($query);
        $name_email_array = $db->loadAssoc();

        // @print_r($name_email_array); die('asdasd');

        return $name_email_array;
    }

    public static function getCurrentLanguageShortCode()
    {
        $lang = JFactory::getLanguage();
        $lang_code = $lang->getTag();
        $lang_code = strtolower(substr($lang_code, 0, 2));
        return $lang_code;
    }

    public static function alertqryconcat()
    {
        $db = JFactory::getDbo();
        // Get plugins
        $db->setQuery('SELECT name, element,params FROM #__extensions WHERE folder=\'emailalerts\' AND enabled = 1');
        $test = $db->loadObjectList();

        // Get alerts
        $query = "SELECT template FROM #__jma_alerts WHERE state=1";
        $db->setQuery($query);
        $test2 = $db->loadObjectList();

        // Get the plugin names and store in an array
        $db->setQuery('SELECT element FROM #__extensions WHERE folder = \'emailalerts\'  AND enabled = 1');
        $plugnamecompair = $db->loadColumn();

        $qry_concat = array();

        if ($test2) {
            foreach ($test2 as $key) {
                $plugin_name_string = array();

                for ($i = 0; $i < count($plugnamecompair); $i++) {
                    if (strstr($key->template, $plugnamecompair[$i])) {
                        $plugin_name_string[] = $plugnamecompair[$i];
                    }
                }

                $tmp = "";

                for ($i = 0; $i < count($plugin_name_string); $i++) {
                    $tmp .= " element LIKE '" . $plugin_name_string[$i] . "' ";

                    if ($i != (count($plugin_name_string) - 1)) {
                        $tmp .= " OR ";
                    }
                }

                $qry_concat[] = $tmp;
                unset($plugin_name_string);
            }
        }

        return $qry_concat;
    }

    public static function getPluginData($qry_concat)
    {
        $db = JFactory::getDbo();
        // This is important to load lang. constants for plugins in frontend.
        JPluginHelper::importPlugin('emailalerts');
        $dispatcher = JDispatcher::getInstance();

        if ($qry_concat !== '') {
            $query = "SELECT name, element, params
			 FROM #__extensions
			 WHERE folder='emailalerts'
			 AND (" . $qry_concat . ")
			 AND enabled=1
			 ORDER BY ordering ASC";

            $db->setQuery($query);
            $plugin_data = $db->loadObjectList();

            if ($plugin_data) {
                return $plugin_data;
            }
        } else {
            return false;
        }
    }

}