AnonSec Shell
Server IP : 54.36.91.62  /  Your IP : 216.73.217.112
Web Server : Apache
System : Linux webm013.cluster127.gra.hosting.ovh.net 5.15.206-ovh-vps-grsec-zfs-classid #1 SMP Fri May 15 02:41:25 UTC 2026 x86_64
User : coopiak ( 151928)
PHP Version : 8.3.23
Disable Function : _dyuweyrj4,_dyuweyrj4r,dl
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /home/coopiak/amisdesseniors-fr/lyon/components/com_djcatalog2/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/coopiak/amisdesseniors-fr/lyon/components/com_djcatalog2/controller.php
<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 *
 */

use Joomla\Registry\Registry;
use Joomla\CMS\Factory;

defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
jimport('joomla.filesystem.file');

class DJCatalog2Controller extends JControllerLegacy
{
    protected $default_view = 'items';

    function __construct($config = array())
    {
        $config['default_view'] = 'items';
        parent::__construct($config);
        $lang = JFactory::GetLanguage();
        $lang->load('com_djcatalog2');
        $this->registerTask('modfp', 'getFrontpageXMLData');
        $this->registerTask('search_reset', 'search');
        $this->registerTask('psearch_reset', 'filterproducers');
    }

    function display($cachable = true, $urlparams = null)
    {
        $app = JFactory::getApplication();

        $view = $app->input->get('view');
        if (($view == '' || $view == 'featured') /*&& $app->input->get('task') == ''*/) {
            $this->input->set('view', 'items');
        }
        $user = JFactory::getUser();

        $params = Djcatalog2Helper::getParams();
        $cached_views = (array)$params->get('cache_options', array('items', 'item', 'producers', 'producer', 'map'));

        if ($view == 'itemform') {
            $id = $app->input->getInt('id');

            if ($app->input->getCmd('format', 'html') == 'html' && $id > 0 && !$this->checkEditId('com_djcatalog2.edit.itemform', $id)) {
                $this->setRedirect(JRoute::_(DJCatalogHelperRoute::getMyItemsRoute(), false), JText::sprintf('JLIB_APPLICATION_ERROR_UNHELD_ID', $id));
                return true;
            }
        }

        $noncachable = array('itemform', 'myitems', 'cart', 'order', 'orders', 'query', 'checkout', 'query', 'questions', 'question', 'compare', 'orderform');

        if (in_array($view, $noncachable) || !in_array($view, $cached_views) || $user->id) {
            $cachable = false;
        } else if ($view == 'items' || $view == 'map') {
            $hasSearch = (bool)(
                $app->input->getString('search', '') != ''
                || $app->input->getString('mapsearch', '') != ''
                || $app->input->getString('ind', '') != ''
                || $app->input->getString('tag', '') != ''
            );
            $hasFilters = (bool)($app->input->getString('cm', '') !== '');
            $hasSort = (bool)($app->input->getString('order', '') != '' || $app->input->getString('dir', '') != '');

            if ($hasSearch) {
                $cachable = false;
            }
            if ($hasFilters && !in_array('filters', $cached_views)) {
                $cachable = false;
            }
            if ($hasSort && !in_array('sort', $cached_views)) {
                $cachable = false;
            }
        } else if ($app->input->get('ic'))
            $cachable = false;

        DJCatalog2ThemeHelper::setThemeAssets();

        $urlparams = array(
            'id' => 'STRING',
            'cid' => 'STRING',
            'pid' => 'STRING',
            'pcid' => 'STRING',
            'aid' => 'STRING',
            'search' => 'STRING',
            'task' => 'STRING',
            'order' => 'STRING',
            'dir' => 'STRING',
            'cm' => 'INT',
            'l' => 'STRING',
            'Itemid' => 'INT',
            'limit' => 'UINT',
            'limitstart' => 'UINT',
            'start' => 'UINT',
            'lang' => 'CMD',
            'tmpl' => 'CMD',
            'ind' => 'RAW',
            'template' => 'STRING',
            'price_from' => 'STRING',
            'price_to' => 'STRING',
            'type' => 'STRING',
            'print' => 'INT',
            'pdf' => 'INT',
            'layout' => 'STRING',
            'ms_unit' => 'STRING',
            'ms_radius' => 'INT',
            'mapsearch' => 'STRING',
            'eid' => 'STRING',
            'ecid' => 'STRING',
            'oid' => 'INT',
            'plg' => 'STRING',
            'plgid' => 'INT',
            'billing' => 'INT',
            'error' => 'RAW',
            'success' => 'RAW',
            'view' => 'STRING',
            'layout' => 'STRING',
            'qid' => 'UINT',
            'token' => 'STRING',
            'tag' => 'STRING',
            'pic_only' => 'INT',
            'cntid' => 'INT',
            'stid' => 'INT',
            'combination_id' => 'INT',
            'pks' => 'STRING',
            'filter' => 'ARRAY'
        );

        $db = JFactory::getDbo();
        $db->setQuery('select alias from #__djc2_items_extra_fields where type=\'checkbox\' or type=\'radio\' or type=\'select\'');
        $extra_fields = $db->loadColumn();
        if (count($extra_fields) > 0) {
            foreach ($extra_fields as $extra_field) {
                $urlparams['f_' . $extra_field] = 'RAW';

                // stupid, stupid, stupid me
                $urlparams[str_replace('-', '_', 'f_' . $extra_field)] = 'RAW';
            }
        }

        Djcatalog2HelperPrice::triggerCurrencyExAPI();

        parent::display($cachable, $urlparams);
    }

    function getFrontpageXMLData()
    {
        $model = $this->getModel('modfrontpage');
        $xml = $model->getXml();

        if (!count(array_diff(ob_list_handlers(), array('default output handler'))) || ob_get_length()) {
            @ob_clean();
        }

        if (!headers_sent()) {
            $document = JFactory::getDocument();
            header('Content-Type: \'text/xml\'; charset=' . $document->_charset);
        }

        echo $xml;
        JFactory::getApplication()->close();
    }

    function search()
    {
        $app = JFactory::getApplication();
        $db = JFactory::getDbo();
        //$post = JRequest::get('post');
        $post = $app->input->getMethod() == 'POST' ? $app->input->getArray($_POST) : $app->input->getArray($_GET);
        $params = array();

        if ($app->input->getCmd('task') != 'search_reset') {
            foreach ($post as $key => $value) {
                if ($key != 'task' && $key != 'option' && $key != 'view' && $key != 'cid' && $key != 'pid' && $key != 'Itemid') {
                    if ($key == 'search') {
                        $params[] = $key . '=' . urlencode($value);
                    } else if (is_array($value)) {
                        foreach ($value as $k => $v) {
                            if (is_numeric($k)) {
                                $params[] = $key . '[]=' . $v;
                            } else {
                                $params[] = $key . '[' . $k . ']=' . $v;
                            }
                        }
                    } else {
                        $params[] = $key . '=' . $value;
                    }
                }
            }
        }


        if (!array_key_exists('cm', $post) && $app->input->getCmd('task') != 'search_reset') {
            $params[] = 'cm=0';
        }

        $categoryId = $app->input->get('cid', '0', 'string');
        if (is_numeric($categoryId) && $categoryId > 0 && strstr($categoryId, ':') === false) {
            $query = $db->getQuery(true);
            $query->select('id, alias')->from('#__djc2_categories')->where('id=' . (int)$categoryId);
            $db->setQuery($query);
            $category = $db->loadObject();
            if ($category) {
                $categoryId .= ':' . $category->alias;
                $app->setUserState('com_djcatalog.items.filter.category', $category->id);
            }
        }
        $producerId = $app->input->get('pid', '0', 'string');
        if (is_numeric($producerId) && $producerId > 0 && strstr($producerId, ':') === false) {
            $query = $db->getQuery(true);
            $query->select('id, alias')->from('#__djc2_producers')->where('id=' . (int)$producerId);
            $db->setQuery($query);
            $producer = $db->loadObject();
            if ($producer) {
                $producerId .= ':' . $producer->alias;
                $app->setUserState('com_djcatalog.items.filter.producer', $producer->id);
            }
        }
        $menu = JFactory::getApplication('site')->getMenu('site');
        $uri = DJCatalogHelperRoute::getCategoryRoute($categoryId, $producerId);
        if (strpos($uri, '?') === false) {
            $get = (count($params)) ? '?' . implode('&', $params) : '';
        } else {
            $get = (count($params)) ? '&' . implode('&', $params) : '';
        }

        $cparams = JComponentHelper::getParams('com_djcatalog2');
        $jumpToSfx = $cparams->get('search_jump', true) ? '#tlb' : '';
        $app->redirect(JRoute::_($uri . $get, false) . $jumpToSfx);
    }

    function producersearch()
    {
        $app = JFactory::getApplication();
        //$post = JRequest::get('post');
        $post = $app->input->getMethod() == 'POST' ? $app->input->getArray($_POST) : $app->input->getArray($_GET);
        $params = array();
        foreach ($post as $key => $value) {
            if ($key != 'task' && $key != 'option' && $key != 'view' && $key != 'pid' && $key != 'cid' && $key != 'Itemid') {
                if ($key == 'search') {
                    $params[] = $key . '=' . urlencode($value);
                } else if (is_array($value)) {
                    foreach ($value as $k => $v) {
                        $params[] = $key . '[]=' . $v;
                    }
                } else {
                    $params[] = $key . '=' . $value;
                }
            }
        }

        $producer_id = $app->input->get('pid', null, 'string');
        if ((int)$producer_id == 0) {
            return $this->search();
        } else {
            if (strpos($producer_id, ':') === false) {
                $db = JFactory::getDbo();
                $db->setQuery('select alias from #__djc2_producers where id =' . (int)$producer_id);
                if ($alias = $db->loadResult()) {
                    $producer_id = (int)$producer_id . ':' . $alias;
                }
            }
        }

        $menu = JFactory::getApplication('site')->getMenu('site');
        $uri = DJCatalogHelperRoute::getProducerRoute($producer_id);
        if (strpos($uri, '?') === false) {
            $get = (count($params)) ? '?' . implode('&', $params) : '';
        } else {
            $get = (count($params)) ? '&' . implode('&', $params) : '';
        }

        $cparams = JComponentHelper::getParams('com_djcatalog2');
        $jumpToSfx = $cparams->get('search_jump', true) ? '#tlb' : '';

        $app->redirect(JRoute::_($uri . $get, false) . $jumpToSfx);
    }

    function mapsearch()
    {
        $app = JFactory::getApplication();
        //$post = JRequest::get('post');
        $post = $app->input->getMethod() == 'POST' ? $app->input->getArray($_POST) : $app->input->getArray($_GET);
        $params = array();
        foreach ($post as $key => $value) {
            if ($key != 'task' && $key != 'option' && $key != 'view' && $key != 'cid' && $key != 'pid' && $key != 'Itemid') {
                if ($key == 'search') {
                    $params[] = $key . '=' . urlencode($value);
                } else if (is_array($value)) {
                    foreach ($value as $k => $v) {
                        $params[] = $key . '[]=' . $v;
                    }
                } else {
                    $params[] = $key . '=' . $value;
                }
            }
        }

        $menu = JFactory::getApplication('site')->getMenu('site');
        //$uri = DJCatalogHelperRoute::getCategoryRoute( $app->input->get( 'cid','0','string' ), $app->input->get( 'pid',null,'string' ));
        $uri = 'index.php?option=com_djcatalog2&view=map';
        if ($app->input->get('cid', false) !== false) {
            $uri .= '&cid=' . $app->input->getInt('cid', 0);
        }
        if ($app->input->get('pid', false) !== false) {
            $uri .= '&pid=' . $app->input->getString('pid', '');
        }
        if ($app->input->get('Itemid', false) !== false) {
            $uri .= '&Itemid=' . $app->input->getInt('Itemid', '');
        }

        if (strpos($uri, '?') === false) {
            $get = (count($params)) ? '?' . implode('&', $params) : '';
        } else {
            $get = (count($params)) ? '&' . implode('&', $params) : '';
        }
        $cparams = JComponentHelper::getParams('com_djcatalog2');
        $jumpToSfx = $cparams->get('search_jump', true) ? '#tlb' : '';

        $app->redirect(JRoute::_($uri . $get, false) . $jumpToSfx);
    }

    function filterproducers()
    {
        $app = JFactory::getApplication();
        $db = JFactory::getDbo();
        //$post = JRequest::get('post');
        $post = $app->input->getMethod() == 'POST' ? $app->input->getArray($_POST) : $app->input->getArray($_GET);
        $params = array();
        foreach ($post as $key => $value) {
            if ($key != 'task' && $key != 'option' && $key != 'view' && $key != 'pcid' && $key != 'Itemid') {
                if ($key == 'search') {
                    $params[] = $key . '=' . urlencode($value);
                } else if (is_array($value)) {
                    foreach ($value as $k => $v) {
                        if (is_numeric($k)) {
                            $params[] = $key . '[]=' . $v;
                        } else {
                            $params[] = $key . '[' . $k . ']=' . $v;
                        }
                    }
                } else {
                    $params[] = $key . '=' . $value;
                }
            }
        }


        if (!array_key_exists('cm', $post) && $app->input->getCmd('task') != 'search_reset') {
            $params[] = 'cm=0';
        }

        $categoryId = $app->input->get('pcid', '0', 'string');
        if (is_numeric($categoryId) && $categoryId > 0 && strstr($categoryId, ':') === false) {
            $query = $db->getQuery(true);
            $query->select('id, alias')->from('#__djc2_producer_categories')->where('id=' . (int)$categoryId);
            $db->setQuery($query);
            $category = $db->loadObject();
            if ($category) {
                $categoryId .= ':' . $category->alias;
            }
        }

        $menu = JFactory::getApplication('site')->getMenu('site');
        $uri = DJCatalogHelperRoute::getProducerCategoryRoute($categoryId);
        if (strpos($uri, '?') === false) {
            $get = (count($params)) ? '?' . implode('&', $params) : '';
        } else {
            $get = (count($params)) ? '&' . implode('&', $params) : '';
        }

        $cparams = JComponentHelper::getParams('com_djcatalog2');
        $jumpToSfx = $cparams->get('search_jump', true) ? '#tlb' : '';

        $app->redirect(JRoute::_($uri . $get, false) . $jumpToSfx);
    }

    function download()
    {
        $app = JFactory::getApplication();
        $user = JFactory::getUser();
        $db = JFactory::getDbo();
        $file_id = $app->input->getInt('fid', 0);

        $query = 'select i.id, i.created_by, f.access, i.product_type ' .
            'from #__djc2_items as i, ' .
            '#__djc2_files as f where f.item_id = i.id and f.id=' . (int)$file_id;
        $db->setQuery($query);
        $itemFile = $db->loadObject();

        if (empty($itemFile)) {
            throw new Exception('', 404);
            return false;
        }

        $owner = $itemFile->created_by;
        $access = $itemFile->access;

        $groups = $user->getAuthorisedViewLevels();

        $authorised = false;
        if (($user->id && $user->id == $owner && $user->id > 0) || $user->authorise('core.admin', 'com_djcatalog2')) {
            $authorised = true;
        } else if ($itemFile->product_type == 'virtual' || $itemFile->product_type == 'hybrid') {
            $token = $app->getUserStateFromRequest('com_djcatalog2.order.token', 'token', null, 'string');
            if ($user->guest == false || $token != '') {
                $query = $db->getQuery(true);
                $query->select('o.*');
                $query->from('#__djc2_orders AS o');
                $query->join('inner', '#__djc2_order_items AS oi ON oi.order_id=o.id');
                if ($user->guest) {
                    $query->where('o.token=' . $db->quote($token));
                } else {
                    $query->where('o.user_id=' . $user->id);
                }
                $query->where('oi.item_id = ' . $itemFile->id);
                $query->order('o.id DESC');

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

                foreach ($fileOrders as $order) {
                    if ($order->status == 'C' || $order->status == 'P' || $order->status == 'F') {
                        $authorised = true;
                        break;
                    }
                }

                if (!$authorised) {
                    if (count($fileOrders) > 0) {
                        $fileOrder = $fileOrders[0];
                        $msg = JText::_('COM_DJCATALOG2_VIRTUAL_PRODUCT_DOWNLOAD_NOT_AUTH');
                        if ($token != '') {
                            $this->setRedirect(JRoute::_(DJCatalog2HelperRoute::getOrderRoute($fileOrder->id) . '&token=' . $token, false), $msg);
                        } else {
                            $this->setRedirect(JRoute::_(DJCatalog2HelperRoute::getOrderRoute($fileOrder->id), false), $msg);
                        }
                        return true;
                    }

                    $itemModel = JModelLegacy::getInstance('Item', 'DJCatalog2Model', ['ignore_request' => true]);
                    $item = $itemModel->getItem($itemFile->id);
                    $msg = JText::_('COM_DJCATALOG2_VIRTUAL_PRODUCT_DOWNLOAD_NOT_AUTH');
                    $this->setRedirect(JRoute::_(DJCatalog2HelperRoute::getItemRoute($item->slug, $item->catslug), false), $msg);
                    return true;
                }
            }
        } else {
            if ($user->authorise('djcatalog2.filedownload', 'com_djcatalog2')) {
                $authorised = (bool)(in_array($access, $groups));
            }
        }

        if ($authorised !== true) {
            if ($user->guest) {
                $return_url = base64_encode(JUri::getInstance()->toString());
                $app->enqueueMessage(JText::_('COM_DJCATALOG2_PLEASE_LOGIN'));
                $app->redirect(JRoute::_('index.php?option=com_users&view=login&return=' . $return_url, false), 303);
                return true;
            } else {
                throw new Exception(JText::_('JERROR_ALERTNOAUTHOR'), 403);
                return false;
            }
        }

        if (!DJCatalog2FileHelper::getFile($file_id)) {
            throw new Exception('', 404);
            return false;
        }

        // Close the application instead of returning from it.
        $app->close();
        //return true;
    }

    public function multiupload()
    {
        $app = JFactory::getApplication();
        // todo: secure upload from injections
        $user = JFactory::getUser();
        if (!$user->authorise('core.manage', 'com_djcatalog2')
            && !$user->authorise('core.create', 'com_djcatalog2')
            && !$user->authorise('core.edit', 'com_djcatalog2')
            && !$user->authorise('core.edit.own', 'com_djcatalog2')
            // not really protection but rather making sure that uploaded file is related to product customisation
            && strpos($app->input->getString('upload_id'), 'customValues_') === false) {
            $app = JFactory::getApplication();
            $app->setHeader('status', 403, true);
            $app->sendHeaders();

            echo '{"jsonrpc" : "2.0", "error" : {"code": 403, "message": "' . JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN') . '"}}';

            $app->close();

        }

        DJCatalog2UploadHelper::upload();

        return true;
    }

    public function getStatesByCountry()
    {
        $app = JFactory::getApplication();
        $country = $app->input->getInt('country');

        $results = array();

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('cs.*')->from('#__djc2_countries_states AS cs')->where('cs.published=1')->order('cs.name asc');

        if ($country > 0) {
            $query->join('inner', '#__djc2_countries AS c ON c.id=cs.country_id AND c.published=1');
            $query->where('cs.country_id=' . (int)$country);
        } else {
            $query->join('inner', '#__djc2_countries AS c ON c.id=cs.country_id AND c.is_default=1 AND c.published=1');
        }

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

        echo json_encode($results);
        $app->close();
    }

    public function paymentProcess()
    {
        $app = JFactory::getApplication();
        $db = JFactory::getDbo();
        $order_id = $app->input->getInt('oid');
        $plugin = $app->input->getString('plg');
        $plugin_id = $app->input->getInt('plgid');

        if (!$order_id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_INVALID_REQUEST'), 400);
        }

        if (!$plugin || !$plugin_id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_INVALID_REQUEST'), 400);
        }

        $model = JModelLegacy::getInstance('Order', 'DJCatalog2Model', array('ignore_request' => true));
        $order = $model->getItem($order_id);
        $paymentMethod = $model->getPaymentMethod($plugin_id);

        if ($order == false || empty($order) || empty($order->id) || $order->payment_method_id != $paymentMethod->id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_ORDER_NOT_FOUND'), 404);
        }

        $transaction = new stdClass();
        $transaction->id = null;
        $transaction->user_id = (int)JFactory::getUser()->id;
        $transaction->order_id = $order_id;
        $transaction->created = JFactory::getDate()->toSql();
        $transaction->paid = 0;
        $transaction->total = $order->grand_total;

        $db->insertObject('#__djc2_transactions', $transaction, 'id');

        JPluginHelper::importPlugin('djcatalog2payment');
        $dispatcher = Joomla\CMS\Factory::getApplication()->getDispatcher();

        // payment processing
        $paymentResponse = Joomla\CMS\Factory::getApplication()->triggerEvent('onDJC2PaymentProcess', array('com_djcatalog2.order.payment', $order, $paymentMethod));

        $app->close();
    }

    public function paymentResponse()
    {
        $app = JFactory::getApplication();
        $plugin = $app->input->getString('plg');
        $plugin_id = $app->input->getInt('plgid');

        if (!$plugin || !$plugin_id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_INVALID_REQUEST'), 400);
        }

        JPluginHelper::importPlugin('djcatalog2payment');
        $dispatcher = Joomla\CMS\Factory::getApplication()->getDispatcher();

        $model = JModelLegacy::getInstance('Order', 'DJCatalog2Model', array('ignore_request' => true));
        $paymentMethod = $model->getPaymentMethod($plugin_id);

        if (!$paymentMethod || $paymentMethod->plugin != $plugin) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_INVALID_REQUEST'), 400);
        }

        $order_id = false;

        // this should go through all the plugins and return order id
        $paymentDiscovery = Joomla\CMS\Factory::getApplication()->triggerEvent('onDJC2PaymentDiscover', array('com_djcatalog2.order.payment', $paymentMethod));
        foreach ($paymentDiscovery as $result) {
            if (!empty($result) && is_numeric($result)) {
                $order_id = (int)$result;
                break;
            }
        }

        if (!$order_id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_ORDER_NOT_FOUND'), 404);
        }

        $order = $model->getItem($order_id);

        if ($order == false || empty($order) || empty($order->id) || $order->payment_method_id != $paymentMethod->id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_ORDER_NOT_FOUND'), 404);
        }

        // payment response validation
        $paymentResponse = Joomla\CMS\Factory::getApplication()->triggerEvent('onDJC2PaymentResponse', array('com_djcatalog2.order.payment', $order, $model, $paymentMethod));

        $app->close();
    }

    public function getUserData()
    {
        $app = JFactory::getApplication();
        $juser = JFactory::getUser();
        $salesman = $juser->authorise('djcatalog2.salesman', 'com_djcatalog2') || $juser->authorise('core.admin', 'com_djcatalog2');

        if (!$salesman) {
            throw new Exception(JText::_('JERROR_ALERTNOAUTHOR'), 403);
        }

        $user_id = $app->input->getInt('user_id');
        if (!$user_id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_INVALID_REQUEST'), 400);
        }

        $user = Djcatalog2Helper::getUser($user_id);
        echo json_encode($user);
        $app->close();

    }

    public function user_login()
    {
        JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

        $app = JFactory::getApplication();
        $input = $app->input;
        $method = $input->getMethod();

        // Populate the data array:
        $data = array();

        $data['return'] = base64_decode($app->input->post->get('return', '', 'BASE64'));
        $data['username'] = $input->$method->get('username', '', 'USERNAME');
        $data['password'] = $input->$method->get('password', '', 'RAW');
        $data['secretkey'] = $input->$method->get('secretkey', '', 'RAW');

        // Check for a simple menu item id
        if (is_numeric($data['return'])) {
            if (JLanguageMultilang::isEnabled()) {

                $db = JFactory::getDbo();
                $query = $db->getQuery(true)
                    ->select('language')
                    ->from($db->quoteName('#__menu'))
                    ->where('client_id = 0')
                    ->where('id =' . $data['return']);

                $db->setQuery($query);

                try {
                    $language = $db->loadResult();
                } catch (RuntimeException $e) {
                    return;
                }

                if ($language !== '*') {
                    $lang = '&lang=' . $language;
                } else {
                    $lang = '';
                }
            } else {
                $lang = '';
            }

            $data['return'] = 'index.php?Itemid=' . $data['return'] . $lang;
        } else {
            // Don't redirect to an external URL.
            if (!JUri::isInternal($data['return'])) {
                $data['return'] = '';
            }
        }

        // Set the return URL if empty.
        if (empty($data['return'])) {
            $data['return'] = DJCatalog2HelperRoute::getCartRoute() . '&layout=login';
        }

        // Set the return URL in the user state to allow modification by plugins
        $app->setUserState('users.login.form.return', $data['return']);

        // Get the log in options.
        $options = array();
        $options['remember'] = $this->input->getBool('remember', false);
        $options['return'] = $data['return'];

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

        // Perform the log in.
        if (true !== $app->login($credentials, $options)) {
            // Login failed !
            // Clear user name, password and secret key before sending the login form back to the user.
            $data['remember'] = (int)$options['remember'];
            $data['username'] = '';
            $data['password'] = '';
            $data['secretkey'] = '';
            $app->setUserState('users.login.form.data', $data);
            $app->redirect(JRoute::_(DJCatalog2HelperRoute::getCartRoute() . '&layout=login', false));
        }

        // Success
        if ($options['remember'] == true) {
            $app->setUserState('rememberLogin', true);
        }

        $app->setUserState('users.login.form.data', array());
        $app->redirect(JRoute::_($app->getUserState('users.login.form.return'), false));
    }

    public function user_register()
    {
        JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
        $app = JFactory::getApplication();
        $app->setUserState('com_djcatalog2.cart_registration', true);

        // TODO: should we do sth about that?
        //require_once JPATH_ROOT.'/components/com_users/helpers/route.php';

        //$link = 'index.php?option=com_users&view=registration&from_cart=1';
        //$link = 'index.php?option=com_users&view=registration&from_cart=1&Itemid='. UsersHelperRoute::getRegistrationRoute() . '&from_cart=1';
        $link = 'index.php?option=com_users&view=registration&from_cart=1';

        $this->setRedirect(JRoute::_($link, false));
        return true;
    }

    public function getFilterModules()
    {
        $app = JFactory::getApplication();

        $moduleIds = $app->input->get('module_id', array(), 'array');

        Joomla\Utilities\ArrayHelper::toInteger($moduleIds);

        if (empty($moduleIds)) {
            $app->close();
        }

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('*')->from('#__modules')->where('client_id=0')->where('id IN (' . implode(',', $moduleIds) . ')');
        $db->setQuery($query);

        $modules = $db->loadObjectList('id');

        if (empty($modules)) {
            $app->close();
        }

        JUri::getInstance()->setVar('task', null);
        $app->input->set('task', null);

        $output = '';
        foreach ($modules as $module) {
            $output .= '<div data-filtersmodule="' . $module->id . '">' . JModuleHelper::renderModule($module) . '</div>';
        }

        echo '<div>' . $output . '</div>';
        $app->close();

        /*require_once (JPATH_BASE.'/modules/mod_djc2filters/helper.php');

        $lang = JFactory::getLanguage();

        $lang->load('mod_djc2filters', JPATH_BASE, null, false, true) ||
        $lang->load('mod_djc2filters', JPATH_BASE.'/modules/mod_djc2filters', null, false, true);

        $output = array();
        foreach($modules as $module) {
            $params = new Registry($module->params);
            $items = DJC2FiltersModuleHelper::getData($params);

            ob_start();
            require JModuleHelper::getLayoutPath('mod_djc2filters', $params->get('layout', 'default'));
            $output[] = ob_get_contents();
            ob_end_clean();
        }

        echo json_encode($output);
        */
        $app->close();
    }

    public function cronjobs()
    {
        $params = JComponentHelper::getParams('com_djcatalog2');

        if ($params->get('cron_recurring')) {
            $this->processRecurringOrders();
        }
        if ($params->get('cron_abandonedcart')) {
            $this->userCartsNotify();
        }
        if ($params->get('cron_unpaid')) {
            $this->unPaidOrdersNotify();
        }
        if ($params->get('cron_rate') && $params->get('product_rating')) {
            $this->rateOrdersNotify();
        }




        JFactory::getApplication()->close();
    }

    public function calculateAveragePrices()
    {
        $app = Factory::getApplication();
        $start = $app->input->get('start', 0);
        $limit = $app->input->get('limit', 50);


        // Calculate avg prices by days
        $db = JFactory::getDbo();
        $params = JComponentHelper::getParams('com_djcatalog2');
        $pricesDateFrom = date("Y-m-d", strtotime('now - ' . $params->get('cron_lowest_prices_delay') . ' days'));


        $query = $db->getQuery(true);
        $query
            ->select([
                'i.id',
                'i.name'
            ])->from($db->quoteName('#__djc2_items','i'))
            ->order('id ASC')
            ->setLimit($limit, $start);

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


        if(count($items)) {

            echo '<table>';
            echo '<thead><th>Name</th><th>Price</th></thead>';
            $model = JModelLegacy::getInstance('Item', 'DJCatalog2Model');
            $today = date('Y-m-d');
            $columns = ['item_id', 'combination_id', 'price', 'date'];
            foreach ($items as $item) {




                $calculatedItem = $model->getItem($item->id);
                $combinations = $model->getCombinations($item->id);

                $query = $db->getQuery(true);
                $values = array($item->id, 0, $calculatedItem->final_price, $db->quote($today));
                $query
                    ->insert($db->quoteName('#__djc2_items_avg_prices'))
                    ->columns($db->quoteName($columns))
                    ->values(implode(',', $values));

                $query .= ' on duplicate key update price = ' . $calculatedItem->price;

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

                // Recalculate avg price of item
                $db->setQuery('SELECT min(price) as lowest_price, count(item_id) as number_of_days FROM #__djc2_items_avg_prices WHERE item_id = ' . (int)$item->id . ' AND combination_id = 0 AND date >= ' . $db->quote($pricesDateFrom) . ' AND date <= ' . $db->quote($today));
                $lowestPrice = $db->loadObject();

                echo '<tr>';
                echo '<td>' . $item->name . '</td>';
                echo '<td>' . $lowestPrice->lowest_price . '</td>';
                echo '<tr>';

                $db->setQuery('UPDATE #__djc2_items SET avg_price = ' . $lowestPrice->lowest_price . ', avg_of_days = ' . $lowestPrice->number_of_days . ' WHERE id = ' . $item->id);
                $db->execute();


                if (count($combinations)) {
                    foreach ($combinations as $combination) {

                        $query = $db->getQuery(true);
                        $values = array($item->id, $combination->id, $calculatedItem->final_price, $db->quote($today));
                        $query
                            ->insert($db->quoteName('#__djc2_items_avg_prices'))
                            ->columns($db->quoteName($columns))
                            ->values(implode(',', $values));
                        $query .= ' on duplicate key update price = ' . $calculatedItem->price;


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

                        // Recalculate item lowest_price
                        // Recalculate avg price of item
                        $db->setQuery('SELECT min(price) as lowest_price, count(item_id) as number_of_days FROM #__djc2_items_avg_prices WHERE item_id = ' . (int)$item->id . ' AND combination_id = ' . $combination->id . ' AND date >= ' . $db->quote($pricesDateFrom) . ' AND date <= ' . $db->quote($today));
                        $lowestPrice = $db->loadObject();

                        echo '<tr>';
                        echo '<td>' . $item->name . '(#' . $combination->id . ')</td>';
                        echo '<td>' . $lowestPrice->lowest_price . '</td>';
                        echo '<tr>';

                        $db->setQuery('UPDATE #__djc2_items_combinations SET avg_price = ' . $lowestPrice->lowest_price . ', avg_of_days = ' . $lowestPrice->number_of_days . ' WHERE id = ' . (int)$combination->id);
                        $db->execute();
                    }

                }



                $start++;
            }

            echo '</table>';

            header( "refresh:2;url=index.php?option=com_djcatalog2&task=calculateAveragePrices&start=" . $start );
        }
        exit();
    }

    protected function userCartsNotify()
    {
        require_once(JPATH_ROOT . '/administrator/components/com_djcatalog2/helpers/messenger.php');

        $app = JFactory::getApplication();
        $db = JFactory::getDbo();

        $session_time = $app->getCfg('lifetime', '30');

        $query = $db->getQuery(true);
        $query->select('uc.*, u.email');
        $query->from('#__djc2_usercarts AS uc');
        $query->join('INNER', '#__users AS u ON uc.user_id = u.id');
        $query->where('uc.time < now() - INTERVAL ' . $session_time . ' MINUTE AND uc.email_sent IS NULL');

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

        foreach ($usercarts as $usercart) {
            $items = json_decode((string)$usercart->items);
            $ids = [];
            foreach ($items as $key => $qty) {
                $temp = explode('.', $key, 2);
                if (isset($temp[0])) {
                    $ids[$temp[0]] = $qty;
                }
            }

            if (!empty($ids)) {
                $query = $db->getQuery(true);
                $query->select('i.id, i.alias, i.name, i.cat_id, c.alias as category_alias');
                $query->from('#__djc2_items as i');
                $query->join('inner', '#__djc2_categories as c ON c.id=i.cat_id');
                $query->where('i.id IN (' . implode(',', array_keys($ids)) . ')');
                $db->setQuery($query);
                $list = $db->loadObjectList('id');

                if (count($list) > 0) {
                    $data = array();
                    $data['items'] = $list;
                    $data['quantities'] = $ids;


                    $mailopts = [
                        'cart_link' => JRoute::_(DJCatalog2HelperRoute::getCartRoute(), true, (JUri::getInstance()->isSsl() ? 1 : -1)),
                        'cart_items' => DJCatalog2HtmlHelper::getThemeLayout($data, 'cart_items', 'email/layouts')
                    ];

                    $messenger = new DJCatalog2HelperMessenger();
                    $messenger->notify($usercart->email, ['type' => 'cart_abandoned'], [], $mailopts);
                }
            }

            $query = $db->getQuery(true);
            $query->update('#__djc2_usercarts');
            $query->set('email_sent=NOW()');
            $query->where('user_id=' . $usercart->user_id);
            $db->setQuery($query);
            $db->execute();
        }
        return true;
    }

    protected function unPaidOrdersNotify()
    {
        require_once(JPATH_ROOT . '/administrator/components/com_djcatalog2/helpers/messenger.php');

        $app = JFactory::getApplication();
        $db = JFactory::getDbo();
        $params = JComponentHelper::getParams('com_djcatalog2');
        $status1 = $params->get('cart_status_new_reg', 'A');
        $status2 = $params->get('cart_status_new_guest', 'N');

        $daysOld = (int)$params->get('cron_upaid_days', 1);
        $daysOld = min(30, max(1, $daysOld));

        $maxDate = JFactory::getDate('-' . $daysOld . ' day');
        $minDate = JFactory::getDate('-31 days');

        $query = $db->getQuery(true);
        $query->select('o.*');
        $query->from('#__djc2_orders AS o');
        // leaving room for more notifications to send
        $query->where('(o.paynotify_cnt != -1 AND o.paynotify_cnt < 1)');
        // give them some time
        $query->where('o.created_date < ' . $db->quote($maxDate->toSql()));
        // ... but let's be serious
        $query->where('o.created_date >= ' . $db->quote($minDate->toSql()));
        // include only "new" statuses
        $query->where('( o.status = ' . $db->quote($status1) . ' OR o.status = ' . $db->quote($status2) . ') ');


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

        foreach ($orders as $order) {
            $mailopts = [
                'recipient_name' => ($order->firstname != '') ? $order->firstname : ($order->lastname != '' ? $order->lastname : $order->company),
                'order_link' => JRoute::_(DJCatalog2HelperRoute::getOrderRoute($order->id) . '&token=' . $order->token, true, (JUri::getInstance()->isSsl() ? 1 : -1)),
                'order_number' => str_pad($order->order_number, 6, '0', STR_PAD_LEFT)

            ];

            $messenger = new DJCatalog2HelperMessenger();
            $messenger->notify($order->email, ['type' => 'order_payment'], [], $mailopts);

            $query = $db->getQuery(true);
            $query->update('#__djc2_orders');
            $query->set('paynotify_cnt = paynotify_cnt + 1');
            $query->where('id=' . $order->id);
            $db->setQuery($query);
            $db->execute();
        }
        return true;
    }

    protected function rateOrdersNotify()
    {
        require_once(JPATH_ROOT . '/administrator/components/com_djcatalog2/helpers/messenger.php');

        $app = JFactory::getApplication();
        $db = JFactory::getDbo();
        $params = JComponentHelper::getParams('com_djcatalog2');
        $invoiceStatuses = (array)$params->get('cart_status_invoice', array('C', 'P', 'F'));

        $orStatuses = [];
        foreach ($invoiceStatuses as $status) {
            $orStatuses[] = 'o.status = ' . $db->quote($status);
        }
        if (empty($orStatuses)) return;

        $daysOld = (int)$params->get('cron_rating_days', 1);
        $daysOld = min(30, max(1, $daysOld));

        $maxDate = JFactory::getDate('-' . $daysOld . ' day');
        $minDate = JFactory::getDate('-31 day');


        $query = $db->getQuery(true);
        $query->select('o.*');
        $query->from('#__djc2_orders AS o');
        // leaving room for more notifications to send
        $query->where('(o.ratingnotify_cnt != -1 AND o.ratingnotify_cnt < 1)');
        // give them some time
        $query->where('o.created_date < ' . $db->quote($maxDate->toSql()));
        // ... but let's be serious
        $query->where('o.created_date >= ' . $db->quote($minDate->toSql()));
        // include only "completed" statuses
        $query->where('( ' . implode(' OR ', $orStatuses) . ' )');
        // only registered user are able to rate order items
        $query->where('o.user_id > 0');


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

        foreach ($orders as $order) {
            $data = Joomla\Utilities\ArrayHelper::fromObject($order);

            $query = $db->getQuery(true);
            $query->select('oi.*');
            $query->from('#__djc2_order_items AS oi');
            $query->where('oi.order_id=' . $order->id);
            $db->setQuery($query);
            $data['items'] = $db->loadAssocList();

            if (count($data['items'])) {
                $mailopts = [
                    'recipient_name' => ($order->firstname != '') ? $order->firstname : ($order->lastname != '' ? $order->lastname : $order->company),
                    'order_link' => JRoute::_(DJCatalog2HelperRoute::getOrderRoute($order->id) . '&layout=rating&token=' . $order->token, true, (JUri::getInstance()->isSsl() ? 1 : -1)),
                    'order_number' => str_pad($order->order_number, 6, '0', STR_PAD_LEFT),
                    'order_items' => DJCatalog2HtmlHelper::getThemeLayout($data, 'order_items', 'email/layouts')
                ];

                $messenger = new DJCatalog2HelperMessenger();
                $messenger->notify($order->email, ['type' => 'order_rating'], [], $mailopts);
            }

            $query = $db->getQuery(true);
            $query->update('#__djc2_orders');
            $query->set('ratingnotify_cnt = ratingnotify_cnt + 1');
            $query->where('id=' . $order->id);
            $db->setQuery($query);
            $db->execute();
        }
        return true;
    }

    protected function processRecurringOrders() {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('ro.id, ro.order_id, ro.start');
        $query->from('#__djc2_orders_recurring AS ro');
        $query->join('left', '#__djc2_orders_recurring AS ro2 ON ro2.id != ro.id AND ro2.start > ro.start AND ro2.order_id = ro.order_id AND ro2.executed=0');
        $query->where('ro.executed=0');
        $query->where('ro.start <= ' . $db->quote(JFactory::getDate()->toSql()));
        $query->group('ro.order_id');
        $db->setQuery($query);

        $orders = $db->loadObjectList();

        if (!count($orders)) {
            return;
        }

        $model = $this->getModel('Order', 'DJCatalog2Model');

        foreach($orders as $orderRepeat) {
            $order = $model->getItem($orderRepeat->order_id);

            if (empty($order)) {
                continue;
            }

            if ($model->repeatOrder($order)) {
                $query = $db->getQuery(true);
                $query->update('#__djc2_orders_recurring')->set('executed=1')->where('id='.$orderRepeat->id);
                $db->setQuery($query);
                $db->execute();
            }
        }
    }

    private function importTCPDF()
    {
        $libfile = JPATH_LIBRARIES . '/tcpdf/tcpdf.php';
        if (JFile::exists($libfile) == false) {
            return false;
        }

        require_once $libfile;
        return true;
    }

    public function getInvoice()
    {

        $user = JFactory::getUser();
        $db = JFactory::getDbo();
        $app = JFactory::getApplication();
        $invoice_id = $app->input->getInt('oid', false);

        $return_url = base64_encode(JRoute::_(DJCatalogHelperRoute::getOrdersRoute(), false));

        if (!$invoice_id) {
            throw new Exception(JText::_('COM_DJCATALOG2_ERROR_INVALID_REQUEST'), 400);
        }

        if ($user->guest) {
            $app->enqueueMessage(JText::_('COM_DJCATALOG2_PLEASE_LOGIN'));
            $app->redirect(JRoute::_('index.php?option=com_users&view=login&return=' . $return_url, false), 303);
            return false;
        }

        $model = $this->getModel('Order', 'DJCatalog2Model');
        $salesman = $user->authorise('djcatalog2.salesman', 'com_djcatalog2');

        $invoice = $model->getItem($invoice_id);
        if ($invoice->user_id != $user->id && !($user->authorise('core.admin') || $salesman)) {
            throw new Exception(JText::_('JERROR_ALERTNOAUTHOR'), 403);
        }

        if (!$this->importTCPDF()) {
            $this->setRedirect(JRoute::_(DJCatalogHelperRoute::getOrdersRoute(), false), JText::_('COM_DJCATALOG2_TCPDF_LIB_IS_MISSING'), 'error');
            return false;
        }

        $filename = JFile::makeSafe('invoice-' . str_replace('/', '-', $invoice->invoice_number)) . '.pdf';

        $task = $this->getTask();
        $layout = ($task == 'proforma_selected') ? 'proforma' : 'invoice';

        error_reporting(0);
        @ini_set('display_errors', 0);

        $pdf = new TCPDF();

        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->setFontSubsetting(true);

        $pdf->SetFont('freesans', '', 9, '', true);
        $pdf->SetPrintHeader(false);
        $pdf->SetPrintFooter(true);
        $pdf->SetFooterMargin('15px');

        $db = JFactory::getDbo();

        $db->setQuery('select * from #__djc2_order_items where order_id=' . $invoice->id);
        $invoice->items = $db->loadObjectList();

        $pdf->AddPage();
        $pdf->_intCurPage = 1;
        $pdf->_intFootNo = $invoice->invoice_number;
        $html = DJCatalog2HtmlHelper::getThemeLayout($invoice, $layout, 'pdf');
        $pdf->writeHTML($html, true, false, true, false, '');

        $pdf->Output($filename, 'D');

        $app->close();
    }

    public function pixelMsg()
    {
        $app = JFactory::getApplication();
        $pixel = $app->input->getInt('pixel');
        $code = $app->input->getString('code');

        if ($pixel > 0 && $code != '') {
            $code = base64_decode($code);

            $db = JFactory::getDbo();
            $query = $db->getQuery(true);
            $query->update('#__djc2_messages');
            $query->set('is_opened=1');
            $query->where('id=' . (int)$pixel);
            $query->where('sent_time=' . $db->quote($code));
            $db->setQuery($query);
            $db->execute();
        }

        header('Content-Type: image/gif');
        readfile(JPATH_ROOT . '/media/djcatalog2/assets/tracking.gif');

        $app->close();
    }

    public function accesslogin()
    {
        $app = JFactory::getApplication();
        $user = JFactory::getUser();
        $id = $app->input->getInt('id');

        $response = [
            'redirect' => false,
            'body' => '',
            'message' => '',
            'error' => false
        ];

        if ($user->guest) {
            $module = JModuleHelper::getModule('mod_login', 'Please login!');
            $response['body'] = JModuleHelper::renderModule($module);
        } else {
            $orders = Djcatalog2HelperUser::getUserOrders($user->id);
            $auth = false;
            if (!empty($orders['items'])) {
                foreach ($orders['items'] as $purchasedItem) {
                    if ($purchasedItem->item_type != 'item' || $purchasedItem->item_id != $id) continue;
                    $auth = true;
                    break;
                }
            }

            if (!$auth) {
                $response['message'] = JText::_('COM_DJCATALOG2_AUTH_ERROR_ORDER_NOT_AUTHORISED');
            } else {
                $response['message'] = JText::_('COM_DJCATALOG2_AUTH_MSG_ALREADY_LOGGED_IN_REDIRECT');
                $response['redirect'] = JUri::current();
            }
        }


        echo json_encode($response);
        $app->close();
    }

    function select_currency()
    {
        $app = JFactory::getApplication();
        $return = $app->input->getBase64('return');
        $currency_id = $app->input->getInt('currency');

        $currency = Djcatalog2HelperPrice::getCurrencyById($currency_id);
        if (!empty($currency)) {
            $app->setUserState('com_djcatalog2.checkout.currency', $currency->id);
        }

        if ($return) {
            $this->setRedirect(base64_decode($return));
        }

        return true;
    }
}

Anon7 - 2022
AnonSec Team