Your IP : 216.73.216.61


Current Path : /home/w/u/e/wuectly/www/03cbe/
Upload File :
Current File : /home/w/u/e/wuectly/www/03cbe/models.tar

index.html000060400000000054152455230470006543 0ustar00<html><body bgcolor="#FFFFFF"></body></html>sitemap.php000060400000023144152455230470006726 0ustar00<?php

/**
 * @version       $Id$
 * @copyright     Copyright (C) 2005 - 2009 Joomla! Vargas. All rights reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @author        Guillermo Vargas (guille@vargas.co.cr)
 */
// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.modelitem');
jimport('joomla.database.query');
require_once(JPATH_COMPONENT . '/helpers/xmap.php');

/**
 * Xmap Component Sitemap Model
 *
 * @package        Xmap
 * @subpackage     com_xmap
 * @since          2.0
 */
class XmapModelSitemap extends JModelItem
{

    /**
     * Model context string.
     *
     * @var        string
     */
    protected $_context = 'com_xmap.sitemap';
    protected $_extensions = null;

    static $items = array();
    /**
     * Method to auto-populate the model state.
     *
     * @return     void
     */
    protected function populateState()
    {
        $app = JFactory::getApplication('site');

        // Load state from the request.
        $pk = JRequest::getInt('id');
        $this->setState('sitemap.id', $pk);

        $offset = JRequest::getInt('limitstart');
        $this->setState('list.offset', $offset);

        // Load the parameters.
        $params = $app->getParams();
        $this->setState('params', $params);

        // TODO: Tune these values based on other permissions.
        $this->setState('filter.published', 1);
        $this->setState('filter.access', true);
    }

    /**
     * Method to get sitemap data.
     *
     * @param    integer    The id of the article.
     *
     * @return   mixed      Menu item data object on success, false on failure.
     */
    public function &getItem($pk = null)
    {
        // Initialize variables.
        $db = $this->getDbo();
        $pk = (!empty($pk)) ? $pk : (int) $this->getState('sitemap.id');

        // If not sitemap specified, select the default one
        if (!$pk) {
            $query = $db->getQuery(true);
            $query->select('id')->from('#__xmap_sitemap')->where('is_default=1');
            $db->setQuery($query);
            $pk = $db->loadResult();
        }

        if ($this->_item === null) {
            $this->_item = array();
        }

        if (!isset($this->_item[$pk])) {
            try {
                $query = $db->getQuery(true);

                $query->select($this->getState('item.select', 'a.*'));
                $query->from('#__xmap_sitemap AS a');

                $query->where('a.id = ' . (int) $pk);

                // Filter by published state.
                $published = $this->getState('filter.published');
                if (is_numeric($published)) {
                    $query->where('a.state = ' . (int) $published);
                }

                // Filter by access level.
                if ($access = $this->getState('filter.access')) {
                    $user = JFactory::getUser();
                    $groups = implode(',', $user->getAuthorisedViewLevels());
                    $query->where('a.access IN (' . $groups . ')');
                }

                $this->_db->setQuery($query);

                $data = $this->_db->loadObject();

                if ($error = $this->_db->getErrorMsg()) {
                    throw new Exception($error);
                }

                if (empty($data)) {
                    throw new Exception(JText::_('COM_XMAP_ERROR_SITEMAP_NOT_FOUND'));
                }

                // Check for published state if filter set.
                if (is_numeric($published) && $data->state != $published) {
                    throw new Exception(JText::_('COM_XMAP_ERROR_SITEMAP_NOT_FOUND'));
                }

                // Convert parameter fields to objects.
                $registry = new JRegistry('_default');
                $registry->loadString($data->attribs);
                $data->params = clone $this->getState('params');
                $data->params->merge($registry);

                // Convert the selections field to an array.
                $registry = new JRegistry('_default');
                $registry->loadString($data->selections);
                $data->selections = $registry->toArray();

                // Compute access permissions.
                if ($access) {
                    // If the access filter has been set, we already know this user can view.
                    $data->params->set('access-view', true);
                } else {
                    // If no access filter is set, the layout takes some responsibility for display of limited information.
                    $user = &JFactory::getUser();
                    $groups = $user->authorisedLevels();

                    $data->params->set('access-view', in_array($data->access, $groups));
                }
                // TODO: Type 2 permission checks?

                $this->_item[$pk] = $data;
            } catch (Exception $e) {
                $this->setError($e->getMessage());
                $this->_item[$pk] = false;
            }
        }

        return $this->_item[$pk];
    }

    public function getItems()
    {
        if ($item = $this->getItem()) {
            return XmapHelper::getMenuItems($item->selections);
        }
        return false;
    }

    function getExtensions()
    {
        return XmapHelper::getExtensions();
    }

    /**
     * Increment the hit counter for the sitemap.
     *
     * @param    int        Optional primary key of the sitemap to increment.
     *
     * @return   boolean    True if successful; false otherwise and internal error set.
     */
    public function hit($count)
    {
        // Initialize variables.
        $pk = (int) $this->getState('sitemap.id');

        $view = JRequest::getCmd('view', 'html');
        if ($view != 'xml' && $view != 'html') {
            return false;
        }

        $this->_db->setQuery(
            'UPDATE #__xmap_sitemap' .
            ' SET views_' . $view . ' = views_' . $view . ' + 1, count_' . $view . ' = ' . $count . ', lastvisit_' . $view . ' = ' . JFactory::getDate()->toUnix() .
            ' WHERE id = ' . (int) $pk
        );

        if (!$this->_db->query()) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }

        return true;
    }

    public function getSitemapItems($view=null)
    {
        if (!isset($view)) {
            $view = JRequest::getCmd('view');
        }
        $db = JFactory::getDBO();
        $pk = (int) $this->getState('sitemap.id');

        if (self::$items !== NULL && isset(self::$items[$view])) {
            return;
        }
        $query = "select * from #__xmap_items where view='$view' and sitemap_id=" . $pk;
        $db->setQuery($query);
        $rows = $db->loadObjectList();
        self::$items[$view] = array();
        foreach ($rows as $row) {
            self::$items[$view][$row->itemid] = array();
            self::$items[$view][$row->itemid][$row->uid] = array();
            $pairs = explode(';', $row->properties);
            foreach ($pairs as $pair) {
                if (strpos($pair, '=') !== FALSE) {
                    list($property, $value) = explode('=', $pair);
                    self::$items[$view][$row->itemid][$row->uid][$property] = $value;
                }
            }
        }
        return self::$items;
    }

    function chageItemPropery($uid, $itemid, $view, $property, $value)
    {
        $items = $this->getSitemapItems($view);
        $db = JFactory::getDBO();
        $pk = (int) $this->getState('sitemap.id');

        $isNew = false;
        if (empty($items[$view][$itemid][$uid])) {
            $items[$view][$itemid][$uid] = array();
            $isNew = true;
        }
        $items[$view][$itemid][$uid][$property] = $value;
        $sep = $properties = '';
        foreach ($items[$view][$itemid][$uid] as $k => $v) {
            $properties .= $sep . $k . '=' . $v;
            $sep = ';';
        }
        if (!$isNew) {
            $query = 'UPDATE #__xmap_items SET properties=\'' . $db->escape($properties) . "' where uid='" . $db->escape($uid) . "' and itemid=$itemid and view='$view' and sitemap_id=" . $pk;
        } else {
            $query = 'INSERT #__xmap_items (uid,itemid,view,sitemap_id,properties) values ( \'' . $db->escape($uid) . "',$itemid,'$view',$pk,'" . $db->escape($properties) . "')";
        }
        $db->setQuery($query);
        //echo $db->getQuery();exit;
        if ($db->query()) {
            return true;
        } else {
            return false;
        }
    }

    function toggleItem($uid, $itemid)
    {
        $app = JFactory::getApplication('site');
        $sitemap = $this->getItem();

        $displayer = new XmapDisplayer($app->getParams(), $sitemap);

        $excludedItems = $displayer->getExcludedItems();
        if (isset($excludedItems[$itemid])) {
            $excludedItems[$itemid] = (array) $excludedItems[$itemid];
        }
        if (!$displayer->isExcluded($itemid, $uid)) {
            $excludedItems[$itemid][] = $uid;
            $state = 0;
        } else {
            if (is_array($excludedItems[$itemid]) && count($excludedItems[$itemid])) {
                $excludedItems[$itemid] = array_filter($excludedItems[$itemid], create_function('$var', 'return ($var != \'' . $uid . '\');'));
            } else {
                unset($excludedItems[$itemid]);
            }
            $state = 1;
        }

        $registry = new JRegistry('_default');
        $registry->loadArray($excludedItems);
        $str = $registry->toString();

        $db = JFactory::getDBO();
        $query = "UPDATE #__xmap_sitemap set excluded_items='" . $db->escape($str) . "' where id=" . $sitemap->id;
        $db->setQuery($query);
        $db->query();
        return $state;
    }

}
mailjet.php000060400000005177152455302470006717 0ustar00<?php
/**
 * @author Mailjet SAS
 *
 * @copyright  Copyright (C) 2014 Mailjet SAS.
 * @license    GNU General Public License version 2 or later; see LICENSE
 */
defined('_JEXEC') or die();

if (!defined('DS')) {
  define('DS',DIRECTORY_SEPARATOR);
}

jimport('joomla.application.component.model');

if (!function_exists('class_alias')) { // For php older then 5.3
  function class_alias($orig, $alias) {
    eval('abstract class ' . $alias . ' extends ' . $orig . ' {}');
  }
}

if (!class_exists('JModelLegacy')) {
  class_alias('JModel','JModelLegacy');
}

/* Require the Mailjet API library */
require_once (sPrintF ('%s/components/com_mailjet/lib/lib/mailjet-api-strategy.php', JPATH_ADMINISTRATOR));

class MailjetModelMailjet extends JModelLegacy {

    protected $api;
    protected $params;

    function __construct()
    {
        parent::__construct();
        $this->params = $this->getAsRecord();
        $this->api = new Mailjet_Api($this->params['username'], $this->params['password']);				
    }
	
    function store(){
    	// Get the data which we'll save
        $email = filter_var($_POST['mailjet-email'], FILTER_SANITIZE_EMAIL);
        $list_id = filter_var($_POST['mailjet-list_id'], FILTER_SANITIZE_NUMBER_INT);
        if (empty($email)) $email = filter_var($_GET['mailjet-email'], FILTER_SANITIZE_EMAIL);
        if (empty($list_id)) $list_id = filter_var($_GET['mailjet-list_id'], FILTER_SANITIZE_NUMBER_INT);
        if ((empty($email)) || (empty($list_id))) return false;
	
		// Add the contact to the contact list
        $response = $this->api->addContact(array(
            'Email' => $email,
            'ListID' => $list_id
        ));
		
        if(isset($response->Status) && $response->Status == 'OK')
            return true;
        return false;
    }

    public function getAsRecord ()
    {
        //Below are some comments containing error messages to improve usability
        $credentials = sPrintF ('%s/components/%s/lib/db/data', JPATH_ADMINISTRATOR, 'com_mailjet');

        if(file_exists($credentials)){
            
            $pre_data = null;
            $content = trim(file_get_contents($credentials));
            
            if ($content) {
                $pre_data = json_decode($content);
            }

            /*if(!$pre_data->apiKey || !$pre_data->apiSecret){
                JError::raiseWarning( 100, JText::_("COM_MAILJET_INCOMPLETE_INFO") );
            }*/

            $data ['username'] = $pre_data->apiKey;
            $data ['password'] = $pre_data->apiSecret;

            return $data;
		}
        /*else{
            JError::raiseWarning( 100, JText::_("COM_MAILJET_NO_DATAFILE") );
        }*/
    }
}
forms/filter_contacts.xml000060400000007205152455302730011605 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>

	<fields name="filter">

		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_CONTACT_FILTER_SEARCH_LABEL"
			description="COM_CONTACT_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="published"
			type="status"
			label="JOPTION_SELECT_PUBLISHED"
			description="JOPTION_SELECT_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="category_id"
			type="category"
			label="JOPTION_FILTER_CATEGORY"
			description="JOPTION_FILTER_CATEGORY_DESC"
			extension="com_contact"
			published="0,1,2"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_CATEGORY</option>
		</field>

		<field
			name="access"
			type="accesslevel"
			label="JOPTION_FILTER_ACCESS"
			description="JOPTION_FILTER_ACCESS_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_ACCESS</option>
		</field>

		<field
			name="language"
			type="contentlanguage"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>

		<field
			name="tag"
			type="tag"
			label="JOPTION_FILTER_TAG"
			description="JOPTION_FILTER_TAG_DESC"
			mode="nested"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_TAG</option>
		</field>

		<field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="10"
			step="1"
			languages="*"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
		</field>
	</fields>

	<fields name="list">

		<field
			name="fullordering"
			type="list"
			label="COM_CONTACT_LIST_FULL_ORDERING"
			description="COM_CONTACT_LIST_FULL_ORDERING_DESC"
			default="a.name ASC"
			onchange="this.form.submit();"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.published ASC">JSTATUS_ASC</option>
			<option value="a.published DESC">JSTATUS_DESC</option>
			<option value="a.featured ASC">JFEATURED_ASC</option>
			<option value="a.featured DESC">JFEATURED_DESC</option>
			<option value="a.name ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.name DESC">JGLOBAL_TITLE_DESC</option>
			<option value="category_title ASC">JCATEGORY_ASC</option>
			<option value="category_title DESC">JCATEGORY_DESC</option>
			<option value="ul.name ASC">COM_CONTACT_FIELD_LINKED_USER_LABEL_ASC</option>
			<option value="ul.name DESC">COM_CONTACT_FIELD_LINKED_USER_LABEL_DESC</option>
			<option value="access_level ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="access_level DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option
				value="association ASC"
				requires="associations"
				>
				JASSOCIATIONS_ASC
			</option>
			<option
				value="association DESC"
				requires="associations"
				>
				JASSOCIATIONS_DESC
			</option>
			<option value="language_title ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="language_title DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="COM_CONTACT_LIST_LIMIT"
			description="COM_CONTACT_LIST_LIMIT_DESC"
			default="25"
			class="input-mini"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/form.xml000060400000037134152455302730007371 0ustar00<?xml version="1.0" encoding="UTF-8"?>
<!-- @deprecated  4.0  Not used since 1.6 No replacement. -->
<form>
	<fieldset>
		<field
			name="id"
			type="hidden"
			label="COM_CONTACT_ID_LABEL"
			default="0"
			readonly="true"
			required="true"
			size="10"
		/>

		<field
			name="name"
			type="text"
			label="CONTACT_NAME_LABEL"
			description="CONTACT_NAME_DESC"
			required="true"
			size="30"
		/>

		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			hint="JFIELD_ALIAS_PLACEHOLDER"
			size="30"
		/>

		<field
			name="user_id"
			type="user"
			label="CONTACT_LINKED_USER_LABEL"
			description="CONTACT_LINKED_USER_DESC"
		/>

		<field
			name="published"
			type="list"
			label="JFIELD_PUBLISHED_LABEL"
			description="JFIELD_PUBLISHED_DESC"
			default="1"
			size="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="-1">JARCHIVED</option>
			<option value="-2">JTRASHED</option>
		</field>

		<field
			name="catid"
			type="category"
			label="JCATEGORY"
			description="JFIELD_CATEGORY_DESC"
			extension="com_contact"
			required="true"
		/>

		<field
			name="access"
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="JFIELD_ACCESS_DESC"
			size="1"
		/>

		<field
			name="sortname1"
			type="text"
			label="CONTACT_SORTNAME1_LABEL"
			description="CONTACT_SORTNAME1_DESC"
			size="30"
		/>

		<field
			name="sortname2"
			type="text"
			label="CONTACT_SORTNAME2_LABEL"
			description="CONTACT_SORTNAME3_DESC"
			size="30"
		/>

		<field
			name="sortname3"
			type="text"
			label="CONTACT_SORTNAME3_LABEL"
			description="CONTACT_SORTNAME3_DESC"
			size="30"
		/>

		<field
			name="language"
			type="text"
			label="CONTACT_LANGUAGE_LABEL"
			description="CONTACT_LANGUAGE_DESC"
			size="30"
		/>

		<field
			name="con_position"
			type="text"
			label="CONTACT_INFORMATION_POSITION_LABEL"
			description="CONTACT_INFORMATION_POSITION_DESC"
			size="30"
		/>

		<field
			name="email_to"
			type="email"
			label="CONTACT_INFORMATION_EMAIL_LABEL"
			description="CONTACT_INFORMATION_EMAIL_DESC"
			size="30"
			validate="email"
			filter="string"
			autocomplete="email"
		/>

		<field
			name="address"
			type="textarea"
			label="CONTACT_INFORMATION_ADDRESS_LABEL"
			description="CONTACT_INFORMATION_ADDRESS_DESC"
			cols="30"
			rows="3"
		/>

		<field
			name="suburb"
			type="text"
			label="CONTACT_INFORMATION_SUBURB_LABEL"
			description="CONTACT_INFORMATION_SUBURB_DESC"
			size="30"
		/>

		<field
			name="state"
			type="text"
			label="CONTACT_INFORMATION_STATE_LABEL"
			description="CONTACT_INFORMATION_STATE_DESC"
			size="30"
		/>

		<field
			name="postcode"
			type="text"
			label="CONTACT_INFORMATION_POSTCODE_LABEL"
			description="CONTACT_INFORMATION_POSTCODE_DESC"
			size="30"
		/>

		<field
			name="country"
			type="text"
			label="CONTACT_INFORMATION_COUNTRY_LABEL"
			description="CONTACT_INFORMATION_COUNTRY_DESC"
			size="30"
		/>

		<field
			name="telephone"
			type="text"
			label="CONTACT_INFORMATION_TELEPHONE_LABEL"
			description="CONTACT_INFORMATION_TELEPHONE_DESC"
			size="30"
		/>

		<field
			name="mobile"
			type="text"
			label="CONTACT_INFORMATION_MOBILE_LABEL"
			description="CONTACT_INFORMATION_MOBILE_DESC"
			size="30"
		/>

		<field
			name="webpage"
			type="text"
			label="CONTACT_INFORMATION_WEBPAGE_LABEL"
			description="CONTACT_INFORMATION_WEBPAGE_DESC"
			size="30"
		/>

		<field
			name="misc"
			type="editor"
			label="CONTACT_INFORMATION_MISC_LABEL"
			description="CONTACT_INFORMATION_MISC_DESC"
			buttons="true"
			hide="pagebreak,readmore"
			filter="safehtml"
			size="30"
		/>

		<field
			name="checked_out"
			type="hidden"
			filter="unset"
		/>

		<field
			name="checked_out_time"
			type="hidden"
			filter="unset"
		/>

		<field
			name="ordering"
			type="ordering"
			label="JFIELD_ORDERING_LABEL"
			description="JFIELD_ORDERING_DESC"
			content_type="com_contact.contact"
		/>

		<field
			name="metakey"
			type="textarea"
			label="JFIELD_META_KEYWORDS_LABEL"
			description="JFIELD_META_KEYWORDS_DESC"
			cols="30"
			rows="3"
		/>

		<field
			name="metadesc"
			type="textarea"
			label="JFIELD_META_DESCRIPTION_LABEL"
			description="JFIELD_META_DESCRIPTION_DESC"
			cols="30"
			rows="3"
		/>

		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="JFIELD_CONTACT_LANGUAGE_DESC"
			>
			<option value="">JALL</option>
		</field>

		<field
			name="contact_icons"
			type="list"
			label="Icons/text"
			description="PARAMCONTACTICONS"
			default="0"
			>
			<option value="0">CONTACT_ICONS_OPTIONS_NONE</option>
			<option value="1">CONTACT_ICONS_OPTIONS_TEXT</option>
			<option value="2">CONTACT_ICONS_OPTIONS_TEXT</option>
		</field>

		<field
			name="icon_address"
			type="imagelist"
			label="CONTACT_ICONS_ADDRESS_LABEL"
			description="CONTACT_ICONS_ADDRESS_DESC"
			directory="/images"
			hide_none="1"
		/>

		<field
			name="icon_email"
			type="imagelist"
			label="CONTACT_ICONS_EMAIL_LABEL"
			description="CONTACT_ICONS_EMAIL_DESC"
			directory="/images"
			hide_none="1"
		/>

		<field
			name="icon_telephone"
			type="imagelist"
			label="CONTACT_ICONS_TELEPHONE_LABEL"
			description="CONTACT_ICONS_TELEPHONE_DESC"
			directory="/images"
			hide_none="1"
		/>

		<field
			name="icon_mobile"
			type="imagelist"
			label="CONTACT_ICONS_MOBILE_LABEL"
			description="CONTACT_ICONS_MOBILE_DESC"
			directory="/images"
			hide_none="1"
		/>

		<field
			name="icon_fax"
			type="imagelist"
			label="CONTACT_ICONS_FAX_LABEL"
			description="CONTACT_ICONS_FAX_DESC"
			directory="/images"
			hide_none="1"
		/>

		<field
			name="icon_misc"
			type="imagelist"
			label="CONTACT_ICONS_MISC_LABEL"
			description="CONTACT_ICONS_MISC_DESC"
			directory="/images"
			hide_none="1"
		/>

	</fieldset>

	<fields name="metadata">
		<fieldset name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">
			<field
				name="robots"
				type="list"
				label="JFIELD_METADATA_ROBOTS_LABEL"
				description="JFIELD_METADATA_ROBOTS_DESC"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="index, follow"></option>
				<option value="noindex, follow"></option>
				<option value="index, nofollow"></option>
				<option value="noindex, nofollow"></option>
			</field>

			<field
				name="rights"
				type="text"
				label="JFIELD_METADATA_RIGHTS_LABEL"
				description="JFIELD_METADATA_RIGHTS_DESC"
				size="20"
			/>

		</fieldset>
	</fields>

	<fields name="params">
		<fieldset name="options" label="CONTACT_PARAMETERS">

			<field
				name="show_tags"
				type="list"
				label="COM_CONTACT_FIELD_SHOW_TAGS_LABEL"
				description="COM_CONTACT_FIELD_SHOW_TAGS_DESC"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_info"
				type="list"
				label="COM_CONTACT_FIELD_SHOW_INFO_LABEL"
				description="COM_CONTACT_FIELD_SHOW_INFO_DESC"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

		<field
			name="show_name"
			type="list"
			label="CONTACT_PARAMS_NAME_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_position"
			type="list"
			label="CONTACT_PARAMS_CONTACT_POSITION_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_email"
			type="list"
			label="CONTACT_PARAMS_CONTACT_POSITION_E_MAIL_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_street_address"
			type="list"
			label="CONTACT_PARAMS_STREET_ADDRESS_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_suburb"
			type="list"
			label="CONTACT_PARAMS_TOWN_SUBURB_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_state"
			type="list"
			label="CONTACT_PARAMS_STATE_COUNTY_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_postcode"
			type="list"
			label="CONTACT_PARAMS_POST_ZIP_CODE_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_country"
			type="list"
			label="CONTACT_PARAMS_COUNTRY_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_telephone"
			type="list"
			label="CONTACT_PARAMS_TELEPHONE_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_mobile"
			type="list"
			label="CONTACT_PARAMS_MOBILE_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_fax"
			type="list"
			label="CONTACT_PARAMS_FAX_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_webpage"
			type="list"
			label="CONTACT_PARAMS_WEBPAGE_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_image"
			type="list"
			label="CONTACT_PARAMS_IMAGE_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="allow_vcard"
			type="list"
			label="CONTACT_PARAMS_VCARD_LABEL"
			description="CONTACT_PARAMS_VCARD_LABEL"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_misc"
			type="list"
			label="CONTACT_PARAMS_MISC_INFO_LABEL"
			description="CONTACT_PARAMS_NAME_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_articles"
			type="list"
			label="CONTACT_SHOW_ARTICLES_LABEL"
			description="CONTACT_SHOW_ARTICLES_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="articles_display_num"
			type="list"
			label="COM_CONTACT_FIELD_ARTICLES_DISPLAY_NUM_LABEL"
			description="COM_CONTACT_FIELD_ARTICLES_DISPLAY_NUM_DESC"
			default=""
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="5">J5</option>
			<option value="10">J10</option>
			<option value="15">J15</option>
			<option value="20">J20</option>
			<option value="25">J25</option>
			<option value="30">J30</option>
			<option value="50">J50</option>
			<option value="75">J75</option>
			<option value="100">J100</option>
			<option value="150">J150</option>
			<option value="200">J200</option>
			<option value="250">J250</option>
			<option value="300">J300</option>
			<option value="0">JALL</option>
		</field>

		<field
			name="show_profile"
			type="list"
			label="CONTACT_PROFILE_SHOW_LABEL"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="show_user_custom_fields"
			type="fieldgroups"
			label="COM_CONTACT_FIELD_USER_CUSTOM_FIELDS_SHOW_LABEL"
			description="COM_CONTACT_FIELD_USER_CUSTOM_FIELDS_SHOW_DESC"
			multiple="true"
			context="com_users.user"
			>
			<option value="-1">JALL</option>
		</field>

		<field
			name="show_links"
			type="list"
			label="CONTACT_SHOW_LINKS_LABEL"
			description="CONTACT_SHOW_LINKS_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="linka_name"
			type="text"
			label="CONTACT_LINKA_NAME_LABEL"
			description="CONTACT_LINKA_NAME_DESC"
			size="30"
		/>

		<field
			name="linka"
			type="text"
			label="CONTACT_LINKA_LABEL"
			description="CONTACT_LINKA_DESC"
			size="30"
		/>

		<field
			name="linkb_name"
			type="text"
			label="CONTACT_LINKB_NAME_LABEL"
			description="CONTACT_LINKB_NAME_DESC"
			size="30"
		/>

		<field
			name="linkb"
			type="text"
			label="CONTACT_LINKB_LABEL"
			description="CONTACT_LINKB_DESC"
			size="30"
		/>

		<field
			name="linkc_name"
			type="text"
			label="CONTACT_LINKC_NAME_LABEL"
			description="CONTACT_LINKC_NAME_DESC"
			size="30"
		/>

		<field
			name="linkc"
			type="text"
			label="CONTACT_LINKC_LABEL"
			description="CONTACT_LINKC_DESC"
			size="30"
		/>

		<field
			name="linkd_name"
			type="text"
			label="CONTACT_LINKD_NAME_LABEL"
			description="CONTACT_LINKD_NAME_DESC"
			size="30"
		/>

		<field
			name="linkd"
			type="text"
			label="CONTACT_LINKD_LABEL"
			description="CONTACT_LINKD_DESC"
			size="30"
		/>

		<field
			name="linke_name"
			type="text"
			label="CONTACT_LINKE_NAME_LABEL"
			description="CONTACT_LINKE_NAME_DESC"
			size="30"
		/>

		<field
			name="linke"
			type="text"
			label="CONTACT_LINKE_LABEL"
			description="CONTACT_LINKE_DESC"
			size="30"
		/>

		</fieldset>
	</fields>

	<fields name="email_form">
		<fieldset name="email_form" label="CONTACT_EMAIL_FORM_LABEL">

		<field
			name="show_email_form"
			type="list"
			label="CONTACT_EMAIL_SHOW_FORM_LABEL"
			description="CONTACT_EMAIL_SHOW_FORM_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="email_description"
			type="text"
			label="CONTACT_EMAIL_DESCRIPTION_TEXT_LABEL"
			description="CONTACT_EMAIL_DESCRIPTION_TEXT_DESC"
			size="30"
		/>

		<field
			name="show_email_copy"
			type="list"
			label="CONTACT_EMAIL_EMAIL_COPY_LABEL"
			description="CONTACT_EMAIL_EMAIL_COPY_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>

		<field
			name="validate_session"
			type="list"
			label="CONTACT_CONFIG_SESSION_CHECK_LABEL"
			description="CONTACT_CONFIG_SESSION_CHECK_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JNO</option>
			<option value="1">JYES</option>
		</field>

		<field
			name="custom_reply"
			type="list"
			label="CONTACT_CONFIG_CUSTOM_REPLY"
			description="CONTACT_CONFIG_CUSTOM_REPLY_DESC"
			>
			<option value="">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JNO</option>
			<option value="1">JYES</option>
		</field>

		<field
			name="redirect"
			type="text"
			label="COM_CONTACT_FIELD_CONFIG_REDIRECT_LABEL"
			description="COM_CONTACT_FIELD_CONFIG_REDIRECT_DESC"
			size="30"
		/>

		</fieldset>
	</fields>
</form>

forms/contact.xml000060400000053200152455302730010051 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>

	<fieldset addfieldpath="/administrator/components/com_categories/models/fields">

		<field
			name="id"
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			default="0"
			class="readonly"
			size="10"
			readonly="true"
		/>

		<field
			name="name"
			type="text"
			label="COM_CONTACT_FIELD_NAME_LABEL"
			description="COM_CONTACT_FIELD_NAME_DESC"
			class="input-xxlarge input-large-text"
			size="40"
			required="true"
		 />

		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			size="45"
			hint="JFIELD_ALIAS_PLACEHOLDER"
		/>

		<field
			name="version_note"
			type="text"
			label="JGLOBAL_FIELD_VERSION_NOTE_LABEL"
			description="JGLOBAL_FIELD_VERSION_NOTE_DESC"
			labelclass="control-label"
			class="span12"
			size="45"
			maxlength="255"
		/>

		<field
			name="user_id"
			type="user"
			label="COM_CONTACT_FIELD_LINKED_USER_LABEL"
			description="COM_CONTACT_FIELD_LINKED_USER_DESC"
		/>

		<field
			name="published"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			default="1"
			id="published"
			class="chzn-color-state"
			size="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="2">JARCHIVED</option>
			<option value="-2">JTRASHED</option>

		</field>

		<field
			name="catid"
			type="categoryedit"
			label="JCATEGORY"
			description="JFIELD_CATEGORY_DESC"
			extension="com_contact"
			required="true"
			default=""
		/>

		<field
			name="access"
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="JFIELD_ACCESS_DESC"
			size="1"
		/>

		<field
			name="misc"
			type="editor"
			label="COM_CONTACT_FIELD_INFORMATION_MISC_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_MISC_DESC"
			filter="JComponentHelper::filterText"
			buttons="true"
			hide="readmore,pagebreak"
		/>

		<field
			name="created_by"
			type="user"
			label="JGLOBAL_FIELD_CREATED_BY_LABEL"
			description="COM_CONTACT_FIELD_CREATED_BY_DESC"
		/>

		<field
			name="created_by_alias"
			type="text"
			label="COM_CONTACT_FIELD_CREATED_BY_ALIAS_LABEL"
			description="COM_CONTACT_FIELD_CREATED_BY_ALIAS_DESC"
			size="20"
		/>

		<field
			name="created"
			type="calendar"
			label="COM_CONTACT_FIELD_CREATED_LABEL"
			description="COM_CONTACT_FIELD_CREATED_DESC"
			size="22"
			translateformat="true"
			showtime="true"
			filter="user_utc"
		/>

		<field
			name="modified"
			type="calendar"
			label="JGLOBAL_FIELD_MODIFIED_LABEL"
			description="COM_CONTACT_FIELD_MODIFIED_DESC"
			class="readonly"
			size="22"
			readonly="true"
			translateformat="true"
			showtime="true"
			filter="user_utc"
		/>

		<field
			name="modified_by"
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			description="COM_CONTACT_FIELD_MODIFIED_BY_DESC"
			class="readonly"
			readonly="true"
			filter="unset"
		/>

		<field
			name="checked_out"
			type="hidden"
			filter="unset"
		/>

		<field
			name="checked_out_time"
			type="hidden"
			filter="unset"
		/>

		<field
			name="ordering"
			type="ordering"
			label="JFIELD_ORDERING_LABEL"
			description="JFIELD_ORDERING_DESC"
			content_type="com_contact.contact"
		/>

		<field
			name="publish_up"
			type="calendar"
			label="COM_CONTACT_FIELD_PUBLISH_UP_LABEL"
			description="COM_CONTACT_FIELD_PUBLISH_UP_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="publish_down"
			type="calendar"
			label="COM_CONTACT_FIELD_PUBLISH_DOWN_LABEL"
			description="COM_CONTACT_FIELD_PUBLISH_DOWN_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="metakey"
			type="textarea"
			label="JFIELD_META_KEYWORDS_LABEL"
			description="JFIELD_META_KEYWORDS_DESC"
			rows="3"
			cols="30"
		 />

		<field
			name="metadesc"
			type="textarea"
			label="JFIELD_META_DESCRIPTION_LABEL"
			description="JFIELD_META_DESCRIPTION_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="COM_CONTACT_FIELD_LANGUAGE_DESC"
			>
			<option value="*">JALL</option>
		</field>

		<field
			name="featured"
			type="radio"
			label="JFEATURED"
			description="COM_CONTACT_FIELD_FEATURED_DESC"
			default="0"
			class="btn-group btn-group-yesno"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>

		<field
			name="tags"
			type="tag"
			label="JTAG"
			description="JTAG_DESC"
			class="span12"
			multiple="true"
		/>

		<field
			name="contact_icons"
			type="list"
			label="COM_CONTACT_FIELD_ICONS_SETTINGS"
			description="COM_CONTACT_FIELD_ICONS_SETTINGS_DESC"
			default="0"
			>
			<option value="0">COM_CONTACT_FIELD_VALUE_NONE</option>
			<option value="1">COM_CONTACT_FIELD_VALUE_TEXT</option>
			<option value="2">COM_CONTACT_FIELD_VALUE_ICONS</option>
		</field>

		<field
			name="icon_address"
			type="media"
			label="COM_CONTACT_FIELD_ICONS_ADDRESS_LABEL"
			description="COM_CONTACT_FIELD_ICONS_ADDRESS_DESC"
			hide_none="1"
		/>

		<field
			name="icon_email"
			type="media"
			label="COM_CONTACT_FIELD_ICONS_EMAIL_LABEL"
			description="COM_CONTACT_FIELD_ICONS_EMAIL_DESC"
			hide_none="1"
		/>

		<field
			name="icon_telephone"
			type="media"
			label="COM_CONTACT_FIELD_ICONS_TELEPHONE_LABEL"
			description="COM_CONTACT_FIELD_ICONS_TELEPHONE_DESC"
			hide_none="1"
		/>

		<field
			name="icon_mobile"
			type="media"
			label="COM_CONTACT_FIELD_ICONS_MOBILE_LABEL"
			description="COM_CONTACT_FIELD_ICONS_MOBILE_DESC"
			hide_none="1"
		/>

		<field
			name="icon_fax"
			type="media"
			label="COM_CONTACT_FIELD_ICONS_FAX_LABEL"
			description="COM_CONTACT_FIELD_ICONS_FAX_DESC"
			hide_none="1"
		/>

		<field
			name="icon_misc"
			type="media"
			label="COM_CONTACT_FIELD_ICONS_MISC_LABEL"
			description="COM_CONTACT_FIELD_ICONS_MISC_DESC"
			hide_none="1"
		/>
	</fieldset>

	<fieldset name="details" label="COM_CONTACT_CONTACT_DETAILS">

		<field
			name="image"
			type="media"
			label="COM_CONTACT_FIELD_PARAMS_IMAGE_LABEL"
			description="COM_CONTACT_FIELD_PARAMS_IMAGE_DESC"
			hide_none="1"
		/>

		<field
			name="con_position"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_POSITION_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_POSITION_DESC"
			size="30"
		/>

		<field
			name="email_to"
			type="email"
			label="JGLOBAL_EMAIL"
			description="COM_CONTACT_FIELD_INFORMATION_EMAIL_DESC"
			size="30"
		/>

		<field
			name="address"
			type="textarea"
			label="COM_CONTACT_FIELD_INFORMATION_ADDRESS_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_ADDRESS_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="suburb"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_SUBURB_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_SUBURB_DESC"
			size="30"
		/>

		<field
			name="state"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_STATE_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_STATE_DESC"
			size="30"
		/>

		<field
			name="postcode"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_POSTCODE_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_POSTCODE_DESC"
			size="30"
		/>

		<field
			name="country"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_COUNTRY_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_COUNTRY_DESC"
			size="30"
		/>

		<field
			name="telephone"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_TELEPHONE_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_TELEPHONE_DESC"
			size="30"
		/>

		<field
			name="mobile"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_MOBILE_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_MOBILE_DESC"
			size="30"
		/>

		<field
			name="fax"
			type="text"
			label="COM_CONTACT_FIELD_INFORMATION_FAX_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_FAX_DESC"
			size="30"
		/>

		<field
			name="webpage"
			type="url"
			label="COM_CONTACT_FIELD_INFORMATION_WEBPAGE_LABEL"
			description="COM_CONTACT_FIELD_INFORMATION_WEBPAGE_DESC"
			size="30"
			filter="url"
			validate="url"
		/>

		<field
			name="sortname1"
			type="text"
			label="COM_CONTACT_FIELD_SORTNAME1_LABEL"
			description="COM_CONTACT_FIELD_SORTNAME1_DESC"
			size="30"
		/>

		<field
			name="sortname2"
			type="text"
			label="COM_CONTACT_FIELD_SORTNAME2_LABEL"
			description="COM_CONTACT_FIELD_SORTNAME2_DESC"
			size="30"
		/>

		<field
			name="sortname3"
			type="text"
			label="COM_CONTACT_FIELD_SORTNAME3_LABEL"
			description="COM_CONTACT_FIELD_SORTNAME3_DESC"
			size="30"
		/>
	</fieldset>

	<fields name="params" label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS">

		<fieldset name="display" label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS"
			 addfieldpath="/administrator/components/com_fields/models/fields">

			<field
				name="show_contact_category"
				type="list"
				label="JGLOBAL_SHOW_CATEGORY_LABEL"
				description="COM_CONTACT_FIELD_SHOW_CATEGORY_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="hide">JHIDE</option>
				<option value="show_no_link">COM_CONTACT_FIELD_VALUE_NO_LINK</option>
				<option value="show_with_link">COM_CONTACT_FIELD_VALUE_WITH_LINK</option>
			</field>

			<field
				name="show_contact_list"
				type="list"
				label="COM_CONTACT_FIELD_CONTACT_SHOW_LIST_LABEL"
				description="COM_CONTACT_FIELD_CONTACT_SHOW_LIST_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="presentation_style"
				type="list"
				label="COM_CONTACT_FIELD_PRESENTATION_LABEL"
				description="COM_CONTACT_FIELD_PRESENTATION_DESC"
				useglobal="true"
				>
				<option value="sliders">COM_CONTACT_FIELD_VALUE_SLIDERS</option>
				<option value="tabs">COM_CONTACT_FIELD_VALUE_TABS</option>
				<option value="plain">COM_CONTACT_FIELD_VALUE_PLAIN</option>
			</field>

			<field
				name="show_tags"
				type="list"
				label="COM_CONTACT_FIELD_SHOW_TAGS_LABEL"
				description="COM_CONTACT_FIELD_SHOW_TAGS_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_info"
				type="list"
				label="COM_CONTACT_FIELD_SHOW_INFO_LABEL"
				description="COM_CONTACT_FIELD_SHOW_INFO_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_name"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_NAME_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_NAME_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_position"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_CONTACT_POSITION_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_CONTACT_POSITION_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_email"
				type="list"
				label="JGLOBAL_EMAIL"
				description="COM_CONTACT_FIELD_PARAMS_CONTACT_E_MAIL_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="add_mailto_link"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_ADD_MAILTO_LINK_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_ADD_MAILTO_LINK_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="1">JYES</option>
				<option value="0">JNO</option>
			</field>

			<field
				name="show_street_address"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_STREET_ADDRESS_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_STREET_ADDRESS_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_suburb"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_TOWN-SUBURB_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_TOWN-SUBURB_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_state"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_STATE-COUNTY_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_STATE-COUNTY_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_postcode"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_POST-ZIP_CODE_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_POST-ZIP_CODE_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_country"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_COUNTRY_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_COUNTRY_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_telephone"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_TELEPHONE_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_TELEPHONE_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_mobile"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_MOBILE_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_MOBILE_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_fax"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_FAX_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_FAX_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_webpage"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_WEBPAGE_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_WEBPAGE_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_image"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_SHOW_IMAGE_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_SHOW_IMAGE_DESC"
				class="chzn-color"
				useglobal="true"
				showon="show_info:1"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_misc"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_MISC_INFO_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_MISC_INFO_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="allow_vcard"
				type="list"
				label="COM_CONTACT_FIELD_PARAMS_VCARD_LABEL"
				description="COM_CONTACT_FIELD_PARAMS_VCARD_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_articles"
				type="list"
				label="COM_CONTACT_FIELD_ARTICLES_SHOW_LABEL"
				description="COM_CONTACT_FIELD_ARTICLES_SHOW_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="articles_display_num"
				type="list"
				label="COM_CONTACT_FIELD_ARTICLES_DISPLAY_NUM_LABEL"
				description="COM_CONTACT_FIELD_ARTICLES_DISPLAY_NUM_DESC"
				default=""
				useglobal="true"
				>
				<option value="5">J5</option>
				<option value="10">J10</option>
				<option value="15">J15</option>
				<option value="20">J20</option>
				<option value="25">J25</option>
				<option value="30">J30</option>
				<option value="50">J50</option>
				<option value="75">J75</option>
				<option value="100">J100</option>
				<option value="150">J150</option>
				<option value="200">J200</option>
				<option value="250">J250</option>
				<option value="300">J300</option>
				<option value="0">JALL</option>
			</field>

			<field
				name="show_profile"
				type="list"
				label="COM_CONTACT_FIELD_PROFILE_SHOW_LABEL"
				description="COM_CONTACT_FIELD_PROFILE_SHOW_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_user_custom_fields"
				type="fieldgroups"
				label="COM_CONTACT_FIELD_USER_CUSTOM_FIELDS_SHOW_LABEL"
				description="COM_CONTACT_FIELD_USER_CUSTOM_FIELDS_SHOW_DESC"
				multiple="true"
				context="com_users.user"
				>
				<option value="-1">JALL</option>
			</field>

			<field
				name="show_links"
				type="list"
				label="COM_CONTACT_FIELD_SHOW_LINKS_LABEL"
				description="COM_CONTACT_FIELD_SHOW_LINKS_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="linka_name"
				type="text"
				label="COM_CONTACT_FIELD_LINKA_NAME_LABEL"
				description="COM_CONTACT_FIELD_LINK_NAME_DESC"
				size="30"
			/>

			<field
				name="linka"
				type="url"
				label="COM_CONTACT_FIELD_LINKA_LABEL"
				description="COM_CONTACT_FIELD_LINKA_DESC"
				size="30"
				filter="url"
				validate="url"
			/>

			<field
				name="linkb_name"
				type="text"
				label="COM_CONTACT_FIELD_LINKB_NAME_LABEL"
				description="COM_CONTACT_FIELD_LINK_NAME_DESC"
				size="30"
			/>

			<field
				name="linkb"
				type="url"
				label="COM_CONTACT_FIELD_LINKB_LABEL"
				description="COM_CONTACT_FIELD_LINKB_DESC"
				size="30"
				filter="url"
				validate="url"
			/>

			<field
				name="linkc_name"
				type="text"
				label="COM_CONTACT_FIELD_LINKC_NAME_LABEL"
				description="COM_CONTACT_FIELD_LINK_NAME_DESC"
				size="30"
			/>

			<field
				name="linkc"
				type="url"
				label="COM_CONTACT_FIELD_LINKC_LABEL"
				description="COM_CONTACT_FIELD_LINKC_DESC"
				size="30"
				filter="url"
				validate="url"
			/>

			<field
				name="linkd_name"
				type="text"
				label="COM_CONTACT_FIELD_LINKD_NAME_LABEL"
				description="COM_CONTACT_FIELD_LINK_NAME_DESC"
				size="30"
			/>

			<field
				name="linkd"
				type="url"
				label="COM_CONTACT_FIELD_LINKD_LABEL"
				description="COM_CONTACT_FIELD_LINKD_DESC"
				size="30"
				filter="url"
				validate="url"
			/>

			<field
				name="linke_name"
				type="text"
				label="COM_CONTACT_FIELD_LINKE_NAME_LABEL"
				description="COM_CONTACT_FIELD_LINK_NAME_DESC"
				size="30"
			/>

			<field
				name="linke"
				type="url"
				label="COM_CONTACT_FIELD_LINKE_LABEL"
				description="COM_CONTACT_FIELD_LINKE_DESC"
				size="30"
				filter="url"
				validate="url"
			/>

			<field
				name="contact_layout"
				type="componentlayout"
				label="JFIELD_ALT_LAYOUT_LABEL"
				description="JFIELD_ALT_COMPONENT_LAYOUT_DESC"
				extension="com_contact"
				view="contact"
				useglobal="true"
			/>
		</fieldset>

		<fieldset name="email" label="COM_CONTACT_FIELDSET_CONTACT_LABEL">

			<field
				name="show_email_form"
				type="list"
				label="COM_CONTACT_FIELD_EMAIL_SHOW_FORM_LABEL"
				description="COM_CONTACT_FIELD_EMAIL_SHOW_FORM_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_email_copy"
				type="list"
				label="COM_CONTACT_FIELD_EMAIL_EMAIL_COPY_LABEL"
				description="COM_CONTACT_FIELD_EMAIL_EMAIL_COPY_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="validate_session"
				type="list"
				label="COM_CONTACT_FIELD_CONFIG_SESSION_CHECK_LABEL"
				description="COM_CONTACT_FIELD_CONFIG_SESSION_CHECK_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
			</field>

			<field
				name="custom_reply"
				type="list"
				label="COM_CONTACT_FIELD_CONFIG_CUSTOM_REPLY_LABEL"
				description="COM_CONTACT_FIELD_CONFIG_CUSTOM_REPLY_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
			</field>

			<field
				name="redirect"
				type="text"
				label="COM_CONTACT_FIELD_CONFIG_REDIRECT_LABEL"
				description="COM_CONTACT_FIELD_CONFIG_REDIRECT_DESC"
				size="30"
			/>
		</fieldset>
	</fields>

	<fields name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">

		<fieldset name="jmetadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">

			<field
				name="robots"
				type="list"
				label="JFIELD_METADATA_ROBOTS_LABEL"
				description="JFIELD_METADATA_ROBOTS_DESC"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="index, follow"></option>
				<option value="noindex, follow"></option>
				<option value="index, nofollow"></option>
				<option value="noindex, nofollow"></option>
			</field>

			<field
				name="rights"
				type="text"
				label="JFIELD_METADATA_RIGHTS_LABEL"
				description="JFIELD_METADATA_RIGHTS_DESC"
				size="20"
			/>
		</fieldset>
	</fields>

	<field
		name="hits"
		type="number"
		label="JGLOBAL_HITS"
		description="COM_CONTACT_HITS_DESC"
		class="readonly"
		size="6"
		readonly="true"
		filter="unset"
	/>

	<field
		name="version"
		type="text"
		label="COM_CONTACT_FIELD_VERSION_LABEL"
		description="COM_CONTACT_FIELD_VERSION_DESC"
		class="readonly"
		size="6"
		readonly="true"
		filter="unset"
	/>
</form>
category.php000060400000020715152455302730007101 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_newsfeeds
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;

/**
 * Newsfeeds Component Category Model
 *
 * @since  1.5
 */
class NewsfeedsModelCategory extends JModelList
{
	/**
	 * Category items data
	 *
	 * @var array
	 */
	protected $_item = null;

	protected $_articles = null;

	protected $_siblings = null;

	protected $_children = null;

	protected $_parent = null;

	/**
	 * The category that applies.
	 *
	 * @access    protected
	 * @var        object
	 */
	protected $_category = null;

	/**
	 * The list of other newsfeed categories.
	 *
	 * @access    protected
	 * @var        array
	 */
	protected $_categories = null;

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'name', 'a.name',
				'numarticles', 'a.numarticles',
				'link', 'a.link',
				'ordering', 'a.ordering',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to get a list of items.
	 *
	 * @return  mixed  An array of objects on success, false on failure.
	 */
	public function getItems()
	{
		// Invoke the parent getItems method to get the main list
		$items = parent::getItems();

		// Convert the params field into an object, saving original in _params
		foreach ($items as $item)
		{
			if (!isset($this->_params))
			{
				$params = new Registry;
				$item->params = $params;
				$params->loadString($item->params);
			}

			// Some contexts may not use tags data at all, so we allow callers to disable loading tag data
			if ($this->getState('load_tags', true))
			{
				$item->tags = new JHelperTags;
				$item->tags->getItemTags('com_newsfeeds.newsfeed', $item->id);
			}
		}

		return $items;
	}

	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return  string    An SQL query
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		$user = JFactory::getUser();
		$groups = implode(',', $user->getAuthorisedViewLevels());

		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select required fields from the categories.
		$query->select($this->getState('list.select', 'a.*'))
			->from($db->quoteName('#__newsfeeds') . ' AS a')
			->where('a.access IN (' . $groups . ')');

		// Filter by category.
		if ($categoryId = $this->getState('category.id'))
		{
			$query->where('a.catid = ' . (int) $categoryId)
				->join('LEFT', '#__categories AS c ON c.id = a.catid')
				->where('c.access IN (' . $groups . ')');
		}

		// Filter by state
		$state = $this->getState('filter.published');

		if (is_numeric($state))
		{
			$query->where('a.published = ' . (int) $state);
		}
		else
		{
			$query->where('(a.published IN (0,1,2))');
		}

		// Filter by start and end dates.
		$nullDate = $db->quote($db->getNullDate());
		$date = JFactory::getDate();
		$nowDate = $db->quote($date->format($db->getDateFormat()));

		if ($this->getState('filter.publish_date'))
		{
			$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')')
				->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
		}

		// Filter by search in title
		$search = $this->getState('list.filter');

		if (!empty($search))
		{
			$search = $db->quote('%' . $db->escape($search, true) . '%');
			$query->where('(a.name LIKE ' . $search . ')');
		}

		// Filter by language
		if ($this->getState('filter.language'))
		{
			$query->where('a.language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		}

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field
	 * @param   string  $direction  An optional direction [asc|desc]
	 *
	 * @return void
	 *
	 * @since   1.6
	 *
	 * @throws Exception
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		$app = JFactory::getApplication();
		$params = JComponentHelper::getParams('com_newsfeeds');

		// List state information
		$limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->get('list_limit'), 'uint');
		$this->setState('list.limit', $limit);

		$limitstart = $app->input->get('limitstart', 0, 'uint');
		$this->setState('list.start', $limitstart);

		// Optional filter text
		$this->setState('list.filter', $app->input->getString('filter-search'));

		$orderCol = $app->input->get('filter_order', 'ordering');

		if (!in_array($orderCol, $this->filter_fields))
		{
			$orderCol = 'ordering';
		}

		$this->setState('list.ordering', $orderCol);

		$listOrder = $app->input->get('filter_order_Dir', 'ASC');

		if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', '')))
		{
			$listOrder = 'ASC';
		}

		$this->setState('list.direction', $listOrder);

		$id = $app->input->get('id', 0, 'int');
		$this->setState('category.id', $id);

		$user = JFactory::getUser();

		if ((!$user->authorise('core.edit.state', 'com_newsfeeds')) && (!$user->authorise('core.edit', 'com_newsfeeds')))
		{
			// Limit to published for people who can't edit or edit.state.
			$this->setState('filter.published', 1);

			// Filter by start and end dates.
			$this->setState('filter.publish_date', true);
		}

		$this->setState('filter.language', JLanguageMultilang::isEnabled());

		// Load the parameters.
		$this->setState('params', $params);
	}

	/**
	 * Method to get category data for the current category
	 *
	 * @return  object
	 *
	 * @since   1.5
	 */
	public function getCategory()
	{
		if (!is_object($this->_item))
		{
			$app = JFactory::getApplication();
			$menu = $app->getMenu();
			$active = $menu->getActive();
			$params = new Registry;

			if ($active)
			{
				$params->loadString($active->params);
			}

			$options = array();
			$options['countItems'] = $params->get('show_cat_items', 1) || $params->get('show_empty_categories', 0);
			$categories = JCategories::getInstance('Newsfeeds', $options);
			$this->_item = $categories->get($this->getState('category.id', 'root'));

			if (is_object($this->_item))
			{
				$this->_children = $this->_item->getChildren();
				$this->_parent = false;

				if ($this->_item->getParent())
				{
					$this->_parent = $this->_item->getParent();
				}

				$this->_rightsibling = $this->_item->getSibling();
				$this->_leftsibling = $this->_item->getSibling(false);
			}
			else
			{
				$this->_children = false;
				$this->_parent = false;
			}
		}

		return $this->_item;
	}

	/**
	 * Get the parent category.
	 *
	 * @return  mixed  An array of categories or false if an error occurs.
	 */
	public function getParent()
	{
		if (!is_object($this->_item))
		{
			$this->getCategory();
		}

		return $this->_parent;
	}

	/**
	 * Get the sibling (adjacent) categories.
	 *
	 * @return  mixed  An array of categories or false if an error occurs.
	 */
	public function &getLeftSibling()
	{
		if (!is_object($this->_item))
		{
			$this->getCategory();
		}

		return $this->_leftsibling;
	}

	/**
	 * Get the sibling (adjacent) categories.
	 *
	 * @return  mixed  An array of categories or false if an error occurs.
	 */
	public function &getRightSibling()
	{
		if (!is_object($this->_item))
		{
			$this->getCategory();
		}

		return $this->_rightsibling;
	}

	/**
	 * Get the child categories.
	 *
	 * @return  mixed  An array of categories or false if an error occurs.
	 */
	public function &getChildren()
	{
		if (!is_object($this->_item))
		{
			$this->getCategory();
		}

		return $this->_children;
	}

	/**
	 * Increment the hit counter for the category.
	 *
	 * @param   int  $pk  Optional primary key of the category to increment.
	 *
	 * @return  boolean True if successful; false otherwise and internal error set.
	 */
	public function hit($pk = 0)
	{
		$input    = JFactory::getApplication()->input;
		$hitcount = $input->getInt('hitcount', 1);

		if ($hitcount)
		{
			$pk    = (!empty($pk)) ? $pk : (int) $this->getState('category.id');
			$table = JTable::getInstance('Category', 'JTable');
			$table->hit($pk);
		}

		return true;
	}
}
rules/contactemailsubject.php000060400000003374152455302730012443 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_contact
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\String\StringHelper;

/**
 * JFormRule for com_contact to make sure the subject contains no banned word.
 *
 * @since  1.6
 */
class JFormRuleContactEmailSubject extends JFormRule
{
	/**
	 * Method to test for a banned subject
	 *
	 * @param   SimpleXMLElement  $element  The SimpleXMLElement object representing the <field /> tag for the form field object.
	 * @param   mixed             $value    The form field value to validate.
	 * @param   string            $group    The field name group control value. This acts as an array container for the field.
	 *                                      For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                      full field name would end up being "bar[foo]".
	 * @param   Registry          $input    An optional Registry object with the entire data set to validate against the entire form.
	 * @param   JForm             $form     The form object for which the field is being tested.
	 *
	 * @return  boolean  True if the value is valid, false otherwise
	 */
	public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null)
	{
		$params = JComponentHelper::getParams('com_contact');
		$banned = $params->get('banned_subject');

		if ($banned)
		{
			foreach (explode(';', $banned) as $item)
			{
				if ($item != '' && StringHelper::stristr($value, $item) !== false)
				{
					return false;
				}
			}
		}

		return true;
	}
}
rules/contactemail.php000060400000003572152455302730011063 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_contact
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\String\StringHelper;

JFormHelper::loadRuleClass('email');

/**
 * JFormRule for com_contact to make sure the email address is not blocked.
 *
 * @since  1.6
 */
class JFormRuleContactEmail extends JFormRuleEmail
{
	/**
	 * Method to test for banned email addresses
	 *
	 * @param   SimpleXMLElement  $element  The SimpleXMLElement object representing the <field /> tag for the form field object.
	 * @param   mixed             $value    The form field value to validate.
	 * @param   string            $group    The field name group control value. This acts as an array container for the field.
	 *                                      For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                      full field name would end up being "bar[foo]".
	 * @param   Registry          $input    An optional Registry object with the entire data set to validate against the entire form.
	 * @param   JForm             $form     The form object for which the field is being tested.
	 *
	 * @return  boolean  True if the value is valid, false otherwise.
	 */
	public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null)
	{
		if (!parent::test($element, $value, $group, $input, $form))
		{
			return false;
		}

		$params = JComponentHelper::getParams('com_contact');
		$banned = $params->get('banned_email');

		if ($banned)
		{
			foreach (explode(';', $banned) as $item)
			{
				if ($item != '' && StringHelper::stristr($value, $item) !== false)
				{
					return false;
				}
			}
		}

		return true;
	}
}
rules/contactemailmessage.php000060400000003405152455302730012423 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_contact
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\String\StringHelper;

/**
 * JFormRule for com_contact to make sure the message body contains no banned word.
 *
 * @since  1.6
 */
class JFormRuleContactEmailMessage extends JFormRule
{
	/**
	 * Method to test a message for banned words
	 *
	 * @param   SimpleXMLElement  $element  The SimpleXMLElement object representing the <field /> tag for the form field object.
	 * @param   mixed             $value    The form field value to validate.
	 * @param   string            $group    The field name group control value. This acts as an array container for the field.
	 *                                      For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                      full field name would end up being "bar[foo]".
	 * @param   Registry          $input    An optional Registry object with the entire data set to validate against the entire form.
	 * @param   JForm             $form     The form object for which the field is being tested.
	 *
	 * @return  boolean  True if the value is valid, false otherwise.
	 */
	public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null)
	{
		$params = JComponentHelper::getParams('com_contact');
		$banned = $params->get('banned_text');

		if ($banned)
		{
			foreach (explode(';', $banned) as $item)
			{
				if ($item != '' && StringHelper::stristr($value, $item) !== false)
				{
					return false;
				}
			}
		}

		return true;
	}
}
featured.php000060400000020404152455302730007056 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_content
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

JLoader::register('ContentModelArticles', __DIR__ . '/articles.php');

/**
 * Methods supporting a list of featured article records.
 *
 * @since  1.6
 */
class ContentModelFeatured extends ContentModelArticles
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JControllerLegacy
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'title', 'a.title',
				'alias', 'a.alias',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'catid', 'a.catid', 'category_title',
				'state', 'a.state',
				'access', 'a.access', 'access_level',
				'created', 'a.created',
				'created_by', 'a.created_by',
				'created_by_alias', 'a.created_by_alias',
				'ordering', 'a.ordering',
				'featured', 'a.featured',
				'language', 'a.language',
				'hits', 'a.hits',
				'publish_up', 'a.publish_up',
				'publish_down', 'a.publish_down',
				'fp.ordering',
				'published', 'a.published',
				'author_id',
				'category_id',
				'level',
				'tag',
				'rating_count', 'rating',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$user = JFactory::getUser();

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.title, a.alias, a.checked_out, a.checked_out_time, a.catid, a.state, a.access, a.created, a.hits,' .
					'a.created_by, a.featured, a.language, a.created_by_alias, a.publish_up, a.publish_down, a.note'
			)
		);
		$query->from('#__content AS a');

		// Join over the language
		$query->select('l.title AS language_title, l.image AS language_image')
			->join('LEFT', $db->quoteName('#__languages') . ' AS l ON l.lang_code = a.language');

		// Join over the content table.
		$query->select('fp.ordering')
			->join('INNER', '#__content_frontpage AS fp ON fp.content_id = a.id');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor')
			->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');

		// Join over the asset groups.
		$query->select('ag.title AS access_level')
			->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access');

		// Join over the categories.
		$query->select('c.title AS category_title, c.created_user_id AS category_uid, c.level AS category_level')
			->join('LEFT', '#__categories AS c ON c.id = a.catid');

		// Join over the parent categories.
		$query->select('parent.title AS parent_category_title, parent.id AS parent_category_id, 
								parent.created_user_id AS parent_category_uid, parent.level AS parent_category_level')
			->join('LEFT', '#__categories AS parent ON parent.id = c.parent_id');

		// Join over the users for the author.
		$query->select('ua.name AS author_name')
			->join('LEFT', '#__users AS ua ON ua.id = a.created_by');

		// Join on voting table
		if (JPluginHelper::isEnabled('content', 'vote'))
		{
			$query->select('COALESCE(NULLIF(ROUND(v.rating_sum  / v.rating_count, 0), 0), 0) AS rating,
							COALESCE(NULLIF(v.rating_count, 0), 0) as rating_count')
				->join('LEFT', '#__content_rating AS v ON a.id = v.content_id');
		}

		// Filter by access level.
		$access = $this->getState('filter.access');

		if (is_numeric($access))
		{
			$query->where('a.access = ' . (int) $access);
		}
		elseif (is_array($access))
		{
			$access = ArrayHelper::toInteger($access);
			$access = implode(',', $access);
			$query->where('a.access IN (' . $access . ')');
		}

		// Filter by access level on categories.
		if (!$user->authorise('core.admin'))
		{
			$groups = implode(',', $user->getAuthorisedViewLevels());
			$query->where('a.access IN (' . $groups . ')');
			$query->where('c.access IN (' . $groups . ')');
		}

		// Filter by published state
		$published = $this->getState('filter.published');

		if (is_numeric($published))
		{
			$query->where('a.state = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.state = 0 OR a.state = 1)');
		}

		// Filter by a single or group of categories.
		$baselevel = 1;
		$categoryId = $this->getState('filter.category_id');

		if (is_array($categoryId) && count($categoryId) === 1)
		{
			$cat_tbl = JTable::getInstance('Category', 'JTable');
			$cat_tbl->load($categoryId[0]);
			$rgt = $cat_tbl->rgt;
			$lft = $cat_tbl->lft;
			$baselevel = (int) $cat_tbl->level;
			$query->where('c.lft >= ' . (int) $lft)
				->where('c.rgt <= ' . (int) $rgt);
		}
		elseif (is_array($categoryId))
		{
			$categoryId = implode(',', ArrayHelper::toInteger($categoryId));
			$query->where('a.catid IN (' . $categoryId . ')');
		}

		// Filter on the level.
		if ($level = $this->getState('filter.level'))
		{
			$query->where('c.level <= ' . ((int) $level + (int) $baselevel - 1));
		}

		// Filter by author
		$authorId = $this->getState('filter.author_id');

		if (is_numeric($authorId))
		{
			$type = $this->getState('filter.author_id.include', true) ? '= ' : '<>';
			$query->where('a.created_by ' . $type . (int) $authorId);
		}
		elseif (is_array($authorId))
		{
			$authorId = ArrayHelper::toInteger($authorId);
			$authorId = implode(',', $authorId);
			$query->where('a.created_by IN (' . $authorId . ')');
		}

		// Filter by search in title.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			elseif (stripos($search, 'author:') === 0)
			{
				$search = $db->quote('%' . $db->escape(substr($search, 7), true) . '%');
				$query->where('(ua.name LIKE ' . $search . ' OR ua.username LIKE ' . $search . ')');
			}
			elseif (stripos($search, 'content:') === 0)
			{
				$search = $db->quote('%' . $db->escape(substr($search, 8), true) . '%');
				$query->where('(a.introtext LIKE ' . $search . ' OR a.fulltext LIKE ' . $search . ')');
			}
			else
			{
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where('(a.title LIKE ' . $search . ' OR a.alias LIKE ' . $search . ' OR a.note LIKE ' . $search . ')');
			}
		}

		// Filter on the language.
		if ($language = $this->getState('filter.language'))
		{
			$query->where('a.language = ' . $db->quote($language));
		}

		// Filter by a single or group of tags.
		$tagId = $this->getState('filter.tag');

		if (is_array($tagId) && count($tagId) === 1)
		{
			$tagId = current($tagId);
		}

		if (is_array($tagId))
		{
			$tagId = implode(',', ArrayHelper::toInteger($tagId));

			if ($tagId)
			{
				$subQuery = $db->getQuery(true)
					->select('DISTINCT content_item_id')
					->from($db->quoteName('#__contentitem_tag_map'))
					->where('tag_id IN (' . $tagId . ')')
					->where('type_alias = ' . $db->quote('com_content.article'));

				$query->join('INNER', '(' . (string) $subQuery . ') AS tagmap ON tagmap.content_item_id = a.id');
			}
		}
		elseif ($tagId)
		{
			$query->join(
				'INNER',
				$db->quoteName('#__contentitem_tag_map', 'tagmap')
				. ' ON tagmap.tag_id = ' . (int) $tagId
				. ' AND tagmap.content_item_id = a.id'
				. ' AND tagmap.type_alias = ' . $db->quote('com_content.article')
			);
		}

		// Add the list ordering clause.
		$orderCol  = $this->state->get('list.ordering', 'a.title');
		$orderDirn = $this->state->get('list.direction', 'ASC');

		$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDirn));

		return $query;
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   3.5
	 */
	protected function populateState($ordering = 'a.title', $direction = 'asc')
	{
		parent::populateState($ordering, $direction);
	}
}
contact.php000060400000032716152455302730006723 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_contact
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;

JLoader::register('ContactHelper', JPATH_ADMINISTRATOR . '/components/com_contact/helpers/contact.php');

/**
 * Item Model for a Contact.
 *
 * @since  1.6
 */
class ContactModelContact extends JModelAdmin
{
	/**
	 * The type alias for this content type.
	 *
	 * @var    string
	 * @since  3.2
	 */
	public $typeAlias = 'com_contact.contact';

	/**
	 * The context used for the associations table
	 *
	 * @var    string
	 * @since  3.4.4
	 */
	protected $associationsContext = 'com_contact.item';

	/**
	 * Batch copy/move command. If set to false, the batch copy/move command is not supported
	 *
	 * @var  string
	 */
	protected $batch_copymove = 'category_id';

	/**
	 * Allowed batch commands
	 *
	 * @var array
	 */
	protected $batch_commands = array(
		'assetgroup_id' => 'batchAccess',
		'language_id'   => 'batchLanguage',
		'tag'           => 'batchTag',
		'user_id'       => 'batchUser',
	);

	/**
	 * Batch change a linked user.
	 *
	 * @param   integer  $value     The new value matching a User ID.
	 * @param   array    $pks       An array of row IDs.
	 * @param   array    $contexts  An array of item contexts.
	 *
	 * @return  boolean  True if successful, false otherwise and internal error is set.
	 *
	 * @since   2.5
	 */
	protected function batchUser($value, $pks, $contexts)
	{
		foreach ($pks as $pk)
		{
			if ($this->user->authorise('core.edit', $contexts[$pk]))
			{
				$this->table->reset();
				$this->table->load($pk);
				$this->table->user_id = (int) $value;

				$this->createTagsHelper($this->tagsObserver, $this->type, $pk, $this->typeAlias, $this->table);

				if (!$this->table->store())
				{
					$this->setError($this->table->getError());

					return false;
				}
			}
			else
			{
				$this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT'));

				return false;
			}
		}

		// Clean the cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 *
	 * @since   1.6
	 */
	protected function canDelete($record)
	{
		if (empty($record->id) || $record->published != -2)
		{
			return false;
		}

		return JFactory::getUser()->authorise('core.delete', 'com_contact.category.' . (int) $record->catid);
	}

	/**
	 * Method to test whether a record can have its state edited.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission set in the component.
	 *
	 * @since   1.6
	 */
	protected function canEditState($record)
	{
		// Check against the category.
		if (!empty($record->catid))
		{
			return JFactory::getUser()->authorise('core.edit.state', 'com_contact.category.' . (int) $record->catid);
		}

		// Default to component settings if category not known.
		return parent::canEditState($record);
	}

	/**
	 * Returns a Table object, always creating it
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A database object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'Contact', $prefix = 'ContactTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the row form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		JForm::addFieldPath(JPATH_ADMINISTRATOR . '/components/com_users/models/fields');

		// Get the form.
		$form = $this->loadForm('com_contact.contact', 'contact', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		// Modify the form based on access controls.
		if (!$this->canEditState((object) $data))
		{
			// Disable fields for display.
			$form->setFieldAttribute('featured', 'disabled', 'true');
			$form->setFieldAttribute('ordering', 'disabled', 'true');
			$form->setFieldAttribute('published', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is a record you can edit.
			$form->setFieldAttribute('featured', 'filter', 'unset');
			$form->setFieldAttribute('ordering', 'filter', 'unset');
			$form->setFieldAttribute('published', 'filter', 'unset');
		}

		return $form;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed  Object on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			// Convert the metadata field to an array.
			$registry = new Registry($item->metadata);
			$item->metadata = $registry->toArray();
		}

		// Load associated contact items
		$assoc = JLanguageAssociations::isEnabled();

		if ($assoc)
		{
			$item->associations = array();

			if ($item->id != null)
			{
				$associations = JLanguageAssociations::getAssociations('com_contact', '#__contact_details', 'com_contact.item', $item->id);

				foreach ($associations as $tag => $association)
				{
					$item->associations[$tag] = $association->id;
				}
			}
		}

		// Load item tags
		if (!empty($item->id))
		{
			$item->tags = new JHelperTags;
			$item->tags->getTagIds($item->id, 'com_contact.contact');
		}

		return $item;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		$app = JFactory::getApplication();

		// Check the session for previously entered form data.
		$data = $app->getUserState('com_contact.edit.contact.data', array());

		if (empty($data))
		{
			$data = $this->getItem();

			// Prime some default values.
			if ($this->getState('contact.id') == 0)
			{
				$data->set('catid', $app->input->get('catid', $app->getUserState('com_contact.contacts.filter.category_id'), 'int'));
			}
		}

		$this->preprocessData('com_contact.contact', $data);

		return $data;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.0
	 */
	public function save($data)
	{
		$input = JFactory::getApplication()->input;

		JLoader::register('CategoriesHelper', JPATH_ADMINISTRATOR . '/components/com_categories/helpers/categories.php');

		// Create new category, if needed.
		$createCategory = true;

		// If category ID is provided, check if it's valid.
		if (is_numeric($data['catid']) && $data['catid'])
		{
			$createCategory = !CategoriesHelper::validateCategoryId($data['catid'], 'com_contact');
		}

		// Save New Category
		if ($createCategory && $this->canCreateCategory())
		{
			$table = array();

			// Remove #new# prefix, if exists.
			$table['title'] = strpos($data['catid'], '#new#') === 0 ? substr($data['catid'], 5) : $data['catid'];
			$table['parent_id'] = 1;
			$table['extension'] = 'com_contact';
			$table['language'] = $data['language'];
			$table['published'] = 1;

			// Create new category and get catid back
			$data['catid'] = CategoriesHelper::createCategory($table);
		}

		// Alter the name for save as copy
		if ($input->get('task') == 'save2copy')
		{
			$origTable = clone $this->getTable();
			$origTable->load($input->getInt('id'));

			if ($data['name'] == $origTable->name)
			{
				list($name, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['name']);
				$data['name'] = $name;
				$data['alias'] = $alias;
			}
			else
			{
				if ($data['alias'] == $origTable->alias)
				{
					$data['alias'] = '';
				}
			}

			$data['published'] = 0;
		}

		$links = array('linka', 'linkb', 'linkc', 'linkd', 'linke');

		foreach ($links as $link)
		{
			if ($data['params'][$link])
			{
				$data['params'][$link] = JStringPunycode::urlToPunycode($data['params'][$link]);
			}
		}

		return parent::save($data);
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @param   JTable  $table  The JTable object
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function prepareTable($table)
	{
		$date = JFactory::getDate()->toSql();

		$table->name = htmlspecialchars_decode($table->name, ENT_QUOTES);

		$table->generateAlias();

		if (empty($table->id))
		{
			// Set the values
			$table->created = $date;

			// Set ordering to the last item if not set
			if (empty($table->ordering))
			{
				$db = $this->getDbo();
				$query = $db->getQuery(true)
					->select('MAX(ordering)')
					->from($db->quoteName('#__contact_details'));
				$db->setQuery($query);
				$max = $db->loadResult();

				$table->ordering = $max + 1;
			}
		}
		else
		{
			// Set the values
			$table->modified = $date;
			$table->modified_by = JFactory::getUser()->id;
		}

		// Increment the content version number.
		$table->version++;
	}

	/**
	 * A protected method to get a set of ordering conditions.
	 *
	 * @param   JTable  $table  A record object.
	 *
	 * @return  array  An array of conditions to add to add to ordering queries.
	 *
	 * @since   1.6
	 */
	protected function getReorderConditions($table)
	{
		return array('catid = ' . (int) $table->catid);
	}

	/**
	 * Preprocess the form.
	 *
	 * @param   JForm   $form   Form object.
	 * @param   object  $data   Data object.
	 * @param   string  $group  Group name.
	 *
	 * @return  void
	 *
	 * @since   3.0.3
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		// Determine correct permissions to check.
		if ($this->getState('contact.id'))
		{
			// Existing record. Can only edit in selected categories.
			$form->setFieldAttribute('catid', 'action', 'core.edit');
		}
		else
		{
			// New record. Can only create in selected categories.
			$form->setFieldAttribute('catid', 'action', 'core.create');
		}

		if ($this->canCreateCategory())
		{
			$form->setFieldAttribute('catid', 'allowAdd', 'true');

			// Add a prefix for categories created on the fly.
			$form->setFieldAttribute('catid', 'customPrefix', '#new#');
		}

		// Association contact items
		if (JLanguageAssociations::isEnabled())
		{
			$languages = JLanguageHelper::getContentLanguages(false, true, null, 'ordering', 'asc');

			if (count($languages) > 1)
			{
				$addform = new SimpleXMLElement('<form />');
				$fields = $addform->addChild('fields');
				$fields->addAttribute('name', 'associations');
				$fieldset = $fields->addChild('fieldset');
				$fieldset->addAttribute('name', 'item_associations');

				foreach ($languages as $language)
				{
					$field = $fieldset->addChild('field');
					$field->addAttribute('name', $language->lang_code);
					$field->addAttribute('type', 'modal_contact');
					$field->addAttribute('language', $language->lang_code);
					$field->addAttribute('label', $language->title);
					$field->addAttribute('translate_label', 'false');
					$field->addAttribute('select', 'true');
					$field->addAttribute('new', 'true');
					$field->addAttribute('edit', 'true');
					$field->addAttribute('clear', 'true');
					$field->addAttribute('propagate', 'true');
				}

				$form->load($addform, false);
			}
		}

		parent::preprocessForm($form, $data, $group);
	}

	/**
	 * Method to toggle the featured setting of contacts.
	 *
	 * @param   array    $pks    The ids of the items to toggle.
	 * @param   integer  $value  The value to toggle to.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function featured($pks, $value = 0)
	{
		// Sanitize the ids.
		$pks = ArrayHelper::toInteger((array) $pks);

		if (empty($pks))
		{
			$this->setError(JText::_('COM_CONTACT_NO_ITEM_SELECTED'));

			return false;
		}

		$table = $this->getTable();

		try
		{
			$db = $this->getDbo();

			$query = $db->getQuery(true);
			$query->update('#__contact_details');
			$query->set('featured = ' . (int) $value);
			$query->where('id IN (' . implode(',', $pks) . ')');
			$db->setQuery($query);

			$db->execute();
		}
		catch (Exception $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		$table->reorder();

		// Clean component's cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Is the user allowed to create an on the fly category?
	 *
	 * @return  boolean
	 *
	 * @since   3.6.1
	 */
	private function canCreateCategory()
	{
		return JFactory::getUser()->authorise('core.create', 'com_contact');
	}

	/**
	 * Method to validate the form data.
	 *
	 * @param   JForm   $form   The form to validate against.
	 * @param   array   $data   The data to validate.
	 * @param   string  $group  The name of the field group to validate.
	 *
	 * @return  array|boolean  Array of filtered data if valid, false otherwise.
	 *
	 * @see     JFormRule
	 * @see     JFilterInput
	 * @since   3.9.25
	 */
	public function validate($form, $data, $group = null)
	{
		// Don't allow to change the users if not allowed to access com_users.
		if (!JFactory::getUser()->authorise('core.manage', 'com_users'))
		{
			if (isset($data['created_by']))
			{
				unset($data['created_by']);
			}
		}

		return parent::validate($form, $data, $group);
	}
}
categories.php000060400000006253152455302730007412 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_newsfeeds
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;

/**
 * This models supports retrieving lists of newsfeed categories.
 *
 * @since  1.6
 */
class NewsfeedsModelCategories extends JModelList
{
	/**
	 * Model context string.
	 *
	 * @var		string
	 */
	public $_context = 'com_newsfeeds.categories';

	/**
	 * The category context (allows other extensions to derived from this model).
	 *
	 * @var		string
	 */
	protected $_extension = 'com_newsfeeds';

	private $_parent = null;

	private $_items = null;

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field
	 * @param   string  $direction  An optional direction [asc|desc]
	 *
	 * @return void
	 *
	 * @throws Exception
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		$app = JFactory::getApplication();
		$this->setState('filter.extension', $this->_extension);

		// Get the parent id if defined.
		$parentId = $app->input->getInt('id');
		$this->setState('filter.parentId', $parentId);

		$params = $app->getParams();
		$this->setState('params', $params);

		$this->setState('filter.published',	1);
		$this->setState('filter.access',	true);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.extension');
		$id .= ':' . $this->getState('filter.published');
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.parentId');

		return parent::getStoreId($id);
	}

	/**
	 * redefine the function an add some properties to make the styling more easy
	 *
	 * @return mixed An array of data items on success, false on failure.
	 */
	public function getItems()
	{
		if ($this->_items === null)
		{
			$app = JFactory::getApplication();
			$menu = $app->getMenu();
			$active = $menu->getActive();
			$params = new Registry;

			if ($active)
			{
				$params->loadString($active->params);
			}

			$options = array();
			$options['countItems'] = $params->get('show_cat_items_cat', 1) || !$params->get('show_empty_categories_cat', 0);
			$categories = JCategories::getInstance('Newsfeeds', $options);
			$this->_parent = $categories->get($this->getState('filter.parentId', 'root'));

			if (is_object($this->_parent))
			{
				$this->_items = $this->_parent->getChildren();
			}
			else
			{
				$this->_items = false;
			}
		}

		return $this->_items;
	}

	/**
	 * get the Parent
	 *
	 * @return null
	 */
	public function getParent()
	{
		if (!is_object($this->_parent))
		{
			$this->getItems();
		}

		return $this->_parent;
	}
}
request.php000060400000016533152455303130006752 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_privacy
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Router\Route;

/**
 * Request model class.
 *
 * @since  3.9.0
 */
class PrivacyModelRequest extends JModelAdmin
{
	/**
	 * Creates an information request.
	 *
	 * @param   array  $data  The data expected for the form.
	 *
	 * @return  mixed  Exception | JException | boolean
	 *
	 * @since   3.9.0
	 */
	public function createRequest($data)
	{
		// Creating requests requires the site's email sending be enabled
		if (!JFactory::getConfig()->get('mailonline', 1))
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_CANNOT_CREATE_REQUEST_WHEN_SENDMAIL_DISABLED'));

			return false;
		}

		// Get the form.
		$form = $this->getForm();		

		// Check for an error.
		if ($form instanceof Exception)
		{
			return $form;
		}

		// Filter and validate the form data.
		$data = $form->filter($data);
		$return = $form->validate($data);

		// Check for an error.
		if ($return instanceof Exception)
		{
			return $return;
		}

		// Check the validation results.
		if ($return === false)
		{
			// Get the validation messages from the form.
			foreach ($form->getErrors() as $formError)
			{
				$this->setError($formError->getMessage());
			}

			return false;
		}

		// Get the user email address
		$data['email'] = JFactory::getUser()->email;

		// Search for an open information request matching the email and type
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('COUNT(id)')
			->from('#__privacy_requests')
			->where('email = ' . $db->quote($data['email']))
			->where('request_type = ' . $db->quote($data['request_type']))
			->where('status IN (0, 1)');

		try
		{
			$result = (int) $db->setQuery($query)->loadResult();
		}
		catch (JDatabaseException $exception)
		{
			// Can't check for existing requests, so don't create a new one
			$this->setError(JText::_('COM_PRIVACY_ERROR_CHECKING_FOR_EXISTING_REQUESTS'));

			return false;
		}

		if ($result > 0)
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_PENDING_REQUEST_OPEN'));

			return false;
		}

		// Everything is good to go, create the request
		$token       = JApplicationHelper::getHash(JUserHelper::genRandomPassword());
		$hashedToken = JUserHelper::hashPassword($token);

		$data['confirm_token']            = $hashedToken;
		$data['confirm_token_created_at'] = JFactory::getDate()->toSql();

		if (!$this->save($data))
		{
			// The save function will set the error message, so just return here
			return false;
		}

		// Push a notification to the site's super users, deliberately ignoring if this process fails so the below message goes out
		JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_messages/models', 'MessagesModel');
		JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_messages/tables');

		/** @var MessagesModelMessage $messageModel */
		$messageModel = JModelLegacy::getInstance('Message', 'MessagesModel');

		$messageModel->notifySuperUsers(
			JText::_('COM_PRIVACY_ADMIN_NOTIFICATION_USER_CREATED_REQUEST_SUBJECT'),
			JText::sprintf('COM_PRIVACY_ADMIN_NOTIFICATION_USER_CREATED_REQUEST_MESSAGE', $data['email'])
		);

		// The mailer can be set to either throw Exceptions or return boolean false, account for both
		try
		{
			$app = JFactory::getApplication();

			$linkMode = $app->get('force_ssl', 0) == 2 ? Route::TLS_FORCE : Route::TLS_IGNORE;

			$substitutions = array(
				'[SITENAME]' => $app->get('sitename'),
				'[URL]'      => JUri::root(),
				'[TOKENURL]' => JRoute::link('site', 'index.php?option=com_privacy&view=confirm&confirm_token=' . $token, false, $linkMode, true),
				'[FORMURL]'  => JRoute::link('site', 'index.php?option=com_privacy&view=confirm', false, $linkMode, true),
				'[TOKEN]'    => $token,
				'\\n'        => "\n",
			);

			switch ($data['request_type'])
			{
				case 'export':
					$emailSubject = JText::_('COM_PRIVACY_EMAIL_REQUEST_SUBJECT_EXPORT_REQUEST');
					$emailBody    = JText::_('COM_PRIVACY_EMAIL_REQUEST_BODY_EXPORT_REQUEST');

					break;

				case 'remove':
					$emailSubject = JText::_('COM_PRIVACY_EMAIL_REQUEST_SUBJECT_REMOVE_REQUEST');
					$emailBody    = JText::_('COM_PRIVACY_EMAIL_REQUEST_BODY_REMOVE_REQUEST');

					break;

				default:
					$this->setError(JText::_('COM_PRIVACY_ERROR_UNKNOWN_REQUEST_TYPE'));

					return false;
			}

			foreach ($substitutions as $k => $v)
			{
				$emailSubject = str_replace($k, $v, $emailSubject);
				$emailBody    = str_replace($k, $v, $emailBody);
			}

			$mailer = JFactory::getMailer();
			$mailer->setSubject($emailSubject);
			$mailer->setBody($emailBody);
			$mailer->addRecipient($data['email']);

			$mailResult = $mailer->Send();

			if ($mailResult instanceof JException)
			{
				// JError was already called so we just need to return now
				return false;
			}
			elseif ($mailResult === false)
			{
				$this->setError($mailer->ErrorInfo);

				return false;
			}

			/** @var PrivacyTableRequest $table */
			$table = $this->getTable();

			if (!$table->load($this->getState($this->getName() . '.id')))
			{
				$this->setError($table->getError());

				return false;
			}

			// Log the request's creation
			JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_actionlogs/models', 'ActionlogsModel');

			$message = array(
				'action'       => 'request-created',
				'requesttype'  => $table->request_type,
				'subjectemail' => $table->email,
				'id'           => $table->id,
				'itemlink'     => 'index.php?option=com_privacy&view=request&id=' . $table->id,
			);

			/** @var ActionlogsModelActionlog $model */
			$model = JModelLegacy::getInstance('Actionlog', 'ActionlogsModel');
			$model->addLog(array($message), 'COM_PRIVACY_ACTION_LOG_CREATED_REQUEST', 'com_privacy.request');

			// The email sent and the record is saved, everything is good to go from here
			return true;
		}
		catch (phpmailerException $exception)
		{
			$this->setError($exception->getMessage());

			return false;
		}
	}

	/**
	 * Method for getting the form from the model.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   3.9.0
	 */
	public function getForm($data = array(), $loadData = true)
	{
		return $this->loadForm('com_privacy.request', 'request', array('control' => 'jform'));
	}

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $name     The table name. Optional.
	 * @param   string  $prefix   The class prefix. Optional.
	 * @param   array   $options  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   3.9.0
	 * @throws  \Exception
	 */
	public function getTable($name = 'Request', $prefix = 'PrivacyTable', $options = array())
	{
		return parent::getTable($name, $prefix, $options);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   3.9.0
	 */
	protected function populateState()
	{
		// Get the application object.
		$params = JFactory::getApplication()->getParams('com_privacy');

		// Load the parameters.
		$this->setState('params', $params);
	}
}
forms/remind.xml000060400000001034152455303130007665 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset name="default" label="COM_PRIVACY_REMIND_REQUEST_FIELDSET_LABEL">
		<field
			name="email"
			type="text"
			label="JGLOBAL_EMAIL"
			description="COM_PRIVACY_FIELD_CONFIRM_EMAIL_DESC"
			validate="email"
			required="true"
			size="30"
		/>

		<field
			name="remind_token"
			type="text"
			label="COM_PRIVACY_FIELD_REMIND_CONFIRM_TOKEN_LABEL"
			description="COM_PRIVACY_FIELD_REMIND_CONFIRM_TOKEN_DESC"
			filter="alnum"
			required="true"
			size="32"
		/>
	</fieldset>
</form>
forms/request.xml000060400000000705152455303130010103 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset name="default">
		<field
			name="request_type"
			type="list"
			label="COM_PRIVACY_FIELD_REQUEST_TYPE_LABEL"
			description="COM_PRIVACY_FIELD_REQUEST_TYPE_DESC"
			filter="string"
			default="export"
			validate="options"
			>
			<option value="export">COM_PRIVACY_REQUEST_TYPE_EXPORT</option>
			<option value="remove">COM_PRIVACY_REQUEST_TYPE_REMOVE</option>
		</field>
	</fieldset>
</form>
forms/confirm.xml000060400000000557152455303130010055 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset name="default" label="COM_PRIVACY_CONFIRM_REQUEST_FIELDSET_LABEL">
		<field
			name="confirm_token"
			type="text"
			label="COM_PRIVACY_FIELD_CONFIRM_CONFIRM_TOKEN_LABEL"
			description="COM_PRIVACY_FIELD_CONFIRM_CONFIRM_TOKEN_DESC"
			filter="alnum"
			required="true"
			size="32"
		/>
	</fieldset>
</form>
confirm.php000060400000013151152455303130006710 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_privacy
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Request confirmation model class.
 *
 * @since  3.9.0
 */
class PrivacyModelConfirm extends JModelAdmin
{
	/**
	 * Confirms the information request.
	 *
	 * @param   array  $data  The data expected for the form.
	 *
	 * @return  mixed  Exception | JException | boolean
	 *
	 * @since   3.9.0
	 */
	public function confirmRequest($data)
	{
		// Get the form.
		$form = $this->getForm();

		// Check for an error.
		if ($form instanceof Exception)
		{
			return $form;
		}

		// Filter and validate the form data.
		$data = $form->filter($data);
		$return = $form->validate($data);

		// Check for an error.
		if ($return instanceof Exception)
		{
			return $return;
		}

		// Check the validation results.
		if ($return === false)
		{
			// Get the validation messages from the form.
			foreach ($form->getErrors() as $formError)
			{
				$this->setError($formError->getMessage());
			}

			return false;
		}

		// Get the user email address
		$data['email'] = JFactory::getUser()->email;

		// Search for the information request
		/** @var PrivacyTableRequest $table */
		$table = $this->getTable();

		if (!$table->load(array('email' => $data['email'], 'status' => 0)))
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_NO_PENDING_REQUESTS'));

			return false;
		}

		// A request can only be confirmed if it is in a pending status and has a confirmation token
		if ($table->status != '0' || !$table->confirm_token)
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_NO_PENDING_REQUESTS'));

			return false;
		}

		// A request can only be confirmed if the token is less than 24 hours old
		$confirmTokenCreatedAt = new JDate($table->confirm_token_created_at);
		$confirmTokenCreatedAt->add(new DateInterval('P1D'));

		$now = new JDate('now');

		if ($now > $confirmTokenCreatedAt)
		{
			// Invalidate the request
			$table->status = -1;
			$table->confirm_token = '';

			try
			{
				$table->store();
			}
			catch (JDatabaseException $exception)
			{
				// The error will be logged in the database API, we just need to catch it here to not let things fatal out
			}

			$this->setError(JText::_('COM_PRIVACY_ERROR_CONFIRM_TOKEN_EXPIRED'));

			return false;
		}

		// Verify the token
		if (!JUserHelper::verifyPassword($data['confirm_token'], $table->confirm_token))
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_NO_PENDING_REQUESTS'));

			return false;
		}

		// Everything is good to go, transition the request to confirmed
		$saved = $this->save(
			array(
				'id'     => $table->id,
				'status' => 1,
				'confirm_token' => '',
			)
		);

		if (!$saved)
		{
			// Error was set by the save method
			return false;
		}

		// Push a notification to the site's super users, deliberately ignoring if this process fails so the below message goes out
		JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_messages/models', 'MessagesModel');
		JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_messages/tables');

		/** @var MessagesModelMessage $messageModel */
		$messageModel = JModelLegacy::getInstance('Message', 'MessagesModel');

		$messageModel->notifySuperUsers(
			JText::_('COM_PRIVACY_ADMIN_NOTIFICATION_USER_CONFIRMED_REQUEST_SUBJECT'),
			JText::sprintf('COM_PRIVACY_ADMIN_NOTIFICATION_USER_CONFIRMED_REQUEST_MESSAGE', $table->email)
		);

		JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_actionlogs/models', 'ActionlogsModel');

		$message = array(
			'action'       => 'request-confirmed',
			'subjectemail' => $table->email,
			'id'           => $table->id,
			'itemlink'     => 'index.php?option=com_privacy&view=request&id=' . $table->id,
		);

		/** @var ActionlogsModelActionlog $model */
		$model = JModelLegacy::getInstance('Actionlog', 'ActionlogsModel');
		$model->addLog(array($message), 'COM_PRIVACY_ACTION_LOG_CONFIRMED_REQUEST', 'com_privacy.request');

		return true;
	}

	/**
	 * Method for getting the form from the model.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   3.9.0
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_privacy.confirm', 'confirm', array('control' => 'jform'));

		if (empty($form))
		{
			return false;
		}

		$input = JFactory::getApplication()->input;

		if ($input->getMethod() === 'GET')
		{
			$form->setValue('confirm_token', '', $input->get->getAlnum('confirm_token'));
		}

		return $form;
	}

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $name     The table name. Optional.
	 * @param   string  $prefix   The class prefix. Optional.
	 * @param   array   $options  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   3.9.0
	 * @throws  \Exception
	 */
	public function getTable($name = 'Request', $prefix = 'PrivacyTable', $options = array())
	{
		return parent::getTable($name, $prefix, $options);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   3.9.0
	 */
	protected function populateState()
	{
		// Get the application object.
		$params = JFactory::getApplication()->getParams('com_privacy');

		// Load the parameters.
		$this->setState('params', $params);
	}
}
remind.php000060400000010055152455303130006531 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_privacy
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Remind confirmation model class.
 *
 * @since  3.9.0
 */
class PrivacyModelRemind extends JModelAdmin
{
	/**
	 * Confirms the remind request.
	 *
	 * @param   array  $data  The data expected for the form.
	 *
	 * @return  mixed  Exception | JException | boolean
	 *
	 * @since   3.9.0
	 */
	public function remindRequest($data)
	{
		// Get the form.
		$form = $this->getForm();
		$data['email'] = JStringPunycode::emailToPunycode($data['email']);

		// Check for an error.
		if ($form instanceof Exception)
		{
			return $form;
		}

		// Filter and validate the form data.
		$data = $form->filter($data);
		$return = $form->validate($data);

		// Check for an error.
		if ($return instanceof Exception)
		{
			return $return;
		}

		// Check the validation results.
		if ($return === false)
		{
			// Get the validation messages from the form.
			foreach ($form->getErrors() as $formError)
			{
				$this->setError($formError->getMessage());
			}

			return false;
		}

		/** @var PrivacyTableConsent $table */
		$table = $this->getTable();

		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select($db->quoteName(array('r.id', 'r.user_id', 'r.token')));
		$query->from($db->quoteName('#__privacy_consents', 'r'));
		$query->join('LEFT', $db->quoteName('#__users', 'u') . ' ON u.id = r.user_id');
		$query->where($db->quoteName('u.email') . ' = ' . $db->quote($data['email']));
		$query->where($db->quoteName('r.remind') . ' = 1');
		$db->setQuery($query);

		try
		{
			$remind = $db->loadObject();
		}
		catch (RuntimeException $e)
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_NO_PENDING_REMIND'));

			return false;
		}

		if (!$remind)
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_NO_PENDING_REMIND'));

			return false;
		}

		// Verify the token
		if (!JUserHelper::verifyPassword($data['remind_token'], $remind->token))
		{
			$this->setError(JText::_('COM_PRIVACY_ERROR_NO_REMIND_REQUESTS'));

			return false;
		}

		// Everything is good to go, transition the request to extended
		$saved = $this->save(
			array(
				'id'      => $remind->id,
				'remind'  => 0,
				'token'   => '',
				'created' => JFactory::getDate()->toSql(),
			)
		);

		if (!$saved)
		{
			// Error was set by the save method
			return false;
		}

		return true;
	}

	/**
	 * Method for getting the form from the model.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   3.9.0
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_privacy.remind', 'remind', array('control' => 'jform'));

		if (empty($form))
		{
			return false;
		}

		$input = JFactory::getApplication()->input;

		if ($input->getMethod() === 'GET')
		{
			$form->setValue('remind_token', '', $input->get->getAlnum('remind_token'));
		}

		return $form;
	}

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $name     The table name. Optional.
	 * @param   string  $prefix   The class prefix. Optional.
	 * @param   array   $options  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   3.9.0
	 * @throws  \Exception
	 */
	public function getTable($name = 'Consent', $prefix = 'PrivacyTable', $options = array())
	{
		return parent::getTable($name, $prefix, $options);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   3.9.0
	 */
	protected function populateState()
	{
		// Get the application object.
		$params = JFactory::getApplication()->getParams('com_privacy');

		// Load the parameters.
		$this->setState('params', $params);
	}
}
archive.php000060400000013044152455312760006706 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_content
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

JLoader::register('ContentModelArticles', __DIR__ . '/articles.php');

/**
 * Content Component Archive Model
 *
 * @since  1.5
 */
class ContentModelArchive extends ContentModelArticles
{
	/**
	 * Model context string.
	 *
	 * @var		string
	 */
	public $_context = 'com_content.archive';

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   The field to order on.
	 * @param   string  $direction  The direction to order on.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		parent::populateState();

		$app = JFactory::getApplication();

		// Add archive properties
		$params = $this->state->params;

		// Filter on archived articles
		$this->setState('filter.published', 2);

		// Filter on month, year
		$this->setState('filter.month', $app->input->getInt('month'));
		$this->setState('filter.year', $app->input->getInt('year'));

		// Optional filter text
		$this->setState('list.filter', $app->input->getString('filter-search'));

		// Get list limit
		$itemid = $app->input->get('Itemid', 0, 'int');
		$limit = $app->getUserStateFromRequest('com_content.archive.list' . $itemid . '.limit', 'limit', $params->get('display_num'), 'uint');
		$this->setState('list.limit', $limit);

		// Set the archive ordering
		$articleOrderby   = $params->get('orderby_sec', 'rdate');
		$articleOrderDate = $params->get('order_date');

		// No category ordering
		$secondary = ContentHelperQuery::orderbySecondary($articleOrderby, $articleOrderDate);

		$this->setState('list.ordering', $secondary . ', a.created DESC');
		$this->setState('list.direction', '');
	}

	/**
	 * Get the master query for retrieving a list of articles subject to the model state.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		$params           = $this->state->params;
		$app              = JFactory::getApplication('site');
		$catids           = ArrayHelper::toInteger($app->input->get('catid', array(), 'array'));
		$catids           = array_values(array_diff($catids, array(0)));
		$articleOrderDate = $params->get('order_date');

		// Create a new query object.
		$query = parent::getListQuery();

			// Add routing for archive
			// Sqlsrv changes
		$case_when = ' CASE WHEN ';
		$case_when .= $query->charLength('a.alias', '!=', '0');
		$case_when .= ' THEN ';
		$a_id = $query->castAsChar('a.id');
		$case_when .= $query->concatenate(array($a_id, 'a.alias'), ':');
		$case_when .= ' ELSE ';
		$case_when .= $a_id . ' END as slug';

		$query->select($case_when);

		$case_when = ' CASE WHEN ';
		$case_when .= $query->charLength('c.alias', '!=', '0');
		$case_when .= ' THEN ';
		$c_id = $query->castAsChar('c.id');
		$case_when .= $query->concatenate(array($c_id, 'c.alias'), ':');
		$case_when .= ' ELSE ';
		$case_when .= $c_id . ' END as catslug';
		$query->select($case_when);

		// Filter on month, year
		// First, get the date field
		$queryDate = ContentHelperQuery::getQueryDate($articleOrderDate);

		if ($month = $this->getState('filter.month'))
		{
			$query->where($query->month($queryDate) . ' = ' . $month);
		}

		if ($year = $this->getState('filter.year'))
		{
			$query->where($query->year($queryDate) . ' = ' . $year);
		}

		if (count($catids) > 0)
		{
			$query->where('c.id IN (' . implode(', ', $catids) . ')');
		}

		return $query;
	}

	/**
	 * Method to get the archived article list
	 *
	 * @access public
	 * @return array
	 */
	public function getData()
	{
		$app = JFactory::getApplication();

		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			// Get the page/component configuration
			$params = $app->getParams();

			// Get the pagination request variables
			$limit      = $app->input->get('limit', $params->get('display_num', 20), 'uint');
			$limitstart = $app->input->get('limitstart', 0, 'uint');

			$query = $this->_buildQuery();

			$this->_data = $this->_getList($query, $limitstart, $limit);
		}

		return $this->_data;
	}

	/**
	 * JModelLegacy override to add alternating value for $odd
	 *
	 * @param   string   $query       The query.
	 * @param   integer  $limitstart  Offset.
	 * @param   integer  $limit       The number of records.
	 *
	 * @return  array  An array of results.
	 *
	 * @since   3.0.1
	 * @throws  RuntimeException
	 */
	protected function _getList($query, $limitstart=0, $limit=0)
	{
		$result = parent::_getList($query, $limitstart, $limit);

		$odd = 1;

		foreach ($result as $k => $row)
		{
			$result[$k]->odd = $odd;
			$odd = 1 - $odd;
		}

		return $result;
	}

	/**
	 * Gets the archived articles years
	 *
	 * @return   array
	 *
	 * @since    3.6.0
	 */
	public function getYears()
	{
		$db = $this->getDbo();
		$nullDate = $db->quote($db->getNullDate());
		$nowDate  = $db->quote(JFactory::getDate()->toSql());

		$query = $db->getQuery(true);
		$years = $query->year($db->qn('created'));
		$query->select('DISTINCT (' . $years . ')')
			->from($db->qn('#__content'))
			->where($db->qn('state') . '= 2')
			->where('(publish_up = ' . $nullDate . ' OR publish_up <= ' . $nowDate . ')')
			->where('(publish_down = ' . $nullDate . ' OR publish_down >= ' . $nowDate . ')')
			->order('1 ASC');

		$db->setQuery($query);

		return $db->loadColumn();
	}
}
article.php000060400000060526152455312760006717 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_content
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;

JLoader::register('ContentHelper', JPATH_ADMINISTRATOR . '/components/com_content/helpers/content.php');

/**
 * Item Model for an Article.
 *
 * @since  1.6
 */
class ContentModelArticle extends JModelAdmin
{
	/**
	 * The prefix to use with controller messages.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $text_prefix = 'COM_CONTENT';

	/**
	 * The type alias for this content type (for example, 'com_content.article').
	 *
	 * @var    string
	 * @since  3.2
	 */
	public $typeAlias = 'com_content.article';

	/**
	 * The context used for the associations table
	 *
	 * @var    string
	 * @since  3.4.4
	 */
	protected $associationsContext = 'com_content.item';

	/**
	 * Function that can be overridden to do any data cleanup after batch copying data
	 *
	 * @param   \JTableInterface  $table  The table object containing the newly created item
	 * @param   integer           $newId  The id of the new item
	 * @param   integer           $oldId  The original item id
	 *
	 * @return  void
	 *
	 * @since  3.8.12
	 */
	protected function cleanupPostBatchCopy(\JTableInterface $table, $newId, $oldId)
	{
		// Check if the article was featured and update the #__content_frontpage table
		if ($table->featured == 1)
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->insert($db->quoteName('#__content_frontpage'))
				->values($newId . ', 0');
			$db->setQuery($query);
			$db->execute();
		}

		// Register FieldsHelper
		JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');

		$oldItem = $this->getTable();
		$oldItem->load($oldId);
		$fields = FieldsHelper::getFields('com_content.article', $oldItem, true);

		$fieldsData = array();

		if (!empty($fields))
		{
			$fieldsData['com_fields'] = array();

			foreach ($fields as $field)
			{
				$fieldsData['com_fields'][$field->name] = $field->rawvalue;
			}
		}

		JEventDispatcher::getInstance()->trigger('onContentAfterSave', array('com_content.article', &$this->table, true, $fieldsData));
	}

	/**
	 * Batch move categories to a new category.
	 *
	 * @param   integer  $value     The new category ID.
	 * @param   array    $pks       An array of row IDs.
	 * @param   array    $contexts  An array of item contexts.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.8.6
	 */
	protected function batchMove($value, $pks, $contexts)
	{
		if (empty($this->batchSet))
		{
			// Set some needed variables.
			$this->user = JFactory::getUser();
			$this->table = $this->getTable();
			$this->tableClassName = get_class($this->table);
			$this->contentType = new JUcmType;
			$this->type = $this->contentType->getTypeByTable($this->tableClassName);
		}

		$categoryId = (int) $value;

		if (!$this->checkCategoryId($categoryId))
		{
			return false;
		}

		JPluginHelper::importPlugin('system');
		$dispatcher = JEventDispatcher::getInstance();

		// Register FieldsHelper
		JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');

		// Parent exists so we proceed
		foreach ($pks as $pk)
		{
			if (!$this->user->authorise('core.edit', $contexts[$pk]))
			{
				$this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT'));

				return false;
			}

			// Check that the row actually exists
			if (!$this->table->load($pk))
			{
				if ($error = $this->table->getError())
				{
					// Fatal error
					$this->setError($error);

					return false;
				}
				else
				{
					// Not fatal error
					$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk));
					continue;
				}
			}

			$fields = FieldsHelper::getFields('com_content.article', $this->table, true);
			$fieldsData = array();

			if (!empty($fields))
			{
				$fieldsData['com_fields'] = array();

				foreach ($fields as $field)
				{
					$fieldsData['com_fields'][$field->name] = $field->rawvalue;
				}
			}

			// Set the new category ID
			$this->table->catid = $categoryId;

			// Check the row.
			if (!$this->table->check())
			{
				$this->setError($this->table->getError());

				return false;
			}

			if (!empty($this->type))
			{
				$this->createTagsHelper($this->tagsObserver, $this->type, $pk, $this->typeAlias, $this->table);
			}

			// Store the row.
			if (!$this->table->store())
			{
				$this->setError($this->table->getError());

				return false;
			}

			// Run event for moved article
			$dispatcher->trigger('onContentAfterSave', array('com_content.article', &$this->table, false, $fieldsData));
		}

		// Clean the cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 *
	 * @since   1.6
	 */
	protected function canDelete($record)
	{
		if (empty($record->id) || $record->state != -2)
		{
			return false;
		}

		return JFactory::getUser()->authorise('core.delete', 'com_content.article.' . (int) $record->id);
	}

	/**
	 * Method to test whether a record can have its state edited.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission set in the component.
	 *
	 * @since   1.6
	 */
	protected function canEditState($record)
	{
		$user = JFactory::getUser();

		// Check for existing article.
		if (!empty($record->id))
		{
			return $user->authorise('core.edit.state', 'com_content.article.' . (int) $record->id);
		}

		// New article, so check against the category.
		if (!empty($record->catid))
		{
			return $user->authorise('core.edit.state', 'com_content.category.' . (int) $record->catid);
		}

		// Default to component settings if neither article nor category known.
		return parent::canEditState($record);
	}

	/**
	 * Prepare and sanitise the table data prior to saving.
	 *
	 * @param   JTable  $table  A JTable object.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function prepareTable($table)
	{
		// Set the publish date to now
		if ($table->state == 1 && (int) $table->publish_up == 0)
		{
			$table->publish_up = JFactory::getDate()->toSql();
		}

		if ($table->state == 1 && intval($table->publish_down) == 0)
		{
			$table->publish_down = $this->getDbo()->getNullDate();
		}

		// Increment the content version number.
		$table->version++;

		// Reorder the articles within the category so the new article is first
		if (empty($table->id))
		{
			$table->reorder('catid = ' . (int) $table->catid . ' AND state >= 0');
		}
	}

	/**
	 * Returns a Table object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable    A database object
	 */
	public function getTable($type = 'Content', $prefix = 'JTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed  Object on success, false on failure.
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			// Convert the params field to an array.
			$registry = new Registry($item->attribs);
			$item->attribs = $registry->toArray();

			// Convert the metadata field to an array.
			$registry = new Registry($item->metadata);
			$item->metadata = $registry->toArray();

			// Convert the images field to an array.
			$registry = new Registry($item->images);
			$item->images = $registry->toArray();

			// Convert the urls field to an array.
			$registry = new Registry($item->urls);
			$item->urls = $registry->toArray();

			$item->articletext = trim($item->fulltext) != '' ? $item->introtext . "<hr id=\"system-readmore\" />" . $item->fulltext : $item->introtext;

			if (!empty($item->id))
			{
				$item->tags = new JHelperTags;
				$item->tags->getTagIds($item->id, 'com_content.article');
			}
		}

		// Load associated content items
		$assoc = JLanguageAssociations::isEnabled();

		if ($assoc)
		{
			$item->associations = array();

			if ($item->id != null)
			{
				$associations = JLanguageAssociations::getAssociations('com_content', '#__content', 'com_content.item', $item->id);

				foreach ($associations as $tag => $association)
				{
					$item->associations[$tag] = $association->id;
				}
			}
		}

		return $item;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		$app = JFactory::getApplication();
		$user = JFactory::getUser();

		// Get the form.
		$form = $this->loadForm('com_content.article', 'article', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		$jinput = JFactory::getApplication()->input;

		/*
		 * The front end calls this model and uses a_id to avoid id clashes so we need to check for that first.
		 * The back end uses id so we use that the rest of the time and set it to 0 by default.
		 */
		$id = (int) $jinput->get('a_id', $jinput->get('id', 0));

		// Determine correct permissions to check.
		if ($id = $this->getState('article.id', $id))
		{
			// Existing record. Can only edit in selected categories.
			$form->setFieldAttribute('catid', 'action', 'core.edit');

			// Existing record. Can only edit own articles in selected categories.
			if ($app->isClient('administrator'))
			{
				$form->setFieldAttribute('catid', 'action', 'core.edit.own');
			}
			else
			// Existing record. We can't edit the category in frontend if not edit.state.
			{
				if ($id != 0 && (!$user->authorise('core.edit.state', 'com_content.article.' . (int) $id))
					|| ($id == 0 && !$user->authorise('core.edit.state', 'com_content')))
				{
					$form->setFieldAttribute('catid', 'readonly', 'true');
					$form->setFieldAttribute('catid', 'required', 'false');
					$form->setFieldAttribute('catid', 'filter', 'unset');
				}
			}
		}
		else
		{
			// New record. Can only create in selected categories.
			$form->setFieldAttribute('catid', 'action', 'core.create');
		}

		// Object uses for checking edit state permission of article
		$record = new stdClass;
		$record->id = $id;

		// Get the category which the article is being added to
		if (!empty($data['catid']))
		{
			$catId = (int) $data['catid'];
		}
		else
		{
			$catIds  = $form->getValue('catid');

			$catId = is_array($catIds)
				? (int) reset($catIds)
				: (int) $catIds;

			if (!$catId)
			{
				$catId = (int) $form->getFieldAttribute('catid', 'default', 0);
			}
		}

		$record->catid = $catId;

		// Modify the form based on Edit State access controls.
		if (!$this->canEditState($record))
		{
			// Disable fields for display.
			$form->setFieldAttribute('featured', 'disabled', 'true');
			$form->setFieldAttribute('ordering', 'disabled', 'true');
			$form->setFieldAttribute('publish_up', 'disabled', 'true');
			$form->setFieldAttribute('publish_down', 'disabled', 'true');
			$form->setFieldAttribute('state', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is an article you can edit.
			$form->setFieldAttribute('featured', 'filter', 'unset');
			$form->setFieldAttribute('ordering', 'filter', 'unset');
			$form->setFieldAttribute('publish_up', 'filter', 'unset');
			$form->setFieldAttribute('publish_down', 'filter', 'unset');
			$form->setFieldAttribute('state', 'filter', 'unset');
		}

		// Prevent messing with article language and category when editing existing article with associations
		$assoc = JLanguageAssociations::isEnabled();

		// Check if article is associated
		if ($this->getState('article.id') && $app->isClient('site') && $assoc)
		{
			$associations = JLanguageAssociations::getAssociations('com_content', '#__content', 'com_content.item', $id);

			// Make fields read only
			if (!empty($associations))
			{
				$form->setFieldAttribute('language', 'readonly', 'true');
				$form->setFieldAttribute('catid', 'readonly', 'true');
				$form->setFieldAttribute('language', 'filter', 'unset');
				$form->setFieldAttribute('catid', 'filter', 'unset');
			}
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$app  = JFactory::getApplication();
		$data = $app->getUserState('com_content.edit.article.data', array());

		if (empty($data))
		{
			$data = $this->getItem();

			// Pre-select some filters (Status, Category, Language, Access) in edit form if those have been selected in Article Manager: Articles
			if ($this->getState('article.id') == 0)
			{
				$filters = (array) $app->getUserState('com_content.articles.filter');
				$data->set(
					'state',
					$app->input->getInt(
						'state',
						((isset($filters['published']) && $filters['published'] !== '') ? $filters['published'] : null)
					)
				);
				$data->set('catid', $app->input->getInt('catid', (!empty($filters['category_id']) ? $filters['category_id'] : null)));
				$data->set('language', $app->input->getString('language', (!empty($filters['language']) ? $filters['language'] : null)));
				$data->set('access',
					$app->input->getInt('access', (!empty($filters['access']) ? $filters['access'] : JFactory::getConfig()->get('access')))
				);
			}
		}

		// If there are params fieldsets in the form it will fail with a registry object
		if (isset($data->params) && $data->params instanceof Registry)
		{
			$data->params = $data->params->toArray();
		}

		$this->preprocessData('com_content.article', $data);

		return $data;
	}

	/**
	 * Method to validate the form data.
	 *
	 * @param   JForm   $form   The form to validate against.
	 * @param   array   $data   The data to validate.
	 * @param   string  $group  The name of the field group to validate.
	 *
	 * @return  array|boolean  Array of filtered data if valid, false otherwise.
	 *
	 * @see     JFormRule
	 * @see     JFilterInput
	 * @since   3.7.0
	 */
	public function validate($form, $data, $group = null)
	{
		// Don't allow to change the users if not allowed to access com_users.
		if (!JFactory::getUser()->authorise('core.manage', 'com_users'))
		{
			if (isset($data['created_by']))
			{
				unset($data['created_by']);
			}
		}

		if (!JFactory::getUser()->authorise('core.admin', 'com_content'))
		{
			if (isset($data['rules']))
			{
				unset($data['rules']);
			}
		}

		return parent::validate($form, $data, $group);
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		$input  = JFactory::getApplication()->input;
		$filter = JFilterInput::getInstance();

		if (isset($data['metadata']) && isset($data['metadata']['author']))
		{
			$data['metadata']['author'] = $filter->clean($data['metadata']['author'], 'TRIM');
		}

		if (isset($data['created_by_alias']))
		{
			$data['created_by_alias'] = $filter->clean($data['created_by_alias'], 'TRIM');
		}

		if (isset($data['images']) && is_array($data['images']))
		{
			$registry = new Registry($data['images']);

			$data['images'] = (string) $registry;
		}

		JLoader::register('CategoriesHelper', JPATH_ADMINISTRATOR . '/components/com_categories/helpers/categories.php');

		// Create new category, if needed.
		$createCategory = true;

		// If category ID is provided, check if it's valid.
		if (is_numeric($data['catid']) && $data['catid'])
		{
			$createCategory = !CategoriesHelper::validateCategoryId($data['catid'], 'com_content');
		}

		// Save New Category
		if ($createCategory && $this->canCreateCategory())
		{
			$table = array();

			// Remove #new# prefix, if exists.
			$table['title'] = strpos($data['catid'], '#new#') === 0 ? substr($data['catid'], 5) : $data['catid'];
			$table['parent_id'] = 1;
			$table['extension'] = 'com_content';
			$table['language'] = $data['language'];
			$table['published'] = 1;

			// Create new category and get catid back
			$data['catid'] = CategoriesHelper::createCategory($table);
		}

		if (isset($data['urls']) && is_array($data['urls']))
		{
			$check = $input->post->get('jform', array(), 'array');

			foreach ($data['urls'] as $i => $url)
			{
				if ($url != false && ($i == 'urla' || $i == 'urlb' || $i == 'urlc'))
				{
					if (preg_match('~^#[a-zA-Z]{1}[a-zA-Z0-9-_:.]*$~', $check['urls'][$i]) == 1)
					{
						$data['urls'][$i] = $check['urls'][$i];
					}
					else
					{
						$data['urls'][$i] = JStringPunycode::urlToPunycode($url);
					}
				}
			}

			unset($check);

			$registry = new Registry($data['urls']);

			$data['urls'] = (string) $registry;
		}

		// Alter the title for save as copy
		if ($input->get('task') == 'save2copy')
		{
			$origTable = clone $this->getTable();
			$origTable->load($input->getInt('id'));

			if ($data['title'] == $origTable->title)
			{
				list($title, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']);
				$data['title'] = $title;
				$data['alias'] = $alias;
			}
			else
			{
				if ($data['alias'] == $origTable->alias)
				{
					$data['alias'] = '';
				}
			}

			$data['state'] = 0;
		}

		// Automatic handling of alias for empty fields
		if (in_array($input->get('task'), array('apply', 'save', 'save2new')) && (!isset($data['id']) || (int) $data['id'] == 0))
		{
			if ($data['alias'] == null)
			{
				if (JFactory::getConfig()->get('unicodeslugs') == 1)
				{
					$data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['title']);
				}
				else
				{
					$data['alias'] = JFilterOutput::stringURLSafe($data['title']);
				}

				$table = JTable::getInstance('Content', 'JTable');

				if ($table->load(array('alias' => $data['alias'], 'catid' => $data['catid'])))
				{
					$msg = JText::_('COM_CONTENT_SAVE_WARNING');
				}

				list($title, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']);
				$data['alias'] = $alias;

				if (isset($msg))
				{
					JFactory::getApplication()->enqueueMessage($msg, 'warning');
				}
			}
		}

		if (parent::save($data))
		{
			if (isset($data['featured']))
			{
				$this->featured($this->getState($this->getName() . '.id'), $data['featured']);
			}

			return true;
		}

		return false;
	}

	/**
	 * Method to toggle the featured setting of articles.
	 *
	 * @param   array    $pks    The ids of the items to toggle.
	 * @param   integer  $value  The value to toggle to.
	 *
	 * @return  boolean  True on success.
	 */
	public function featured($pks, $value = 0)
	{
		// Sanitize the ids.
		$pks = (array) $pks;
		$pks = ArrayHelper::toInteger($pks);

		if (empty($pks))
		{
			$this->setError(JText::_('COM_CONTENT_NO_ITEM_SELECTED'));

			return false;
		}

		$table = $this->getTable('Featured', 'ContentTable');

		try
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->update($db->quoteName('#__content'))
				->set('featured = ' . (int) $value)
				->where('id IN (' . implode(',', $pks) . ')');
			$db->setQuery($query);
			$db->execute();

			if ((int) $value == 0)
			{
				// Adjust the mapping table.
				// Clear the existing features settings.
				$query = $db->getQuery(true)
					->delete($db->quoteName('#__content_frontpage'))
					->where('content_id IN (' . implode(',', $pks) . ')');
				$db->setQuery($query);
				$db->execute();
			}
			else
			{
				// First, we find out which of our new featured articles are already featured.
				$query = $db->getQuery(true)
					->select('f.content_id')
					->from('#__content_frontpage AS f')
					->where('content_id IN (' . implode(',', $pks) . ')');
				$db->setQuery($query);

				$oldFeatured = $db->loadColumn();

				// We diff the arrays to get a list of the articles that are newly featured
				$newFeatured = array_diff($pks, $oldFeatured);

				// Featuring.
				$tuples = array();

				foreach ($newFeatured as $pk)
				{
					$tuples[] = $pk . ', 0';
				}

				if (count($tuples))
				{
					$columns = array('content_id', 'ordering');
					$query = $db->getQuery(true)
						->insert($db->quoteName('#__content_frontpage'))
						->columns($db->quoteName($columns))
						->values($tuples);
					$db->setQuery($query);
					$db->execute();
				}
			}
		}
		catch (Exception $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		$table->reorder();

		$this->cleanCache();

		return true;
	}

	/**
	 * A protected method to get a set of ordering conditions.
	 *
	 * @param   object  $table  A record object.
	 *
	 * @return  array  An array of conditions to add to add to ordering queries.
	 *
	 * @since   1.6
	 */
	protected function getReorderConditions($table)
	{
		return array('catid = ' . (int) $table->catid);
	}

	/**
	 * Allows preprocessing of the JForm object.
	 *
	 * @param   JForm   $form   The form object
	 * @param   array   $data   The data to be merged into the form object
	 * @param   string  $group  The plugin group to be executed
	 *
	 * @return  void
	 *
	 * @since   3.0
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		if ($this->canCreateCategory())
		{
			$form->setFieldAttribute('catid', 'allowAdd', 'true');

			// Add a prefix for categories created on the fly.
			$form->setFieldAttribute('catid', 'customPrefix', '#new#');
		}

		// Association content items
		if (JLanguageAssociations::isEnabled())
		{
			$languages = JLanguageHelper::getContentLanguages(false, true, null, 'ordering', 'asc');

			if (count($languages) > 1)
			{
				$addform = new SimpleXMLElement('<form />');
				$fields = $addform->addChild('fields');
				$fields->addAttribute('name', 'associations');
				$fieldset = $fields->addChild('fieldset');
				$fieldset->addAttribute('name', 'item_associations');

				foreach ($languages as $language)
				{
					$field = $fieldset->addChild('field');
					$field->addAttribute('name', $language->lang_code);
					$field->addAttribute('type', 'modal_article');
					$field->addAttribute('language', $language->lang_code);
					$field->addAttribute('label', $language->title);
					$field->addAttribute('translate_label', 'false');
					$field->addAttribute('select', 'true');
					$field->addAttribute('new', 'true');
					$field->addAttribute('edit', 'true');
					$field->addAttribute('clear', 'true');
					$field->addAttribute('propagate', 'true');
				}

				$form->load($addform, false);
			}
		}

		parent::preprocessForm($form, $data, $group);
	}

	/**
	 * Custom clean the cache of com_content and content modules
	 *
	 * @param   string   $group     The cache group
	 * @param   integer  $clientId  The ID of the client
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function cleanCache($group = null, $clientId = 0)
	{
		parent::cleanCache('com_content');
		parent::cleanCache('mod_articles_archive');
		parent::cleanCache('mod_articles_categories');
		parent::cleanCache('mod_articles_category');
		parent::cleanCache('mod_articles_latest');
		parent::cleanCache('mod_articles_news');
		parent::cleanCache('mod_articles_popular');
	}

	/**
	 * Void hit function for pagebreak when editing content from frontend
	 *
	 * @return  void
	 *
	 * @since   3.6.0
	 */
	public function hit()
	{
		return;
	}

	/**
	 * Is the user allowed to create an on the fly category?
	 *
	 * @return  boolean
	 *
	 * @since   3.6.1
	 */
	private function canCreateCategory()
	{
		return JFactory::getUser()->authorise('core.create', 'com_content');
	}

	/**
	 * Delete #__content_frontpage items if the deleted articles was featured
	 *
	 * @param   object  $pks  The primary key related to the contents that was deleted.
	 *
	 * @return  boolean
	 *
	 * @since   3.7.0
	 */
	public function delete(&$pks)
	{
		$return = parent::delete($pks);

		if ($return)
		{
			// Now check to see if this articles was featured if so delete it from the #__content_frontpage table
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->delete($db->quoteName('#__content_frontpage'))
				->where('content_id IN (' . implode(',', $pks) . ')');
			$db->setQuery($query);
			$db->execute();
		}

		return $return;
	}
}
articles.php000060400000031630152455312760007074 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_content
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Methods supporting a list of article records.
 *
 * @since  1.6
 */
class ContentModelArticles extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   1.6
	 * @see     JControllerLegacy
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'title', 'a.title',
				'alias', 'a.alias',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'catid', 'a.catid', 'category_title',
				'state', 'a.state',
				'access', 'a.access', 'access_level',
				'created', 'a.created',
				'modified', 'a.modified',
				'created_by', 'a.created_by',
				'created_by_alias', 'a.created_by_alias',
				'ordering', 'a.ordering',
				'featured', 'a.featured',
				'language', 'a.language',
				'hits', 'a.hits',
				'publish_up', 'a.publish_up',
				'publish_down', 'a.publish_down',
				'published', 'a.published',
				'author_id',
				'category_id',
				'level',
				'tag',
				'rating_count', 'rating',
			);

			if (JLanguageAssociations::isEnabled())
			{
				$config['filter_fields'][] = 'association';
			}
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.id', $direction = 'desc')
	{
		$app = JFactory::getApplication();

		$forcedLanguage = $app->input->get('forcedLanguage', '', 'cmd');

		// Adjust the context to support modal layouts.
		if ($layout = $app->input->get('layout'))
		{
			$this->context .= '.' . $layout;
		}

		// Adjust the context to support forced languages.
		if ($forcedLanguage)
		{
			$this->context .= '.' . $forcedLanguage;
		}

		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
		$this->setState('filter.published', $published);

		$level = $this->getUserStateFromRequest($this->context . '.filter.level', 'filter_level');
		$this->setState('filter.level', $level);

		$language = $this->getUserStateFromRequest($this->context . '.filter.language', 'filter_language', '');
		$this->setState('filter.language', $language);

		$formSubmited = $app->input->post->get('form_submited');

		$access     = $this->getUserStateFromRequest($this->context . '.filter.access', 'filter_access');
		$authorId   = $this->getUserStateFromRequest($this->context . '.filter.author_id', 'filter_author_id');
		$categoryId = $this->getUserStateFromRequest($this->context . '.filter.category_id', 'filter_category_id');
		$tag        = $this->getUserStateFromRequest($this->context . '.filter.tag', 'filter_tag', '');

		if ($formSubmited)
		{
			$access = $app->input->post->get('access');
			$this->setState('filter.access', $access);

			$authorId = $app->input->post->get('author_id');
			$this->setState('filter.author_id', $authorId);

			$categoryId = $app->input->post->get('category_id');
			$this->setState('filter.category_id', $categoryId);

			$tag = $app->input->post->get('tag');
			$this->setState('filter.tag', $tag);
		}

		// List state information.
		parent::populateState($ordering, $direction);

		// Force a language
		if (!empty($forcedLanguage))
		{
			$this->setState('filter.language', $forcedLanguage);
			$this->setState('filter.forcedLanguage', $forcedLanguage);
		}
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . serialize($this->getState('filter.access'));
		$id .= ':' . $this->getState('filter.published');
		$id .= ':' . serialize($this->getState('filter.category_id'));
		$id .= ':' . serialize($this->getState('filter.author_id'));
		$id .= ':' . $this->getState('filter.language');
		$id .= ':' . serialize($this->getState('filter.tag'));

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db    = $this->getDbo();
		$query = $db->getQuery(true);
		$user  = JFactory::getUser();

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.title, a.alias, a.checked_out, a.checked_out_time, a.catid' .
				', a.state, a.access, a.created, a.created_by, a.created_by_alias, a.modified, a.ordering, a.featured, a.language, a.hits' .
				', a.publish_up, a.publish_down, a.note'
			)
		);
		$query->from('#__content AS a');

		// Join over the language
		$query->select('l.title AS language_title, l.image AS language_image')
			->join('LEFT', $db->quoteName('#__languages') . ' AS l ON l.lang_code = a.language');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor')
			->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');

		// Join over the asset groups.
		$query->select('ag.title AS access_level')
			->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access');

		// Join over the categories.
		$query->select('c.title AS category_title, c.created_user_id AS category_uid, c.level AS category_level')
			->join('LEFT', '#__categories AS c ON c.id = a.catid');

		// Join over the parent categories.
		$query->select('parent.title AS parent_category_title, parent.id AS parent_category_id,
								parent.created_user_id AS parent_category_uid, parent.level AS parent_category_level')
			->join('LEFT', '#__categories AS parent ON parent.id = c.parent_id');

		// Join over the users for the author.
		$query->select('ua.name AS author_name')
			->join('LEFT', '#__users AS ua ON ua.id = a.created_by');

		// Join on voting table
		if (JPluginHelper::isEnabled('content', 'vote'))
		{
			$query->select('COALESCE(NULLIF(ROUND(v.rating_sum  / v.rating_count, 0), 0), 0) AS rating,
					COALESCE(NULLIF(v.rating_count, 0), 0) as rating_count')
				->join('LEFT', '#__content_rating AS v ON a.id = v.content_id');
		}

		// Join over the associations.
		if (JLanguageAssociations::isEnabled())
		{
			$subQuery = $db->getQuery(true)
				->select('COUNT(' . $db->quoteName('asso1.id') . ') > 1')
				->from($db->quoteName('#__associations', 'asso1'))
				->join('INNER', $db->quoteName('#__associations', 'asso2') . ' ON ' . $db->quoteName('asso1.key') . ' = ' . $db->quoteName('asso2.key'))
				->where(
					array(
						$db->quoteName('asso1.id') . ' = ' . $db->quoteName('a.id'),
						$db->quoteName('asso1.context') . ' = ' . $db->quote('com_content.item'),
					)
				);

			$query->select('(' . $subQuery . ') AS ' . $db->quoteName('association'));
		}

		// Filter by access level.
		$access = $this->getState('filter.access');

		if (is_numeric($access))
		{
			$query->where('a.access = ' . (int) $access);
		}
		elseif (is_array($access))
		{
			$access = ArrayHelper::toInteger($access);
			$access = implode(',', $access);
			$query->where('a.access IN (' . $access . ')');
		}

		// Filter by access level on categories.
		if (!$user->authorise('core.admin'))
		{
			$groups = implode(',', $user->getAuthorisedViewLevels());
			$query->where('a.access IN (' . $groups . ')');
			$query->where('c.access IN (' . $groups . ')');
		}

		// Filter by published state
		$published = $this->getState('filter.published');

		if (is_numeric($published))
		{
			$query->where('a.state = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.state = 0 OR a.state = 1)');
		}

		// Filter by categories and by level
		$categoryId = $this->getState('filter.category_id', array());
		$level = $this->getState('filter.level');

		if (!is_array($categoryId))
		{
			$categoryId = $categoryId ? array($categoryId) : array();
		}

		// Case: Using both categories filter and by level filter
		if (count($categoryId))
		{
			$categoryId = ArrayHelper::toInteger($categoryId);
			$categoryTable = JTable::getInstance('Category', 'JTable');
			$subCatItemsWhere = array();

			foreach ($categoryId as $filter_catid)
			{
				$categoryTable->load($filter_catid);
				$subCatItemsWhere[] = '(' .
					($level ? 'c.level <= ' . ((int) $level + (int) $categoryTable->level - 1) . ' AND ' : '') .
					'c.lft >= ' . (int) $categoryTable->lft . ' AND ' .
					'c.rgt <= ' . (int) $categoryTable->rgt . ')';
			}

			$query->where('(' . implode(' OR ', $subCatItemsWhere) . ')');
		}

		// Case: Using only the by level filter
		elseif ($level)
		{
			$query->where('c.level <= ' . (int) $level);
		}

		// Filter by author
		$authorId = $this->getState('filter.author_id');

		if (is_numeric($authorId))
		{
			$type = $this->getState('filter.author_id.include', true) ? '= ' : '<>';
			$query->where('a.created_by ' . $type . (int) $authorId);
		}
		elseif (is_array($authorId))
		{
			$authorId = ArrayHelper::toInteger($authorId);
			$authorId = implode(',', $authorId);
			$query->where('a.created_by IN (' . $authorId . ')');
		}

		// Filter by search in title.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			elseif (stripos($search, 'author:') === 0)
			{
				$search = $db->quote('%' . $db->escape(substr($search, 7), true) . '%');
				$query->where('(ua.name LIKE ' . $search . ' OR ua.username LIKE ' . $search . ')');
			}
			elseif (stripos($search, 'content:') === 0)
			{
				$search = $db->quote('%' . $db->escape(substr($search, 8), true) . '%');
				$query->where('(a.introtext LIKE ' . $search . ' OR a.fulltext LIKE ' . $search . ')');
			}
			else
			{
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where('(a.title LIKE ' . $search . ' OR a.alias LIKE ' . $search . ' OR a.note LIKE ' . $search . ')');
			}
		}

		// Filter on the language.
		if ($language = $this->getState('filter.language'))
		{
			$query->where('a.language = ' . $db->quote($language));
		}

		$tag = $this->getState('filter.tag');

		// Run simplified query when filtering by one tag.
		if (\is_array($tag) && \count($tag) === 1)
		{
			$tag = $tag[0];
		}

		if ($tag && \is_array($tag))
		{
			$tag = ArrayHelper::toInteger($tag);

			$subQuery = $db->getQuery(true)
				->select('DISTINCT ' . $db->quoteName('content_item_id'))
				->from($db->quoteName('#__contentitem_tag_map'))
				->where(
					array(
						$db->quoteName('tag_id') . ' IN (' . implode(',', $tag) . ')',
						$db->quoteName('type_alias') . ' = ' . $db->quote('com_content.article'),
					)
				);

			$query->join(
				'INNER',
				'(' . $subQuery . ') AS ' . $db->quoteName('tagmap')
					. ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id')
			);
		}
		elseif ($tag = (int) $tag)
		{
			$query->join(
				'INNER',
				$db->quoteName('#__contentitem_tag_map', 'tagmap')
					. ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id')
			)
				->where(
					array(
						$db->quoteName('tagmap.tag_id') . ' = ' . $tag,
						$db->quoteName('tagmap.type_alias') . ' = ' . $db->quote('com_content.article'),
					)
				);
		}

		// Add the list ordering clause.
		$orderCol  = $this->state->get('list.ordering', 'a.id');
		$orderDirn = $this->state->get('list.direction', 'DESC');

		if ($orderCol == 'a.ordering' || $orderCol == 'category_title')
		{
			$orderCol = $db->quoteName('c.title') . ' ' . $orderDirn . ', ' . $db->quoteName('a.ordering');
		}

		$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDirn));

		return $query;
	}

	/**
	 * Build a list of authors
	 *
	 * @return  stdClass
	 *
	 * @since   1.6
	 *
	 * @deprecated  4.0  To be removed with Hathor
	 */
	public function getAuthors()
	{
		// Create a new query object.
		$db    = $this->getDbo();
		$query = $db->getQuery(true);

		// Construct the query
		$query->select('u.id AS value, u.name AS text')
			->from('#__users AS u')
			->join('INNER', '#__content AS c ON c.created_by = u.id')
			->group('u.id, u.name')
			->order('u.name');

		// Setup the query
		$db->setQuery($query);

		// Return the result
		return $db->loadObjectList();
	}
}
forms/filter_articles.xml000060400000011366152455312760011604 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_CONTENT_FILTER_SEARCH_LABEL"
			description="COM_CONTENT_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="published"
			type="status"
			label="COM_CONTENT_FILTER_PUBLISHED"
			description="COM_CONTENT_FILTER_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="category_id"
			type="category"
			label="JOPTION_FILTER_CATEGORY"
			description="JOPTION_FILTER_CATEGORY_DESC"
			multiple="true"
			class="multipleCategories"
			extension="com_content"
			onchange="this.form.submit();"
			published="0,1,2"
		/>

		<field
			name="access"
			type="accesslevel"
			label="JOPTION_FILTER_ACCESS"
			description="JOPTION_FILTER_ACCESS_DESC"
			multiple="true"
			class="multipleAccessLevels"
			onchange="this.form.submit();"
		/>

		<field
			name="author_id"
			type="author"
			label="COM_CONTENT_FILTER_AUTHOR"
			description="COM_CONTENT_FILTER_AUTHOR_DESC"
			multiple="true"
			class="multipleAuthors"
			onchange="this.form.submit();"
			>
			<option value="0">JNONE</option>
		</field>

		<field
			name="language"
			type="contentlanguage"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>

		<field
			name="tag"
			type="tag"
			label="JOPTION_FILTER_TAG"
			description="JOPTION_FILTER_TAG_DESC"
			multiple="true"
			class="multipleTags"
			mode="nested"
			onchange="this.form.submit();"
		/>

		<field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="10"
			step="1"
			languages="*"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
			</field>
		<input type="hidden" name="form_submited" value="1"/>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="COM_CONTENT_LIST_FULL_ORDERING"
			description="COM_CONTENT_LIST_FULL_ORDERING_DESC"
			onchange="this.form.submit();"
			default="a.id DESC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.state ASC">JSTATUS_ASC</option>
			<option value="a.state DESC">JSTATUS_DESC</option>
			<option value="a.featured ASC">JFEATURED_ASC</option>
			<option value="a.featured DESC">JFEATURED_DESC</option>
			<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="category_title ASC">JCATEGORY_ASC</option>
			<option value="category_title DESC">JCATEGORY_DESC</option>
			<option value="a.access ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="a.access DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option value="association ASC" requires="associations">JASSOCIATIONS_ASC</option>
			<option value="association DESC" requires="associations">JASSOCIATIONS_DESC</option>
			<option value="a.created_by ASC">JAUTHOR_ASC</option>
			<option value="a.created_by DESC">JAUTHOR_DESC</option>
			<option value="language ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="language DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.created ASC">JDATE_ASC</option>
			<option value="a.created DESC">JDATE_DESC</option>
			<option value="a.modified ASC">COM_CONTENT_MODIFIED_ASC</option>
			<option value="a.modified DESC">COM_CONTENT_MODIFIED_DESC</option>
			<option value="a.publish_up ASC">COM_CONTENT_PUBLISH_UP_ASC</option>
			<option value="a.publish_up DESC">COM_CONTENT_PUBLISH_UP_DESC</option>
			<option value="a.publish_down ASC">COM_CONTENT_PUBLISH_DOWN_ASC</option>
			<option value="a.publish_down DESC">COM_CONTENT_PUBLISH_DOWN_DESC</option>
			<option value="a.hits ASC">JGLOBAL_HITS_ASC</option>
			<option value="a.hits DESC">JGLOBAL_HITS_DESC</option>
			<option value="rating_count ASC" requires="vote">JGLOBAL_VOTES_ASC</option>
			<option value="rating_count DESC" requires="vote">JGLOBAL_VOTES_DESC</option>
			<option value="rating ASC" requires="vote">JGLOBAL_RATINGS_ASC</option>
			<option value="rating DESC" requires="vote">JGLOBAL_RATINGS_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="COM_CONTENT_LIST_LIMIT"
			description="COM_CONTENT_LIST_LIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/article.xml000060400000055206152455312760010055 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_categories/models/fields" >
		<field
			name="id"
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			class="readonly"
			size="10"
			default="0"
			readonly="true"
		/>

		<field
			name="asset_id"
			type="hidden"
			filter="unset"
		/>

		<field
			name="title"
			type="text"
			label="JGLOBAL_TITLE"
			description="JFIELD_TITLE_DESC"
			class="input-xxlarge input-large-text"
			size="40"
			required="true"
		/>

		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			hint="JFIELD_ALIAS_PLACEHOLDER"
			size="40"
		/>

		<field
			name="note"
			type="text"
			label="COM_CONTENT_FIELD_NOTE_LABEL"
			description="COM_CONTENT_FIELD_NOTE_DESC"
			class="span12"
			size="40"
			maxlength="255"
		/>

		<field
			name="version_note"
			type="text"
			label="JGLOBAL_FIELD_VERSION_NOTE_LABEL"
			description="JGLOBAL_FIELD_VERSION_NOTE_DESC"
			class="span12"
			maxlength="255"
			size="45"
		/>

		<field
			name="articletext"
			type="editor"
			label="COM_CONTENT_FIELD_ARTICLETEXT_LABEL"
			description="COM_CONTENT_FIELD_ARTICLETEXT_DESC"
			filter="JComponentHelper::filterText"
			buttons="true"
		/>

		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			class="chzn-color-state"
			filter="intval"
			size="1"
			default="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="2">JARCHIVED</option>
			<option value="-2">JTRASHED</option>
		</field>

		<field
			name="catid"
			type="categoryedit"
			label="JCATEGORY"
			description="JFIELD_CATEGORY_DESC"
			required="true"
			default=""
		/>

		<field
			name="tags"
			type="tag"
			label="JTAG"
			description="JTAG_DESC"
			class="span12"
			multiple="true"
		/>

		<field
			name="buttonspacer"
			type="spacer"
			description="JGLOBAL_ACTION_PERMISSIONS_DESCRIPTION"
		/>

		<field
			name="created"
			type="calendar"
			label="COM_CONTENT_FIELD_CREATED_LABEL"
			description="COM_CONTENT_FIELD_CREATED_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="created_by"
			type="user"
			label="COM_CONTENT_FIELD_CREATED_BY_LABEL"
			description="COM_CONTENT_FIELD_CREATED_BY_DESC"
		/>

		<field
			name="created_by_alias"
			type="text"
			label="COM_CONTENT_FIELD_CREATED_BY_ALIAS_LABEL"
			description="COM_CONTENT_FIELD_CREATED_BY_ALIAS_DESC"
			size="20"
		/>

		<field
			name="modified"
			type="calendar"
			label="JGLOBAL_FIELD_MODIFIED_LABEL"
			description="COM_CONTENT_FIELD_MODIFIED_DESC"
			class="readonly"
			translateformat="true"
			showtime="true"
			size="22"
			readonly="true"
			filter="user_utc"
		/>

		<field
			name="modified_by"
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			class="readonly"
			readonly="true"
			filter="unset"
		/>

		<field
			name="checked_out"
			type="hidden"
			filter="unset"
		/>

		<field
			name="checked_out_time"
			type="hidden"
			filter="unset"
		/>

		<field
			name="publish_up"
			type="calendar"
			label="COM_CONTENT_FIELD_PUBLISH_UP_LABEL"
			description="COM_CONTENT_FIELD_PUBLISH_UP_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="publish_down"
			type="calendar"
			label="COM_CONTENT_FIELD_PUBLISH_DOWN_LABEL"
			description="COM_CONTENT_FIELD_PUBLISH_DOWN_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="version"
			type="text"
			label="COM_CONTENT_FIELD_VERSION_LABEL"
			description="COM_CONTENT_FIELD_VERSION_DESC"
			size="6"
			class="readonly"
			readonly="true"
			filter="unset"
		/>

		<field
			name="ordering"
			type="text"
			label="JFIELD_ORDERING_LABEL"
			description="JFIELD_ORDERING_DESC"
			size="6"
			default="0"
		/>

		<field
			name="metakey"
			type="textarea"
			label="JFIELD_META_KEYWORDS_LABEL"
			description="JFIELD_META_KEYWORDS_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="metadesc"
			type="textarea"
			label="JFIELD_META_DESCRIPTION_LABEL"
			description="JFIELD_META_DESCRIPTION_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="access"
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="JFIELD_ACCESS_DESC"
			size="1"
		/>

		<field
			name="hits"
			type="number"
			label="JGLOBAL_HITS"
			description="COM_CONTENT_FIELD_HITS_DESC"
			class="readonly"
			size="6"
			readonly="true"
			filter="unset"
		/>

		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="COM_CONTENT_FIELD_LANGUAGE_DESC"
			>
			<option value="*">JALL</option>
		</field>

		<field
			name="featured"
			type="radio"
			label="JFEATURED"
			description="COM_CONTENT_FIELD_FEATURED_DESC"
			class="btn-group btn-group-yesno"
			default="0"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>

		<field
			name="rules"
			type="rules"
			label="JFIELD_RULES_LABEL"
			translate_label="false"
			filter="rules"
			component="com_content"
			section="article"
			validate="rules"
		/>

	</fieldset>

	<fields name="attribs" label="COM_CONTENT_ATTRIBS_FIELDSET_LABEL">
		<fieldset name="basic" label="COM_CONTENT_ATTRIBS_FIELDSET_LABEL">

			<field
				name="article_layout"
				type="componentlayout"
				label="JFIELD_ALT_LAYOUT_LABEL"
				description="JFIELD_ALT_COMPONENT_LAYOUT_DESC"
				useglobal="true"
				extension="com_content"
				view="article"
			/>

			<field
				name="show_title"
				type="list"
				label="JGLOBAL_SHOW_TITLE_LABEL"
				description="JGLOBAL_SHOW_TITLE_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="1">JSHOW</option>
				<option value="0">JHIDE</option>
			</field>

			<field
				name="link_titles"
				type="list"
				label="JGLOBAL_LINKED_TITLES_LABEL"
				description="JGLOBAL_LINKED_TITLES_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option	value="0">JNO</option>
				<option value="1">JYES</option>
			</field>

			<field
				name="show_tags"
				type="list"
				label="COM_CONTENT_FIELD_SHOW_TAGS_LABEL"
				description="COM_CONTENT_FIELD_SHOW_TAGS_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="1">JSHOW</option>
				<option value="0">JHIDE</option>
			</field>

			<field
				name="show_intro"
				type="list"
				label="JGLOBAL_SHOW_INTRO_LABEL"
				description="JGLOBAL_SHOW_INTRO_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="1">JSHOW</option>
				<option value="0">JHIDE</option>
			</field>

			<field
				name="info_block_position"
				type="list"
				label="COM_CONTENT_FIELD_INFOBLOCK_POSITION_LABEL"
				description="COM_CONTENT_FIELD_INFOBLOCK_POSITION_DESC"
				useglobal="true"
				>
				<option value="0">COM_CONTENT_FIELD_OPTION_ABOVE</option>
				<option value="1">COM_CONTENT_FIELD_OPTION_BELOW</option>
				<option value="2">COM_CONTENT_FIELD_OPTION_SPLIT</option>
			</field>

			<field
				name="info_block_show_title"
				type="list"
				label="COM_CONTENT_FIELD_INFOBLOCK_TITLE_LABEL"
				description="COM_CONTENT_FIELD_INFOBLOCK_TITLE_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_category"
				type="list"
				label="JGLOBAL_SHOW_CATEGORY_LABEL"
				description="JGLOBAL_SHOW_CATEGORY_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="link_category"
				type="list"
				label="JGLOBAL_LINK_CATEGORY_LABEL"
				description="JGLOBAL_LINK_CATEGORY_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JNO</option>
				<option	value="1">JYES</option>
			</field>

			<field
				name="show_parent_category"
				type="list"
				label="JGLOBAL_SHOW_PARENT_CATEGORY_LABEL"
				description="JGLOBAL_SHOW_PARENT_CATEGORY_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="link_parent_category"
				type="list"
				label="JGLOBAL_LINK_PARENT_CATEGORY_LABEL"
				description="JGLOBAL_LINK_PARENT_CATEGORY_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JNO</option>
				<option	value="1">JYES</option>
			</field>

			<field
				name="show_associations"
				type="list"
				label="JGLOBAL_SHOW_ASSOCIATIONS_LABEL"
				description="JGLOBAL_SHOW_ASSOCIATIONS_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option value="1">JSHOW</option>
				<option value="0">JHIDE</option>
			</field>

			<field
				name="show_author"
				type="list"
				label="JGLOBAL_SHOW_AUTHOR_LABEL"
				description="JGLOBAL_SHOW_AUTHOR_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="link_author"
				type="list"
				label="JGLOBAL_LINK_AUTHOR_LABEL"
				description="JGLOBAL_LINK_AUTHOR_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JNO</option>
				<option	value="1">JYES</option>
			</field>

			<field
				name="show_create_date"
				type="list"
				label="JGLOBAL_SHOW_CREATE_DATE_LABEL"
				description="JGLOBAL_SHOW_CREATE_DATE_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_modify_date"
				type="list"
				label="JGLOBAL_SHOW_MODIFY_DATE_LABEL"
				description="JGLOBAL_SHOW_MODIFY_DATE_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_publish_date"
				type="list"
				label="JGLOBAL_SHOW_PUBLISH_DATE_LABEL"
				description="JGLOBAL_SHOW_PUBLISH_DATE_DESC"
				class="chzn-color"
				useglobal="true"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_item_navigation"
				type="list"
				label="JGLOBAL_SHOW_NAVIGATION_LABEL"
				description="JGLOBAL_SHOW_NAVIGATION_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_icons"
				type="list"
				label="JGLOBAL_SHOW_ICONS_LABEL"
				description="JGLOBAL_SHOW_ICONS_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_print_icon"
				type="list"
				label="JGLOBAL_SHOW_PRINT_ICON_LABEL"
				description="JGLOBAL_SHOW_PRINT_ICON_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_email_icon"
				type="list"
				label="JGLOBAL_SHOW_EMAIL_ICON_LABEL"
				description="JGLOBAL_SHOW_EMAIL_ICON_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_vote"
				type="list"
				label="JGLOBAL_SHOW_VOTE_LABEL"
				description="JGLOBAL_SHOW_VOTE_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_hits"
				type="list"
				label="JGLOBAL_SHOW_HITS_LABEL"
				description="JGLOBAL_SHOW_HITS_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option	value="0">JHIDE</option>
				<option	value="1">JSHOW</option>
			</field>

			<field
				name="show_noauth"
				type="list"
				label="JGLOBAL_SHOW_UNAUTH_LINKS_LABEL"
				description="JGLOBAL_SHOW_UNAUTH_LINKS_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
			</field>

			<field
				name="urls_position"
				type="list"
				label="COM_CONTENT_FIELD_URLSPOSITION_LABEL"
				description="COM_CONTENT_FIELD_URLSPOSITION_DESC"
				useglobal="true"
				class="chzn-color"
				>
				<option value="0">COM_CONTENT_FIELD_OPTION_ABOVE</option>
				<option value="1">COM_CONTENT_FIELD_OPTION_BELOW</option>
			</field>

			<field
				name="spacer2"
				type="spacer"
				hr="true"
			/>

			<field
				name="alternative_readmore"
				type="text"
				label="JFIELD_READMORE_LABEL"
				description="JFIELD_READMORE_DESC"
				size="25"
			/>

			<field
				name="article_page_title"
				type="text"
				label="COM_CONTENT_FIELD_BROWSER_PAGE_TITLE_LABEL"
				description="COM_CONTENT_FIELD_BROWSER_PAGE_TITLE_DESC"
				size="25"
			/>
		</fieldset>

		<fieldset name="editorConfig" label="COM_CONTENT_EDITORCONFIG_FIELDSET_LABEL">
			<field
				name="show_publishing_options"
				type="list"
				label="COM_CONTENT_SHOW_PUBLISHING_OPTIONS_LABEL"
				description="COM_CONTENT_SHOW_PUBLISHING_OPTIONS_DESC"
				default=""
				useglobal="true"
				class="chzn-color"
				>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
			</field>

			<field
				name="show_article_options"
				type="list"
				label="COM_CONTENT_SHOW_ARTICLE_OPTIONS_LABEL"
				description="COM_CONTENT_SHOW_ARTICLE_OPTIONS_DESC"
				default=""
				useglobal="true"
				class="chzn-color"
				>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
			</field>

			<field
				name="show_urls_images_backend"
				type="list"
				label="COM_CONTENT_SHOW_IMAGES_URLS_BACK_LABEL"
				description="COM_CONTENT_SHOW_IMAGES_URLS_BACK_DESC"
				useglobal="true"
				class="chzn-color"
				default=""
				>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
			</field>

			<field
				name="show_urls_images_frontend"
				type="list"
				label="COM_CONTENT_SHOW_IMAGES_URLS_FRONT_LABEL"
				description="COM_CONTENT_SHOW_IMAGES_URLS_FRONT_DESC"
				useglobal="true"
				class="chzn-color"
				default=""
				>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
			</field>
		</fieldset>

		<fieldset name="basic-limited" label="COM_CONTENT_ATTRIBS_FIELDSET_LABEL">
			<field
				name="show_title"
				type="hidden"
				label="JGLOBAL_SHOW_TITLE_LABEL"
				description="JGLOBAL_SHOW_TITLE_DESC"
			/>

			<field
				name="link_titles"
				type="hidden"
				label="JGLOBAL_LINKED_TITLES_LABEL"
				description="JGLOBAL_LINKED_TITLES_DESC"
			/>

			<field
				name="show_intro"
				type="hidden"
				label="JGLOBAL_SHOW_INTRO_LABEL"
				description="JGLOBAL_SHOW_INTRO_DESC"
			/>

			<field
				name="show_category"
				type="hidden"
				label="JGLOBAL_SHOW_CATEGORY_LABEL"
				description="JGLOBAL_SHOW_CATEGORY_DESC"
			/>

			<field
				name="link_category"
				type="hidden"
				label="JGLOBAL_LINK_CATEGORY_LABEL"
				description="JGLOBAL_LINK_CATEGORY_DESC"
			/>

			<field
				name="show_parent_category"
				type="hidden"
				label="JGLOBAL_SHOW_PARENT_CATEGORY_LABEL"
				description="JGLOBAL_SHOW_PARENT_CATEGORY_DESC"
			/>

			<field
				name="link_parent_category"
				type="hidden"
				label="JGLOBAL_LINK_PARENT_CATEGORY_LABEL"
				description="JGLOBAL_LINK_PARENT_CATEGORY_DESC"
			/>

			<field
				name="show_author"
				type="hidden"
				label="JGLOBAL_SHOW_AUTHOR_LABEL"
				description="JGLOBAL_SHOW_AUTHOR_DESC"
			/>

			<field
				name="link_author"
				type="hidden"
				label="JGLOBAL_LINK_AUTHOR_LABEL"
				description="JGLOBAL_LINK_AUTHOR_DESC"
			/>

			<field
				name="show_create_date"
				type="hidden"
				label="JGLOBAL_SHOW_CREATE_DATE_LABEL"
				description="JGLOBAL_SHOW_CREATE_DATE_DESC"
			/>

			<field
				name="show_modify_date"
				type="hidden"
				label="JGLOBAL_SHOW_MODIFY_DATE_LABEL"
				description="JGLOBAL_SHOW_MODIFY_DATE_DESC"
			/>

			<field
				name="show_publish_date"
				type="hidden"
				label="JGLOBAL_SHOW_PUBLISH_DATE_LABEL"
				description="JGLOBAL_SHOW_PUBLISH_DATE_DESC"
			/>

			<field
				name="show_item_navigation"
				type="hidden"
				label="JGLOBAL_SHOW_NAVIGATION_LABEL"
				description="JGLOBAL_SHOW_NAVIGATION_DESC"
			/>

			<field
				name="show_icons"
				type="hidden"
				label="JGLOBAL_SHOW_ICONS_LABEL"
				description="JGLOBAL_SHOW_ICONS_DESC"
			/>

			<field
				name="show_print_icon"
				type="hidden"
				label="JGLOBAL_SHOW_PRINT_ICON_LABEL"
				description="JGLOBAL_SHOW_PRINT_ICON_DESC"
			/>

			<field
				name="show_email_icon"
				type="hidden"
				label="JGLOBAL_SHOW_EMAIL_ICON_LABEL"
				description="JGLOBAL_SHOW_EMAIL_ICON_DESC"
			/>

			<field
				name="show_vote"
				type="hidden"
				label="JGLOBAL_SHOW_VOTE_LABEL"
				description="JGLOBAL_SHOW_VOTE_DESC"
			/>

			<field
				name="show_hits"
				type="hidden"
				label="JGLOBAL_SHOW_HITS_LABEL"
				description="JGLOBAL_SHOW_HITS_DESC"
			/>

			<field
				name="show_noauth"
				type="hidden"
				label="JGLOBAL_SHOW_UNAUTH_LINKS_LABEL"
				description="JGLOBAL_SHOW_UNAUTH_LINKS_DESC"
			/>

			<field
				name="alternative_readmore"
				type="hidden"
				label="JFIELD_READMORE_LABEL"
				description="JFIELD_READMORE_DESC"
				size="25"
			/>

			<field
				name="article_layout"
				type="hidden"
				label="JFIELD_ALT_LAYOUT_LABEL"
				description="JFIELD_ALT_COMPONENT_LAYOUT_DESC"
				useglobal="true"
				extension="com_content" view="article"
			/>
		</fieldset>
	</fields>

	<field
		name="xreference"
		type="text"
		label="JFIELD_KEY_REFERENCE_LABEL"
		description="JFIELD_KEY_REFERENCE_DESC"
		size="20"
	/>

	<fields name="images" label="COM_CONTENT_FIELD_IMAGE_OPTIONS">
		<field
			name="image_intro"
			type="media"
			label="COM_CONTENT_FIELD_INTRO_LABEL"
			description="COM_CONTENT_FIELD_INTRO_DESC"
		/>

		<field
			name="float_intro"
			type="list"
			label="COM_CONTENT_FLOAT_LABEL"
			description="COM_CONTENT_FLOAT_DESC"
			useglobal="true"
			>
			<option value="right">COM_CONTENT_RIGHT</option>
			<option value="left">COM_CONTENT_LEFT</option>
			<option value="none">COM_CONTENT_NONE</option>
		</field>

		<field
			name="image_intro_alt"
			type="text"
			label="COM_CONTENT_FIELD_IMAGE_ALT_LABEL"
			description="COM_CONTENT_FIELD_IMAGE_ALT_DESC"
			size="20"
		/>

		<field
			name="image_intro_caption"
			type="text"
			label="COM_CONTENT_FIELD_IMAGE_CAPTION_LABEL"
			description="COM_CONTENT_FIELD_IMAGE_CAPTION_DESC"
			size="20"
		/>

		<field
			name="spacer1"
			type="spacer"
			hr="true"
		/>

		<field
			name="image_fulltext"
			type="media"
			label="COM_CONTENT_FIELD_FULL_LABEL"
			description="COM_CONTENT_FIELD_FULL_DESC"
		/>

		<field
			name="float_fulltext"
			type="list"
			label="COM_CONTENT_FLOAT_LABEL"
			description="COM_CONTENT_FLOAT_DESC"
			useglobal="true"
			>
			<option value="right">COM_CONTENT_RIGHT</option>
			<option value="left">COM_CONTENT_LEFT</option>
			<option value="none">COM_CONTENT_NONE</option>
		</field>

		<field
			name="image_fulltext_alt"
			type="text"
			label="COM_CONTENT_FIELD_IMAGE_ALT_LABEL"
			description="COM_CONTENT_FIELD_IMAGE_ALT_DESC"
			size="20"
		/>

		<field
			name="image_fulltext_caption"
			type="text"
			label="COM_CONTENT_FIELD_IMAGE_CAPTION_LABEL"
			description="COM_CONTENT_FIELD_IMAGE_CAPTION_DESC"
			size="20"
		/>
	</fields>
	<fields name="urls" label="COM_CONTENT_FIELD_URLS_OPTIONS">
		<field
			name="urla"
			type="url"
			label="COM_CONTENT_FIELD_URLA_LABEL"
			description="COM_CONTENT_FIELD_URL_DESC"
			validate="url"
			filter="url"
			relative="true"
		/>

		<field
			name="urlatext"
			type="text"
			label="COM_CONTENT_FIELD_URLA_LINK_TEXT_LABEL"
			description="COM_CONTENT_FIELD_URL_LINK_TEXT_DESC"
			size="20"
		/>

		<field
			name="targeta"
			type="list"
			label="COM_CONTENT_URL_FIELD_BROWSERNAV_LABEL"
			description="COM_CONTENT_URL_FIELD_BROWSERNAV_DESC"
			default=""
			filter="options"
			useglobal="true"
			>
			<option value="0">JBROWSERTARGET_PARENT</option>
			<option value="1">JBROWSERTARGET_NEW</option>
			<option value="2">JBROWSERTARGET_POPUP</option>
			<option value="3">JBROWSERTARGET_MODAL</option>
		</field>

		<field
			name="spacer3"
			type="spacer"
			hr="true"
		/>

		<field
			name="urlb"
			type="url"
			label="COM_CONTENT_FIELD_URLB_LABEL"
			description="COM_CONTENT_FIELD_URL_DESC"
			validate="url"
			filter="url"
			relative="true"
		/>

		<field
			name="urlbtext"
			type="text"
			label="COM_CONTENT_FIELD_URLB_LINK_TEXT_LABEL"
			description="COM_CONTENT_FIELD_URL_LINK_TEXT_DESC"
			size="20"
		/>

		<field
			name="targetb"
			type="list"
			label="COM_CONTENT_URL_FIELD_BROWSERNAV_LABEL"
			description="COM_CONTENT_URL_FIELD_BROWSERNAV_DESC"
			default=""
			filter="options"
			useglobal="true"
			>
			<option value="0">JBROWSERTARGET_PARENT</option>
			<option value="1">JBROWSERTARGET_NEW</option>
			<option value="2">JBROWSERTARGET_POPUP</option>
			<option value="3">JBROWSERTARGET_MODAL</option>
		</field>

		<field
			name="spacer4"
			type="spacer"
			hr="true"
		/>

		<field
			name="urlc"
			type="url"
			label="COM_CONTENT_FIELD_URLC_LABEL"
			description="COM_CONTENT_FIELD_URL_DESC"
			validate="url"
			filter="url"
			relative="true"
		/>

		<field
			name="urlctext"
			type="text"
			label="COM_CONTENT_FIELD_URLC_LINK_TEXT_LABEL"
			description="COM_CONTENT_FIELD_URL_LINK_TEXT_DESC"
			size="20"
		/>

		<field
			name="targetc"
			type="list"
			label="COM_CONTENT_URL_FIELD_BROWSERNAV_LABEL"
			description="COM_CONTENT_URL_FIELD_BROWSERNAV_DESC"
			default=""
			filter="options"
			useglobal="true"
			>
			<option value="0">JBROWSERTARGET_PARENT</option>
			<option value="1">JBROWSERTARGET_NEW</option>
			<option value="2">JBROWSERTARGET_POPUP</option>
			<option value="3">JBROWSERTARGET_MODAL</option>
		</field>

	</fields>

	<fields name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">
		<fieldset name="jmetadata"
			label="JGLOBAL_FIELDSET_METADATA_OPTIONS">

			<field
				name="robots"
				type="list"
				label="JFIELD_METADATA_ROBOTS_LABEL"
				description="JFIELD_METADATA_ROBOTS_DESC"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="index, follow"></option>
				<option value="noindex, follow"></option>
				<option value="index, nofollow"></option>
				<option value="noindex, nofollow"></option>
			</field>

			<field
				name="author"
				type="text"
				label="JAUTHOR"
				description="JFIELD_METADATA_AUTHOR_DESC"
				size="20"
			/>

			<field
				name="rights"
				type="textarea"
				label="JFIELD_META_RIGHTS_LABEL"
				description="JFIELD_META_RIGHTS_DESC"
				filter="string"
				cols="30"
				rows="2"
			/>

			<field
				name="xreference"
				type="text"
				label="COM_CONTENT_FIELD_XREFERENCE_LABEL"
				description="COM_CONTENT_FIELD_XREFERENCE_DESC"
				size="20"
			/>

		</fieldset>
	</fields>
	<!-- These fields are used to get labels for the Content History Preview and Compare Views -->
	<fields>
		<field
			name="introtext"
			label="COM_CONTENT_FIELD_INTROTEXT"
		/>

		<field
			name="fulltext"
			label="COM_CONTENT_FIELD_FULLTEXT"
		/>
	</fields>

</form>
form.php000060400000012512152455312760006227 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_content
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;

// Base this model on the backend version.
JLoader::register('ContentModelArticle', JPATH_ADMINISTRATOR . '/components/com_content/models/article.php');

/**
 * Content Component Article Model
 *
 * @since  1.5
 */
class ContentModelForm extends ContentModelArticle
{
	/**
	 * Model typeAlias string. Used for version history.
	 *
	 * @var        string
	 */
	public $typeAlias = 'com_content.article';

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication();

		// Load the parameters.
		$params = $app->getParams();
		$this->setState('params', $params);

		if ($params && $params->get('enable_category') == 1 && $params->get('catid'))
		{
			$catId = $params->get('catid');
		}
		else
		{
			$catId = 0;
		}

		// Load state from the request.
		$pk = $app->input->getInt('a_id');
		$this->setState('article.id', $pk);

		$this->setState('article.catid', $app->input->getInt('catid', $catId));

		$return = $app->input->get('return', null, 'base64');
		$this->setState('return_page', base64_decode($return));

		$this->setState('layout', $app->input->getString('layout'));
	}

	/**
	 * Method to get article data.
	 *
	 * @param   integer  $itemId  The id of the article.
	 *
	 * @return  mixed  Content item data object on success, false on failure.
	 */
	public function getItem($itemId = null)
	{
		$itemId = (int) (!empty($itemId)) ? $itemId : $this->getState('article.id');

		// Get a row instance.
		$table = $this->getTable();

		// Attempt to load the row.
		$return = $table->load($itemId);

		// Check for a table object error.
		if ($return === false && $table->getError())
		{
			$this->setError($table->getError());

			return false;
		}

		$properties = $table->getProperties(1);
		$value = ArrayHelper::toObject($properties, 'JObject');

		// Convert attrib field to Registry.
		$value->params = new Registry($value->attribs);

		// Compute selected asset permissions.
		$user   = JFactory::getUser();
		$userId = $user->get('id');
		$asset  = 'com_content.article.' . $value->id;

		// Check general edit permission first.
		if ($user->authorise('core.edit', $asset))
		{
			$value->params->set('access-edit', true);
		}

		// Now check if edit.own is available.
		elseif (!empty($userId) && $user->authorise('core.edit.own', $asset))
		{
			// Check for a valid user and that they are the owner.
			if ($userId == $value->created_by)
			{
				$value->params->set('access-edit', true);
			}
		}

		// Check edit state permission.
		if ($itemId)
		{
			// Existing item
			$value->params->set('access-change', $user->authorise('core.edit.state', $asset));
		}
		else
		{
			// New item.
			$catId = (int) $this->getState('article.catid');

			if ($catId)
			{
				$value->params->set('access-change', $user->authorise('core.edit.state', 'com_content.category.' . $catId));
				$value->catid = $catId;
			}
			else
			{
				$value->params->set('access-change', $user->authorise('core.edit.state', 'com_content'));
			}
		}

		$value->articletext = $value->introtext;

		if (!empty($value->fulltext))
		{
			$value->articletext .= '<hr id="system-readmore" />' . $value->fulltext;
		}

		// Convert the metadata field to an array.
		$registry = new Registry($value->metadata);
		$value->metadata = $registry->toArray();

		if ($itemId)
		{
			$value->tags = new JHelperTags;
			$value->tags->getTagIds($value->id, 'com_content.article');
			$value->metadata['tags'] = $value->tags;
		}

		return $value;
	}

	/**
	 * Get the return URL.
	 *
	 * @return  string	The return URL.
	 *
	 * @since   1.6
	 */
	public function getReturnPage()
	{
		return base64_encode($this->getState('return_page'));
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.2
	 */
	public function save($data)
	{
		// Associations are not edited in frontend ATM so we have to inherit them
		if (JLanguageAssociations::isEnabled() && !empty($data['id'])
			&& $associations = JLanguageAssociations::getAssociations('com_content', '#__content', 'com_content.item', $data['id']))
		{
			foreach ($associations as $tag => $associated)
			{
				$associations[$tag] = (int) $associated->id;
			}

			$data['associations'] = $associations;
		}

		return parent::save($data);
	}

	/**
	 * Allows preprocessing of the JForm object.
	 *
	 * @param   JForm   $form   The form object
	 * @param   array   $data   The data to be merged into the form object
	 * @param   string  $group  The plugin group to be executed
	 *
	 * @return  void
	 *
	 * @since   3.7.0
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		$params = $this->getState()->get('params');

		if ($params && $params->get('enable_category') == 1 && $params->get('catid'))
		{
			$form->setFieldAttribute('catid', 'default', $params->get('catid'));
			$form->setFieldAttribute('catid', 'readonly', 'true');
		}

		parent::preprocessForm($form, $data, $group);
	}
}
browse.php000060400000000615152455516220006563 0ustar00<?php
/**
 * @name		Slideshow CK
 * @package		com_slideshowck
 * @copyright	Copyright (C) 2019. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 * @author		Cedric Keiflin - https://www.template-creator.com - https://www.joomlack.fr
 */

defined('_JEXEC') or die;

include_once(JPATH_ADMINISTRATOR . '/components/com_slideshowck/models/browse.php');menus.php000060400000000614152455516220006410 0ustar00<?php
/**
 * @name		Slideshow CK
 * @package		com_slideshowck
 * @copyright	Copyright (C) 2019. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 * @author		Cedric Keiflin - https://www.template-creator.com - https://www.joomlack.fr
 */

defined('_JEXEC') or die;

include_once(JPATH_ADMINISTRATOR . '/components/com_slideshowck/models/menus.php');suggestions.php000060400000011700152455516270007636 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\String\StringHelper;

define('FINDER_PATH_INDEXER', JPATH_ADMINISTRATOR . '/components/com_finder/helpers/indexer');
JLoader::register('FinderIndexerHelper', FINDER_PATH_INDEXER . '/helper.php');

/**
 * Suggestions model class for the Finder package.
 *
 * @since  2.5
 */
class FinderModelSuggestions extends JModelList
{
	/**
	 * Context string for the model type.
	 *
	 * @var    string
	 * @since  2.5
	 */
	protected $context = 'com_finder.suggestions';

	/**
	 * Method to get an array of data items.
	 *
	 * @return  array  An array of data items.
	 *
	 * @since   2.5
	 */
	public function getItems()
	{
		// Get the items.
		$items = parent::getItems();

		// Convert them to a simple array.
		foreach ($items as $k => $v)
		{
			$items[$k] = $v->term;
		}

		return $items;
	}

	/**
	 * Method to build a database query to load the list data.
	 *
	 * @return  JDatabaseQuery  A database query
	 *
	 * @since   2.5
	 */
	protected function getListQuery()
	{
		$user = JFactory::getUser();
		$groups = \Joomla\Utilities\ArrayHelper::toInteger($user->getAuthorisedViewLevels());

		// Create a new query object.
		$db = $this->getDbo();
		$termIdQuery = $db->getQuery(true);
		$termQuery = $db->getQuery(true);

		// Limit term count to a reasonable number of results to reduce main query join size
		$termIdQuery->select('ti.term_id')
			->from($db->quoteName('#__finder_terms', 'ti'))
			->where('ti.term LIKE ' . $db->quote($db->escape(StringHelper::strtolower($this->getState('input')), true) . '%', false))
			->where('ti.common = 0')
			->where('ti.language IN (' . $db->quote($this->getState('language')) . ', ' . $db->quote('*') . ')')
			->order('ti.links DESC')
			->order('ti.weight DESC');

		$termIds = $db->setQuery($termIdQuery, 0, 100)->loadColumn();

		// Early return on term mismatch
		if (!count($termIds))
		{
			return $termIdQuery;
		}

		$termIdString = implode(',', $termIds);

		// Select required fields
		$termQuery->select('DISTINCT(t.term)')
			->select('t.links')
			->select('t.weight')
			->from($db->quoteName('#__finder_terms') . ' AS t')
			->where('t.term_id IN (' . $termIdString . ')')
			->order('t.links DESC')
			->order('t.weight DESC');

		// Determine the relevant mapping table suffix by inverting the logic from drivers
		$mappingTableSuffix = StringHelper::substr(md5(StringHelper::substr(StringHelper::strtolower($this->getState('input')), 0, 1)), 0, 1);

		// Join mapping table for term <-> link relation
		$mappingTable = $db->quoteName('#__finder_links_terms' . $mappingTableSuffix);
		$termQuery->join('INNER', $mappingTable . ' AS tm ON tm.term_id = t.term_id');

		// Join links table
		$termQuery->join('INNER', $db->quoteName('#__finder_links') . ' AS l ON (tm.link_id = l.link_id)')
			->where('l.access IN (' . implode(',', $groups) . ')')
			->where('l.state = 1')
			->where('l.published = 1');

		return $termQuery;
	}

	/**
	 * Method to get a store id based on model the configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  An identifier string to generate the store id. [optional]
	 *
	 * @return  string  A store id.
	 *
	 * @since   2.5
	 */
	protected function getStoreId($id = '')
	{
		// Add the search query state.
		$id .= ':' . $this->getState('input');
		$id .= ':' . $this->getState('language');

		// Add the list state.
		$id .= ':' . $this->getState('list.start');
		$id .= ':' . $this->getState('list.limit');

		return parent::getStoreId($id);
	}

	/**
	 * Method to auto-populate the model state.  Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Get the configuration options.
		$app = JFactory::getApplication();
		$input = $app->input;
		$params = JComponentHelper::getParams('com_finder');
		$user = JFactory::getUser();

		// Get the query input.
		$this->setState('input', $input->request->get('q', '', 'string'));

		// Set the query language
		if (JLanguageMultilang::isEnabled())
		{
			$lang = JFactory::getLanguage()->getTag();
		}
		else
		{
			$lang = FinderIndexerHelper::getDefaultLanguage();
		}

		$lang = FinderIndexerHelper::getPrimaryLanguage($lang);
		$this->setState('language', $lang);

		// Load the list state.
		$this->setState('list.start', 0);
		$this->setState('list.limit', 10);

		// Load the parameters.
		$this->setState('params', $params);

		// Load the user state.
		$this->setState('user.id', (int) $user->get('id'));
	}
}
search.php000060400000011466152455516270006542 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_search
 *
 * @copyright   (C) 2007 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Search Component Search Model
 *
 * @since  1.5
 */
class SearchModelSearch extends JModelLegacy
{
	/**
	 * Search data array
	 *
	 * @var   array
	 */
	protected $_data = null;

	/**
	 * Search total
	 *
	 * @var   integer
	 */
	protected $_total = null;

	/**
	 * Search areas
	 *
	 * @var   integer
	 */
	protected $_areas = null;

	/**
	 * Pagination object
	 *
	 * @var   object
	 */
	protected $_pagination = null;

	/**
	 * Constructor
	 *
	 * @since  1.5
	 */
	public function __construct()
	{
		parent::__construct();

		// Get configuration
		$app    = JFactory::getApplication();
		$config = JFactory::getConfig();

		// Get the pagination request variables
		$this->setState('limit', $app->getUserStateFromRequest('com_search.limit', 'limit', $config->get('list_limit'), 'uint'));
		$this->setState('limitstart', $app->input->get('limitstart', 0, 'uint'));

		// Get parameters.
		$params = $app->getParams();

		if ($params->get('searchphrase') == 1)
		{
			$searchphrase = 'any';
		}
		elseif ($params->get('searchphrase') == 2)
		{
			$searchphrase = 'exact';
		}
		else
		{
			$searchphrase = 'all';
		}

		// Set the search parameters
		$keyword  = urldecode($app->input->getString('searchword'));
		$match    = $app->input->get('searchphrase', $searchphrase, 'word');
		$ordering = $app->input->get('ordering', $params->get('ordering', 'newest'), 'word');
		$this->setSearch($keyword, $match, $ordering);

		// Set the search areas
		$areas = $app->input->get('areas', null, 'array');
		$this->setAreas($areas);
	}

	/**
	 * Method to set the search parameters
	 *
	 * @param   string  $keyword   string search string
	 * @param   string  $match     matching option, exact|any|all
	 * @param   string  $ordering  option, newest|oldest|popular|alpha|category
	 *
	 * @access  public
	 *
	 * @return  void
	 */
	public function setSearch($keyword, $match = 'all', $ordering = 'newest')
	{
		if (isset($keyword))
		{
			$this->setState('origkeyword', $keyword);

			if ($match !== 'exact')
			{
				$keyword = preg_replace('#\xE3\x80\x80#', ' ', $keyword);
			}

			$this->setState('keyword', $keyword);
		}

		if (isset($match))
		{
			$this->setState('match', $match);
		}

		if (isset($ordering))
		{
			$this->setState('ordering', $ordering);
		}
	}

	/**
	 * Method to get weblink item data for the category
	 *
	 * @access  public
	 * @return  array
	 */
	public function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$areas = $this->getAreas();

			JPluginHelper::importPlugin('search');
			$dispatcher = JEventDispatcher::getInstance();
			$results = $dispatcher->trigger('onContentSearch', array(
				$this->getState('keyword'),
				$this->getState('match'),
				$this->getState('ordering'),
				$areas['active'])
			);

			$rows = array();

			foreach ($results as $result)
			{
				$rows = array_merge((array) $rows, (array) $result);
			}

			$this->_total = count($rows);

			if ($this->getState('limit') > 0)
			{
				$this->_data = array_splice($rows, $this->getState('limitstart'), $this->getState('limit'));
			}
			else
			{
				$this->_data = $rows;
			}
		}

		return $this->_data;
	}

	/**
	 * Method to get the total number of weblink items for the category
	 *
	 * @access  public
	 *
	 * @return  integer
	 */
	public function getTotal()
	{
		return $this->_total;
	}

	/**
	 * Method to set the search areas
	 *
	 * @param   array  $active  areas
	 * @param   array  $search  areas
	 *
	 * @return  void
	 *
	 * @access  public
	 */
	public function setAreas($active = array(), $search = array())
	{
		$this->_areas['active'] = $active;
		$this->_areas['search'] = $search;
	}

	/**
	 * Method to get a pagination object of the weblink items for the category
	 *
	 * @access  public
	 * @return  integer
	 */
	public function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_pagination;
	}

	/**
	 * Method to get the search areas
	 *
	 * @return  integer
	 *
	 * @since   1.5
	 */
	public function getAreas()
	{
		// Load the Category data
		if (empty($this->_areas['search']))
		{
			$areas = array();

			JPluginHelper::importPlugin('search');
			$dispatcher  = JEventDispatcher::getInstance();
			$searchareas = $dispatcher->trigger('onContentSearchAreas');

			foreach ($searchareas as $area)
			{
				if (is_array($area))
				{
					$areas = array_merge($areas, $area);
				}
			}

			$this->_areas['search'] = $areas;
		}

		return $this->_areas;
	}
}
tag.php000060400000023277152455610750006051 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_tags
 *
 * @copyright   (C) 2013 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\String\StringHelper;

/**
 * Tags Component Tag Model
 *
 * @since  3.1
 */
class TagsModelTag extends JModelAdmin
{
	/**
	 * @var    string  The prefix to use with controller messages.
	 * @since  3.1
	 */
	protected $text_prefix = 'COM_TAGS';

	/**
	 * @var    string  The type alias for this content type.
	 * @since  3.2
	 */
	public $typeAlias = 'com_tags.tag';

	/**
	 * Allowed batch commands
	 *
	 * @var    array
	 * @since  3.7.0
	 */
	protected $batch_commands = array(
		'assetgroup_id' => 'batchAccess',
		'language_id' => 'batchLanguage',
	);

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 *
	 * @since   3.1
	 */
	protected function canDelete($record)
	{
		if (empty($record->id) || $record->published != -2)
		{
			return false;
		}

		return parent::canDelete($record);
	}

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $type    The table name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   3.1
	 */
	public function getTable($type = 'Tag', $prefix = 'TagsTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Auto-populate the model state.
	 *
	 * @note Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   3.1
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication('administrator');

		$parentId = $app->input->getInt('parent_id');
		$this->setState('tag.parent_id', $parentId);

		// Load the User state.
		$pk = $app->input->getInt('id');
		$this->setState($this->getName() . '.id', $pk);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_tags');
		$this->setState('params', $params);
	}

	/**
	 * Method to get a tag.
	 *
	 * @param   integer  $pk  An optional id of the object to get, otherwise the id from the model state is used.
	 *
	 * @return  mixed  Tag data object on success, false on failure.
	 *
	 * @since   3.1
	 */
	public function getItem($pk = null)
	{
		if ($result = parent::getItem($pk))
		{
			// Prime required properties.
			if (empty($result->id))
			{
				$result->parent_id = $this->getState('tag.parent_id');
			}

			// Convert the metadata field to an array.
			$registry = new Registry($result->metadata);
			$result->metadata = $registry->toArray();

			// Convert the images field to an array.
			$registry = new Registry($result->images);
			$result->images = $registry->toArray();

			// Convert the urls field to an array.
			$registry = new Registry($result->urls);
			$result->urls = $registry->toArray();

			// Convert the modified date to local user time for display in the form.
			$tz = new DateTimeZone(JFactory::getApplication()->get('offset'));

			if ((int) $result->modified_time)
			{
				$date = new JDate($result->modified_time);
				$date->setTimezone($tz);
				$result->modified_time = $date->toSql(true);
			}
			else
			{
				$result->modified_time = null;
			}
		}

		return $result;
	}

	/**
	 * Method to get the row form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed  A JForm object on success, false on failure
	 *
	 * @since   3.1
	 */
	public function getForm($data = array(), $loadData = true)
	{
		$jinput = JFactory::getApplication()->input;

		// Get the form.
		$form = $this->loadForm('com_tags.tag', 'tag', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		$user = JFactory::getUser();

		if (!$user->authorise('core.edit.state', 'com_tags' . $jinput->get('id')))
		{
			// Disable fields for display.
			$form->setFieldAttribute('ordering', 'disabled', 'true');
			$form->setFieldAttribute('published', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is a record you can edit.
			$form->setFieldAttribute('ordering', 'filter', 'unset');
			$form->setFieldAttribute('published', 'filter', 'unset');
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   3.1
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_tags.edit.tag.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		$this->preprocessData('com_tags.tag', $data);

		return $data;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.1
	 */
	public function save($data)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$table      = $this->getTable();
		$input      = JFactory::getApplication()->input;
		$pk         = (!empty($data['id'])) ? $data['id'] : (int) $this->getState($this->getName() . '.id');
		$isNew      = true;
		$context    = $this->option . '.' . $this->name;

		// Include the plugins for the save events.
		JPluginHelper::importPlugin($this->events_map['save']);

		// Load the row if saving an existing tag.
		if ($pk > 0)
		{
			$table->load($pk);
			$isNew = false;
		}

		// Set the new parent id if parent id not matched OR while New/Save as Copy .
		if ($table->parent_id != $data['parent_id'] || $data['id'] == 0)
		{
			$table->setLocation($data['parent_id'], 'last-child');
		}

		if (isset($data['images']) && is_array($data['images']))
		{
			$registry = new Registry($data['images']);
			$data['images'] = (string) $registry;
		}

		if (isset($data['urls']) && is_array($data['urls']))
		{
			$registry = new Registry($data['urls']);
			$data['urls'] = (string) $registry;
		}

		// Alter the title for save as copy
		if ($input->get('task') == 'save2copy')
		{
			$origTable = $this->getTable();
			$origTable->load($input->getInt('id'));

			if ($data['title'] == $origTable->title)
			{
				list($title, $alias) = $this->generateNewTitle($data['parent_id'], $data['alias'], $data['title']);
				$data['title'] = $title;
				$data['alias'] = $alias;
			}
			elseif ($data['alias'] == $origTable->alias)
			{
				$data['alias'] = '';
			}

			$data['published'] = 0;
		}

		// Bind the data.
		if (!$table->bind($data))
		{
			$this->setError($table->getError());

			return false;
		}

		// Bind the rules.
		if (isset($data['rules']))
		{
			$rules = new JAccessRules($data['rules']);
			$table->setRules($rules);
		}

		// Check the data.
		if (!$table->check())
		{
			$this->setError($table->getError());

			return false;
		}

		// Trigger the before save event.
		$result = $dispatcher->trigger($this->event_before_save, array($context, &$table, $isNew));

		if (in_array(false, $result, true))
		{
			$this->setError($table->getError());

			return false;
		}

		// Store the data.
		if (!$table->store())
		{
			$this->setError($table->getError());

			return false;
		}

		// Trigger the after save event.
		$dispatcher->trigger($this->event_after_save, array($context, &$table, $isNew));

		// Rebuild the path for the tag:
		if (!$table->rebuildPath($table->id))
		{
			$this->setError($table->getError());

			return false;
		}

		// Rebuild the paths of the tag's children:
		if (!$table->rebuild($table->id, $table->lft, $table->level, $table->path))
		{
			$this->setError($table->getError());

			return false;
		}

		$this->setState($this->getName() . '.id', $table->id);

		// Clear the cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method rebuild the entire nested set tree.
	 *
	 * @return  boolean  False on failure or error, true otherwise.
	 *
	 * @since   3.1
	 */
	public function rebuild()
	{
		// Get an instance of the table object.
		$table = $this->getTable();

		if (!$table->rebuild())
		{
			$this->setError($table->getError());

			return false;
		}

		// Clear the cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to save the reordered nested set tree.
	 * First we save the new order values in the lft values of the changed ids.
	 * Then we invoke the table rebuild to implement the new ordering.
	 *
	 * @param   array    $idArray   An array of primary key ids.
	 * @param   integer  $lftArray  The lft value
	 *
	 * @return  boolean  False on failure or error, True otherwise
	 *
	 * @since   3.1
	 */
	public function saveorder($idArray = null, $lftArray = null)
	{
		// Get an instance of the table object.
		$table = $this->getTable();

		if (!$table->saveorder($idArray, $lftArray))
		{
			$this->setError($table->getError());

			return false;
		}

		// Clear the cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to change the title & alias.
	 *
	 * @param   integer  $parentId  The id of the parent.
	 * @param   string   $alias     The alias.
	 * @param   string   $title     The title.
	 *
	 * @return  array  Contains the modified title and alias.
	 *
	 * @since   3.1
	 */
	protected function generateNewTitle($parentId, $alias, $title)
	{
		// Alter the title & alias
		$table = $this->getTable();

		while ($table->load(array('alias' => $alias, 'parent_id' => $parentId)))
		{
			$title = ($table->title != $title) ? $title : StringHelper::increment($title);
			$alias = StringHelper::increment($alias, 'dash');
		}

		return array($title, $alias);
	}
}
tags.php000060400000023176152455610750006232 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_tags
 *
 * @copyright   (C) 2013 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Tags Component Tags Model
 *
 * @since  3.1
 */
class TagsModelTags extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see    JController
	 * @since  3.0.3
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'title', 'a.title',
				'alias', 'a.alias',
				'published', 'a.published',
				'access', 'a.access', 'access_level',
				'language', 'a.language',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'created_time', 'a.created_time',
				'created_user_id', 'a.created_user_id',
				'lft', 'a.lft',
				'rgt', 'a.rgt',
				'level', 'a.level',
				'path', 'a.path',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return    void
	 *
	 * @since    3.1
	 */
	protected function populateState($ordering = 'a.lft', $direction = 'asc')
	{
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$level = $this->getUserStateFromRequest($this->context . '.filter.level', 'filter_level', '');
		$this->setState('filter.level', $level);

		$access = $this->getUserStateFromRequest($this->context . '.filter.access', 'filter_access', '');
		$this->setState('filter.access', $access);

		$published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
		$this->setState('filter.published', $published);

		$language = $this->getUserStateFromRequest($this->context . '.filter.language', 'filter_language', '');
		$this->setState('filter.language', $language);

		$extension = $this->getUserStateFromRequest($this->context . '.filter.extension', 'extension', 'com_content', 'cmd');

		$this->setState('filter.extension', $extension);
		$parts = explode('.', $extension);

		// Extract the component name
		$this->setState('filter.component', $parts[0]);

		// Extract the optional section name
		$this->setState('filter.section', (count($parts) > 1) ? $parts[1] : null);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_tags');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   3.1
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.extension');
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.level');
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.published');
		$id .= ':' . $this->getState('filter.language');

		return parent::getStoreId($id);
	}

	/**
	 * Method to create a query for a list of items.
	 *
	 * @return  string
	 *
	 * @since  3.1
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$user = JFactory::getUser();

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.title, a.alias, a.note, a.published, a.access, a.description' .
					', a.checked_out, a.checked_out_time, a.created_user_id' .
					', a.path, a.parent_id, a.level, a.lft, a.rgt' .
					', a.language'
			)
		);
		$query->from('#__tags AS a')
			->where('a.alias <> ' . $db->quote('root'));

		// Join over the language
		$query->select('l.title AS language_title, l.image AS language_image')
			->join('LEFT', $db->quoteName('#__languages') . ' AS l ON l.lang_code = a.language');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor')
			->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');

		// Join over the users for the author.
		$query->select('ua.name AS author_name')
			->join('LEFT', '#__users AS ua ON ua.id = a.created_user_id')

			->select('ug.title AS access_title')
			->join('LEFT', '#__viewlevels AS ug on ug.id = a.access');

		// Filter on the level.
		if ($level = $this->getState('filter.level'))
		{
			$query->where('a.level <= ' . (int) $level);
		}

		// Filter by access level.
		if ($access = $this->getState('filter.access'))
		{
			$query->where('a.access = ' . (int) $access);
		}

		// Implement View Level Access
		if (!$user->authorise('core.admin'))
		{
			$groups = implode(',', $user->getAuthorisedViewLevels());
			$query->where('a.access IN (' . $groups . ')');
		}

		// Filter by published state
		$published = $this->getState('filter.published');

		if (is_numeric($published))
		{
			$query->where('a.published = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.published IN (0, 1))');
		}

		// Filter by search in title
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where('(a.title LIKE ' . $search . ' OR a.alias LIKE ' . $search . ' OR a.note LIKE ' . $search . ')');
			}
		}

		// Filter on the language.
		if ($language = $this->getState('filter.language'))
		{
			$query->where('a.language = ' . $db->quote($language));
		}

		// Add the list ordering clause
		$listOrdering = $this->getState('list.ordering', 'a.lft');
		$listDirn = $db->escape($this->getState('list.direction', 'ASC'));

		if ($listOrdering == 'a.access')
		{
			$query->order('a.access ' . $listDirn . ', a.lft ' . $listDirn);
		}
		else
		{
			$query->order($db->escape($listOrdering) . ' ' . $listDirn);
		}

		return $query;
	}

	/**
	 * Method override to check-in a record or an array of record
	 *
	 * @param   mixed  $pks  The ID of the primary key or an array of IDs
	 *
	 * @return  mixed  Boolean false if there is an error, otherwise the count of records checked in.
	 *
	 * @since   3.0.1
	 */
	public function checkin($pks = array())
	{
		$pks = (array) $pks;
		$table = $this->getTable();
		$count = 0;

		if (empty($pks))
		{
			$pks = array((int) $this->getState($this->getName() . '.id'));
		}

		// Check in all items.
		foreach ($pks as $pk)
		{
			if ($table->load($pk))
			{
				if ($table->checked_out > 0)
				{
					// Only attempt to check the row in if it exists.
					if ($pk)
					{
						$user = JFactory::getUser();

						// Get an instance of the row to checkin.
						$table = $this->getTable();

						if (!$table->load($pk))
						{
							$this->setError($table->getError());

							return false;
						}

						// Check if this is the user having previously checked out the row.
						if ($table->checked_out > 0 && $table->checked_out != $user->get('id') && !$user->authorise('core.admin', 'com_checkin'))
						{
							$this->setError(JText::_('JLIB_APPLICATION_ERROR_CHECKIN_USER_MISMATCH'));

							return false;
						}

						// Attempt to check the row in.
						if (!$table->checkin($pk))
						{
							$this->setError($table->getError());

							return false;
						}
					}

					$count++;
				}
			}
			else
			{
				$this->setError($table->getError());

				return false;
			}
		}

		return $count;
	}

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $type    The table name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   3.1
	 */
	public function getTable($type = 'Tag', $prefix = 'TagsTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get an array of data items.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   3.0.1
	 */
	public function getItems()
	{
		$items = parent::getItems();

		if ($items != false)
		{
			$extension = $this->getState('filter.extension');

			$this->countItems($items, $extension);
		}

		return $items;
	}

	/**
	 * Method to load the countItems method from the extensions
	 *
	 * @param   stdClass[]  &$items     The category items
	 * @param   string      $extension  The category extension
	 *
	 * @return  void
	 *
	 * @since   3.5
	 */
	public function countItems(&$items, $extension)
	{
		$parts = explode('.', $extension);
		$component = $parts[0];
		$section = null;

		if (count($parts) < 2)
		{
			return;
		}

		// Try to find the component helper.
		$eName = str_replace('com_', '', $component);
		$file = JPath::clean(JPATH_ADMINISTRATOR . '/components/' . $component . '/helpers/' . $eName . '.php');

		if (file_exists($file))
		{
			$prefix = ucfirst(str_replace('com_', '', $component));
			$cName = $prefix . 'Helper';

			JLoader::register($cName, $file);

			if (class_exists($cName) && is_callable(array($cName, 'countTagItems')))
			{
				$cName::countTagItems($items, $extension);
			}
		}
	}
}
forms/filter_modules.xml000060400000007374152455625210011447 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_modules/models/fields" />

	<field
		name="client_id"
		type="list"
		label=""
		filtermode="selector"
		layout="default"
		onchange="jQuery('#filter_position, #filter_module, #filter_language, #filter_menuitem').val('');this.form.submit();"
		>
		<option value="0">JSITE</option>
		<option value="1">JADMINISTRATOR</option>
	</field>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_MODULES_MODULES_FILTER_SEARCH_LABEL"
			description="COM_MODULES_MODULES_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
			noresults="COM_MODULES_MSG_MANAGE_NO_MODULES"
		/>
		<field
			name="state"
			type="status"
			label="JSTATUS"
			filter="*,-2,0,1"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>
		<field
			name="position"
			type="modulesposition"
			label="COM_MODULES_FIELD_POSITION_LABEL"
			onchange="this.form.submit();"
			>
			<option value="">COM_MODULES_OPTION_SELECT_POSITION</option>
		</field>
		<field
			name="module"
			type="ModulesModule"
			label="COM_MODULES_OPTION_SELECT_MODULE"
			onchange="this.form.submit();"
			>
			<option value="">COM_MODULES_OPTION_SELECT_MODULE</option>
		</field>
		<field
			name="menuitem"
			type="menuitem"
			label="COM_MODULES_OPTION_SELECT_MENU_ITEM"
			disable="separator,alias,heading,url"
			onchange="this.form.submit();"
			>
			<option	value="">COM_MODULES_OPTION_SELECT_MENU_ITEM</option>
			<option	value="-1">COM_MODULES_NONE</option>
		</field>
		<field
			name="access"
			type="accesslevel"
			label="JOPTION_FILTER_ACCESS"
			description="JOPTION_FILTER_ACCESS_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_ACCESS</option>
		</field>
		<field
			name="language"
			type="contentlanguage"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			statuses="*,0,1,-2"
			onchange="this.form.submit();"
			default="a.position ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.published ASC">JSTATUS_ASC</option>
			<option value="a.published DESC">JSTATUS_DESC</option>
			<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="a.position ASC">COM_MODULES_HEADING_POSITION_ASC</option>
			<option value="a.position DESC">COM_MODULES_HEADING_POSITION_DESC</option>
			<option value="name ASC">COM_MODULES_HEADING_MODULE_ASC</option>
			<option value="name DESC">COM_MODULES_HEADING_MODULE_DESC</option>
			<option value="pages ASC">COM_MODULES_HEADING_PAGES_ASC</option>
			<option value="pages DESC">COM_MODULES_HEADING_PAGES_DESC</option>
			<option value="ag.title ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="ag.title DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option value="l.title ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="l.title DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="COM_MODULES_LIST_LIMIT"
			description="JFIELD_PLG_SEARCH_SEARCHLIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
feature.php000060400000010215152455670110006711 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      doorknob
 * @link        http://www.joomlic.com
 *
 * @version     3.4.0 2014-12-05
 * @since       3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modeladmin');

/**
 * iCagenda model.
 */
class iCagendaModelfeature extends JModelAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	3.4.0
	 */
	protected $text_prefix = 'COM_ICAGENDA';

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	3.4.0
	 */
	public function getTable($type = 'Feature', $prefix = 'iCagendaTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		An optional array of data for the form to interogate.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	JForm	A JForm object on success, false on failure
	 * @since	3.4.0
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Initialise variables.
		$app	= JFactory::getApplication();

		// Get the form.
		$form = $this->loadForm('com_icagenda.feature', 'feature', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	3.4.0
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_icagenda.edit.feature.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param	integer	The id of the primary key.
	 *
	 * @return	mixed	Object on success, false on failure.
	 * @since	3.4.0
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			//Do any procesing on fields here if needed
		}

		return $item;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @since	3.4.0
	 */
	protected function prepareTable($table)
	{
		jimport('joomla.filter.output');

		if (empty($table->id))
		{
			// Set ordering to the last item if not set
			if (@$table->ordering === '')
			{
				$db = JFactory::getDbo();
				$db->setQuery('SELECT MAX(ordering) FROM #__icagenda_feature');
				$max = $db->loadResult();
				$table->ordering = $max+1;
			}
		}
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.4.0
	 */
	public function save($data)
	{
		$date = JFactory::getDate();

		if (empty($data['created']))
		{
			$data['created'] = !empty($data['created']) ? $data['created'] : $date->toSql();
		}

		// Generates Alias if empty
		// Alias is not generated if non-latin characters, so we fix it by using created date, or title if unicode is activated, as alias
		if ($data['alias'] == null || empty($data['alias']))
		{
			$data['alias'] = JFilterOutput::stringURLSafe($data['title']);

			if ($data['alias'] == null || empty($data['alias']))
			{
				if (JFactory::getConfig()->get('unicodeslugs') == 1)
				{
					$data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['title']);
				}
				else
				{
					$data['alias'] = JFilterOutput::stringURLSafe($data['created']);
				}
			}
		}

		$return = parent::save($data);

		return $return;
	}
}
forms/filter_featured.xml000060400000010400152455670110011555 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_CONTENT_FILTER_SEARCH_LABEL"
			description="COM_CONTENT_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="published"
			type="status"
			label="COM_CONTENT_FILTER_PUBLISHED"
			description="COM_CONTENT_FILTER_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="category_id"
			type="category"
			label="JOPTION_FILTER_CATEGORY"
			description="JOPTION_FILTER_CATEGORY_DESC"
			multiple="true"
			class="multipleCategories"
			extension="com_content"
			onchange="this.form.submit();"
		/>

		<field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="10"
			step="1"
			languages="*"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
		</field>

		<field
			name="access"
			type="accesslevel"
			label="JOPTION_FILTER_ACCESS"
			description="JOPTION_FILTER_ACCESS_DESC"
			multiple="true"
			class="multipleAccessLevels"
			onchange="this.form.submit();"
		/>

		<field
			name="author_id"
			type="author"
			label="COM_CONTENT_FILTER_AUTHOR"
			description="COM_CONTENT_FILTER_AUTHOR_DESC"
			multiple="true"
			class="multipleAuthors"
			onchange="this.form.submit();"
			>
			<option value="0">JNONE</option>
		</field>

		<field
			name="language"
			type="contentlanguage"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>

		<field
			name="tag"
			type="tag"
			label="JOPTION_FILTER_TAG"
			description="JOPTION_FILTER_TAG_DESC"
			multiple="true"
			class="multipleTags"
			mode="nested"
			onchange="this.form.submit();"
		/>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="COM_CONTENT_LIST_FULL_ORDERING"
			description="COM_CONTENT_LIST_FULL_ORDERING_DESC"
			onchange="this.form.submit();"
			default="a.title ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="fp.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="fp.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.state ASC">JSTATUS_ASC</option>
			<option value="a.state DESC">JSTATUS_DESC</option>
			<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="category_title ASC">JCATEGORY_ASC</option>
			<option value="category_title DESC">JCATEGORY_DESC</option>
			<option value="a.access ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="a.access DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option value="a.created_by ASC">JAUTHOR_ASC</option>
			<option value="a.created_by DESC">JAUTHOR_DESC</option>
			<option value="a.publish_up ASC">COM_CONTENT_PUBLISH_UP_ASC</option>
			<option value="a.publish_up DESC">COM_CONTENT_PUBLISH_UP_DESC</option>
			<option value="a.publish_down ASC">COM_CONTENT_PUBLISH_DOWN_ASC</option>
			<option value="a.publish_down DESC">COM_CONTENT_PUBLISH_DOWN_DESC</option>
			<option value="language ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="language DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.created ASC">JDATE_ASC</option>
			<option value="a.created DESC">JDATE_DESC</option>
			<option value="a.hits ASC">JGLOBAL_HITS_ASC</option>
			<option value="a.hits DESC">JGLOBAL_HITS_DESC</option>
			<option value="rating_count ASC" requires="vote">JGLOBAL_VOTES_ASC</option>
			<option value="rating_count DESC" requires="vote">JGLOBAL_VOTES_DESC</option>
			<option value="rating ASC" requires="vote">JGLOBAL_RATINGS_ASC</option>
			<option value="rating DESC" requires="vote">JGLOBAL_RATINGS_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="COM_CONTENT_LIST_LIMIT"
			description="COM_CONTENT_LIST_LIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
fields/modal/article.php000060400000023130152455670110011243 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_content
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Language\LanguageHelper;

/**
 * Supports a modal article picker.
 *
 * @since  1.6
 */
class JFormFieldModal_Article extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $type = 'Modal_Article';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   1.6
	 */
	protected function getInput()
	{
		$allowNew       = ((string) $this->element['new'] == 'true');
		$allowEdit      = ((string) $this->element['edit'] == 'true');
		$allowClear     = ((string) $this->element['clear'] != 'false');
		$allowSelect    = ((string) $this->element['select'] != 'false');
		$allowPropagate = ((string) $this->element['propagate'] == 'true');

		$languages = LanguageHelper::getContentLanguages(array(0, 1));

		// Load language
		JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR);

		// The active article id field.
		$value = (int) $this->value > 0 ? (int) $this->value : '';

		// Create the modal id.
		$modalId = 'Article_' . $this->id;

		// Add the modal field script to the document head.
		JHtml::_('jquery.framework');
		JHtml::_('script', 'system/modal-fields.js', array('version' => 'auto', 'relative' => true));

		// Script to proxy the select modal function to the modal-fields.js file.
		if ($allowSelect)
		{
			static $scriptSelect = null;

			if (is_null($scriptSelect))
			{
				$scriptSelect = array();
			}

			if (!isset($scriptSelect[$this->id]))
			{
				JFactory::getDocument()->addScriptDeclaration("
				function jSelectArticle_" . $this->id . "(id, title, catid, object, url, language) {
					window.processModalSelect('Article', '" . $this->id . "', id, title, catid, object, url, language);
				}
				");

				JText::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED');

				$scriptSelect[$this->id] = true;
			}
		}

		// Setup variables for display.
		$linkArticles = 'index.php?option=com_content&amp;view=articles&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';
		$linkArticle  = 'index.php?option=com_content&amp;view=article&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';

		if (isset($this->element['language']))
		{
			$linkArticles .= '&amp;forcedLanguage=' . $this->element['language'];
			$linkArticle  .= '&amp;forcedLanguage=' . $this->element['language'];
			$modalTitle    = JText::_('COM_CONTENT_CHANGE_ARTICLE') . ' &#8212; ' . $this->element['label'];
		}
		else
		{
			$modalTitle    = JText::_('COM_CONTENT_CHANGE_ARTICLE');
		}

		$urlSelect = $linkArticles . '&amp;function=jSelectArticle_' . $this->id;
		$urlEdit   = $linkArticle . '&amp;task=article.edit&amp;id=\' + document.getElementById("' . $this->id . '_id").value + \'';
		$urlNew    = $linkArticle . '&amp;task=article.add';

		if ($value)
		{
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true)
				->select($db->quoteName('title'))
				->from($db->quoteName('#__content'))
				->where($db->quoteName('id') . ' = ' . (int) $value);
			$db->setQuery($query);

			try
			{
				$title = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				JError::raiseWarning(500, $e->getMessage());
			}
		}

		$title = empty($title) ? JText::_('COM_CONTENT_SELECT_AN_ARTICLE') : htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

		// The current article display field.
		$html  = '<span class="input-append">';
		$html .= '<input class="input-medium" id="' . $this->id . '_name" type="text" value="' . $title . '" disabled="disabled" size="35" />';

		// Select article button
		if ($allowSelect)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"'
				. ' id="' . $this->id . '_select"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalSelect' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_CONTENT_CHANGE_ARTICLE') . '">'
				. '<span class="icon-file" aria-hidden="true"></span> ' . JText::_('JSELECT')
				. '</button>';
		}

		// New article button
		if ($allowNew)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"'
				. ' id="' . $this->id . '_new"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalNew' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_CONTENT_NEW_ARTICLE') . '">'
				. '<span class="icon-new" aria-hidden="true"></span> ' . JText::_('JACTION_CREATE')
				. '</button>';
		}

		// Edit article button
		if ($allowEdit)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"'
				. ' id="' . $this->id . '_edit"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalEdit' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_CONTENT_EDIT_ARTICLE') . '">'
				. '<span class="icon-edit" aria-hidden="true"></span> ' . JText::_('JACTION_EDIT')
				. '</button>';
		}

		// Clear article button
		if ($allowClear)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn' . ($value ? '' : ' hidden') . '"'
				. ' id="' . $this->id . '_clear"'
				. ' onclick="window.processModalParent(\'' . $this->id . '\'); return false;">'
				. '<span class="icon-remove" aria-hidden="true"></span>' . JText::_('JCLEAR')
				. '</button>';
		}

		// Propagate article button
		if ($allowPropagate && count($languages) > 2)
		{
			// Strip off language tag at the end
			$tagLength = (int) strlen($this->element['language']);
			$callbackFunctionStem = substr("jSelectArticle_" . $this->id, 0, -$tagLength);

			$html .= '<a'
			. ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"'
			. ' id="' . $this->id . '_propagate"'
			. ' href="#"'
			. ' title="' . JHtml::tooltipText('JGLOBAL_ASSOCIATIONS_PROPAGATE_TIP') . '"'
			. ' onclick="Joomla.propagateAssociation(\'' . $this->id . '\', \'' . $callbackFunctionStem . '\');">'
			. '<span class="icon-refresh" aria-hidden="true"></span>' . JText::_('JGLOBAL_ASSOCIATIONS_PROPAGATE_BUTTON')
			. '</a>';
		}

		$html .= '</span>';

		// Select article modal
		if ($allowSelect)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalSelect' . $modalId,
				array(
					'title'       => $modalTitle,
					'url'         => $urlSelect,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn" data-dismiss="modal">' . JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>',
				)
			);
		}

		// New article modal
		if ($allowNew)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalNew' . $modalId,
				array(
					'title'       => JText::_('COM_CONTENT_NEW_ARTICLE'),
					'backdrop'    => 'static',
					'keyboard'    => false,
					'closeButton' => false,
					'url'         => $urlNew,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'add\', \'article\', \'cancel\', \'item-form\'); return false;">'
							. JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>'
							. '<button type="button" class="btn btn-primary"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'add\', \'article\', \'save\', \'item-form\'); return false;">'
							. JText::_('JSAVE') . '</button>'
							. '<button type="button" class="btn btn-success"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'add\', \'article\', \'apply\', \'item-form\'); return false;">'
							. JText::_('JAPPLY') . '</button>',
				)
			);
		}

		// Edit article modal
		if ($allowEdit)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalEdit' . $modalId,
				array(
					'title'       => JText::_('COM_CONTENT_EDIT_ARTICLE'),
					'backdrop'    => 'static',
					'keyboard'    => false,
					'closeButton' => false,
					'url'         => $urlEdit,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'edit\', \'article\', \'cancel\', \'item-form\'); return false;">'
							. JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>'
							. '<button type="button" class="btn btn-primary"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'edit\', \'article\', \'save\', \'item-form\'); return false;">'
							. JText::_('JSAVE') . '</button>'
							. '<button type="button" class="btn btn-success"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id . '\', \'edit\', \'article\', \'apply\', \'item-form\'); return false;">'
							. JText::_('JAPPLY') . '</button>',
				)
			);
		}

		// Note: class='required' for client side validation.
		$class = $this->required ? ' class="required modal-value"' : '';

		$html .= '<input type="hidden" id="' . $this->id . '_id" ' . $class . ' data-required="' . (int) $this->required . '" name="' . $this->name
			. '" data-text="' . htmlspecialchars(JText::_('COM_CONTENT_SELECT_AN_ARTICLE'), ENT_COMPAT, 'UTF-8') . '" value="' . $value . '" />';

		return $html;
	}

	/**
	 * Method to get the field label markup.
	 *
	 * @return  string  The field label markup.
	 *
	 * @since   3.4
	 */
	protected function getLabel()
	{
		return str_replace($this->id, $this->id . '_id', parent::getLabel());
	}
}
fields/voteradio.php000060400000002132152455670110010517 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_content
 *
 * @copyright   (C) 2017 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JFormHelper::loadFieldClass('radio');

/**
 * Voteradio Field class.
 *
 * @since  3.8.0
 */
class JFormFieldVoteradio extends JFormFieldRadio
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.7.1
	 */
	protected $type = 'Voteradio';

	/**
	 * Method to get the field Label.
	 *
	 * @return array The field label objects.
	 *
	 * @throws \Exception
	 *
	 * @since  3.8.2
	 */
	public function getLabel()
	{
		// Requires vote plugin enabled
		return JPluginHelper::isEnabled('content', 'vote') ? parent::getLabel() : null;
	}

	/**
	 * Method to get the field options.
	 *
	 * @return array The field option objects.
	 *
	 * @throws \Exception
	 *
	 * @since  3.7.1
	 */
	public function getOptions()
	{
		// Requires vote plugin enabled
		return JPluginHelper::isEnabled('content', 'vote') ? parent::getOptions() : array();
	}
}
indexer.php000060400000000567152455702220006723 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Indexer model class for Finder.
 *
 * @since  2.5
 */
class FinderModelIndexer extends JModelLegacy
{
}
filters.php000060400000007364152455702220006737 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Filters model class for Finder.
 *
 * @since  2.5
 */
class FinderModelFilters extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An associative array of configuration settings. [optional]
	 *
	 * @since   2.5
	 * @see     JControllerLegacy
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'filter_id', 'a.filter_id',
				'title', 'a.title',
				'state', 'a.state',
				'created_by_alias', 'a.created_by_alias',
				'created', 'a.created',
				'map_count', 'a.map_count'
			);
		}

		parent::__construct($config);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery  A JDatabaseQuery object
	 *
	 * @since   2.5
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select all fields from the table.
		$query->select('a.*')
			->from($db->quoteName('#__finder_filters', 'a'));

		// Join over the users for the checked out user.
		$query->select($db->quoteName('uc.name', 'editor'))
			->join('LEFT', $db->quoteName('#__users', 'uc') . ' ON ' . $db->quoteName('uc.id') . ' = ' . $db->quoteName('a.checked_out'));

		// Join over the users for the author.
		$query->select($db->quoteName('ua.name', 'user_name'))
			->join('LEFT', $db->quoteName('#__users', 'ua') . ' ON ' . $db->quoteName('ua.id') . ' = ' . $db->quoteName('a.created_by'));

		// Check for a search filter.
		if ($search = $this->getState('filter.search'))
		{
			$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
			$query->where($db->quoteName('a.title') . ' LIKE ' . $search);
		}

		// If the model is set to check item state, add to the query.
		$state = $this->getState('filter.state');

		if (is_numeric($state))
		{
			$query->where($db->quoteName('a.state') . ' = ' . (int) $state);
		}

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'a.title') . ' ' . $db->escape($this->getState('list.direction', 'ASC'))));

		return $query;
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id. [optional]
	 *
	 * @return  string  A store id.
	 *
	 * @since   2.5
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.state');

		return parent::getStoreId($id);
	}

	/**
	 * Method to auto-populate the model state.  Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field. [optional]
	 * @param   string  $direction  An optional direction. [optional]
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	protected function populateState($ordering = 'a.title', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.state', $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'cmd'));

		// Load the parameters.
		$params = JComponentHelper::getParams('com_finder');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}
}
index.php000060400000026656152455702220006403 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Index model class for Finder.
 *
 * @since  2.5
 */
class FinderModelIndex extends JModelList
{
	/**
	 * The event to trigger after deleting the data.
	 *
	 * @var    string
	 * @since  2.5
	 */
	protected $event_after_delete = 'onContentAfterDelete';

	/**
	 * The event to trigger before deleting the data.
	 *
	 * @var    string
	 * @since  2.5
	 */
	protected $event_before_delete = 'onContentBeforeDelete';

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An associative array of configuration settings. [optional]
	 *
	 * @since   2.5
	 * @see     JControllerLegacy
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'state', 'published', 'l.published',
				'title', 'l.title',
				'type', 'type_id', 'l.type_id',
				't.title', 't_title',
				'url', 'l.url',
				'indexdate', 'l.indexdate',
				'content_map',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission for the component.
	 *
	 * @since   2.5
	 */
	protected function canDelete($record)
	{
		return JFactory::getUser()->authorise('core.delete', $this->option);
	}

	/**
	 * Method to test whether a record can have its state changed.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission for the component.
	 *
	 * @since   2.5
	 */
	protected function canEditState($record)
	{
		return JFactory::getUser()->authorise('core.edit.state', $this->option);
	}

	/**
	 * Method to delete one or more records.
	 *
	 * @param   array  $pks  An array of record primary keys.
	 *
	 * @return  boolean  True if successful, false if an error occurs.
	 *
	 * @since   2.5
	 */
	public function delete(&$pks)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$pks = (array) $pks;
		$table = $this->getTable();

		// Include the content plugins for the on delete events.
		JPluginHelper::importPlugin('content');

		// Iterate the items to delete each one.
		foreach ($pks as $i => $pk)
		{
			if ($table->load($pk))
			{
				if ($this->canDelete($table))
				{
					$context = $this->option . '.' . $this->name;

					// Trigger the onContentBeforeDelete event.
					$result = $dispatcher->trigger($this->event_before_delete, array($context, $table));

					if (in_array(false, $result, true))
					{
						$this->setError($table->getError());

						return false;
					}

					if (!$table->delete($pk))
					{
						$this->setError($table->getError());

						return false;
					}

					// Trigger the onContentAfterDelete event.
					$dispatcher->trigger($this->event_after_delete, array($context, $table));
				}
				else
				{
					// Prune items that you can't change.
					unset($pks[$i]);
					$error = $this->getError();

					if ($error)
					{
						$this->setError($error);
					}
					else
					{
						$this->setError(JText::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'));
					}
				}
			}
			else
			{
				$this->setError($table->getError());

				return false;
			}
		}

		// Clear the component's cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery  A JDatabaseQuery object
	 *
	 * @since   2.5
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('l.*')
			->select($db->quoteName('t.title', 't_title'))
			->from($db->quoteName('#__finder_links', 'l'))
			->join('INNER', $db->quoteName('#__finder_types', 't') . ' ON ' . $db->quoteName('t.id') . ' = ' . $db->quoteName('l.type_id'));

		// Check the type filter.
		$type = $this->getState('filter.type');

		if (is_numeric($type))
		{
			$query->where($db->quoteName('l.type_id') . ' = ' . (int) $type);
		}

		// Check the map filter.
		$contentMapId = $this->getState('filter.content_map');

		if (is_numeric($contentMapId))
		{
			$query->join('INNER', $db->quoteName('#__finder_taxonomy_map', 'm') . ' ON ' . $db->quoteName('m.link_id') . ' = ' . $db->quoteName('l.link_id'))
				->where($db->quoteName('m.node_id') . ' = ' . (int) $contentMapId);
		}

		// Check for state filter.
		$state = $this->getState('filter.state');

		if (is_numeric($state))
		{
			$query->where($db->quoteName('l.published') . ' = ' . (int) $state);
		}

		// Check the search phrase.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			$search      = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
			$orSearchSql = $db->quoteName('l.title') . ' LIKE ' . $search . ' OR ' . $db->quoteName('l.url') . ' LIKE ' . $search;

			// Filter by indexdate only if $search doesn't contains non-ascii characters
			if (!preg_match('/[^\x00-\x7F]/', $search))
			{
				$orSearchSql .= ' OR ' . $query->castAsChar($db->quoteName('l.indexdate')) . ' LIKE ' . $search;
			}

			$query->where('(' . $orSearchSql . ')');
		}

		// Handle the list ordering.
		$listOrder = $this->getState('list.ordering', 'l.title');
		$listDir   = $this->getState('list.direction', 'ASC');

		if ($listOrder === 't.title')
		{
			$ordering = $db->quoteName('t.title') . ' ' . $db->escape($listDir) . ', ' . $db->quoteName('l.title') . ' ' . $db->escape($listDir);
		}
		else
		{
			$ordering = $db->escape($listOrder) . ' ' . $db->escape($listDir);
		}

		$query->order($ordering);

		return $query;
	}

	/**
	 * Method to get the state of the Smart Search Plugins.
	 *
	 * @return  array  Array of relevant plugins and whether they are enabled or not.
	 *
	 * @since   2.5
	 */
	public function getPluginState()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('name, enabled')
			->from($db->quoteName('#__extensions'))
			->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
			->where($db->quoteName('folder') . ' IN (' . $db->quote('system') . ',' . $db->quote('content') . ')')
			->where($db->quoteName('element') . ' = ' . $db->quote('finder'));
		$db->setQuery($query);

		return $db->loadObjectList('name');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id. [optional]
	 *
	 * @return  string  A store id.
	 *
	 * @since   2.5
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.state');
		$id .= ':' . $this->getState('filter.type');
		$id .= ':' . $this->getState('filter.content_map');

		return parent::getStoreId($id);
	}

	/**
	 * Gets the total of indexed items.
	 *
	 * @return  integer  The total of indexed items.
	 *
	 * @since   3.6.0
	 */
	public function getTotalIndexed()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('COUNT(link_id)')
			->from($db->quoteName('#__finder_links'));
		$db->setQuery($query);

		$db->execute();

		return (int) $db->loadResult();
	}

	/**
	 * Returns a JTable object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate. [optional]
	 * @param   string  $prefix  A prefix for the table class name. [optional]
	 * @param   array   $config  Configuration array for model. [optional]
	 *
	 * @return  JTable  A database object
	 *
	 * @since   2.5
	 */
	public function getTable($type = 'Link', $prefix = 'FinderTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to purge the index, deleting all links.
	 *
	 * @return  boolean  True on success, false on failure.
	 *
	 * @since   2.5
	 * @throws  Exception on database error
	 */
	public function purge()
	{
		$db = $this->getDbo();

		// Truncate the links table.
		$db->truncateTable('#__finder_links');

		// Truncate the links terms tables.
		for ($i = 0; $i <= 15; $i++)
		{
			// Get the mapping table suffix.
			$suffix = dechex($i);

			$db->truncateTable('#__finder_links_terms' . $suffix);
		}

		// Truncate the terms table.
		$db->truncateTable('#__finder_terms');

		// Truncate the taxonomy map table.
		$db->truncateTable('#__finder_taxonomy_map');

		// Delete all the taxonomy nodes except the root.
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__finder_taxonomy'))
			->where($db->quoteName('id') . ' > 1');
		$db->setQuery($query);
		$db->execute();

		// Truncate the tokens tables.
		$db->truncateTable('#__finder_tokens');

		// Truncate the tokens aggregate table.
		$db->truncateTable('#__finder_tokens_aggregate');

		return true;
	}

	/**
	 * Method to auto-populate the model state.  Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field. [optional]
	 * @param   string  $direction  An optional direction. [optional]
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	protected function populateState($ordering = 'l.title', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.state', $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'cmd'));
		$this->setState('filter.type', $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'cmd'));
		$this->setState('filter.content_map', $this->getUserStateFromRequest($this->context . '.filter.content_map', 'filter_content_map', '', 'cmd'));

		// Load the parameters.
		$params = JComponentHelper::getParams('com_finder');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to change the published state of one or more records.
	 *
	 * @param   array    $pks    A list of the primary keys to change.
	 * @param   integer  $value  The value of the published state. [optional]
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   2.5
	 */
	public function publish(&$pks, $value = 1)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$user = JFactory::getUser();
		$table = $this->getTable();
		$pks = (array) $pks;

		// Include the content plugins for the change of state event.
		JPluginHelper::importPlugin('content');

		// Access checks.
		foreach ($pks as $i => $pk)
		{
			$table->reset();

			if ($table->load($pk) && !$this->canEditState($table))
			{
				// Prune items that you can't change.
				unset($pks[$i]);
				$this->setError(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));

				return false;
			}
		}

		// Attempt to change the state of the records.
		if (!$table->publish($pks, $value, $user->get('id')))
		{
			$this->setError($table->getError());

			return false;
		}

		$context = $this->option . '.' . $this->name;

		// Trigger the onContentChangeState event.
		$result = $dispatcher->trigger('onContentChangeState', array($context, $pks, $value));

		if (in_array(false, $result, true))
		{
			$this->setError($table->getError());

			return false;
		}

		// Clear the component's cache
		$this->cleanCache();

		return true;
	}
}
filter.php000060400000007160152455702220006546 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Filter model class for Finder.
 *
 * @since  2.5
 */
class FinderModelFilter extends JModelAdmin
{
	/**
	 * The prefix to use with controller messages.
	 *
	 * @var    string
	 * @since  2.5
	 */
	protected $text_prefix = 'COM_FINDER';

	/**
	 * Model context string.
	 *
	 * @var    string
	 * @since  2.5
	 */
	protected $context = 'com_finder.filter';

	/**
	 * Custom clean cache method.
	 *
	 * @param   string   $group     The component name. [optional]
	 * @param   integer  $clientId  The client ID. [optional]
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	protected function cleanCache($group = 'com_finder', $clientId = 1)
	{
		parent::cleanCache($group, $clientId);
	}

	/**
	 * Method to get the filter data.
	 *
	 * @return  FinderTableFilter|boolean  The filter data or false on a failure.
	 *
	 * @since   2.5
	 */
	public function getFilter()
	{
		$filter_id = (int) $this->getState('filter.id');

		// Get a FinderTableFilter instance.
		$filter = $this->getTable();

		// Attempt to load the row.
		$return = $filter->load($filter_id);

		// Check for a database error.
		if ($return === false && $filter->getError())
		{
			$this->setError($filter->getError());

			return false;
		}

		// Process the filter data.
		if (!empty($filter->data))
		{
			$filter->data = explode(',', $filter->data);
		}
		elseif (empty($filter->data))
		{
			$filter->data = array();
		}

		// Check for a database error.
		if ($this->_db->getErrorNum())
		{
			$this->setError($this->_db->getErrorMsg());

			return false;
		}

		return $filter;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form. [optional]
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not. [optional]
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   2.5
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_finder.filter', 'filter', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Returns a JTable object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate. [optional]
	 * @param   string  $prefix  A prefix for the table class name. [optional]
	 * @param   array   $config  Configuration array for model. [optional]
	 *
	 * @return  JTable  A database object
	 *
	 * @since   2.5
	 */
	public function getTable($type = 'Filter', $prefix = 'FinderTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   2.5
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_finder.edit.filter.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		$this->preprocessData('com_finder.filter', $data);

		return $data;
	}

	/**
	 * Method to get the total indexed items
	 *
	 * @return  number the number of indexed items
	 *
	 * @since  3.5
	 */
	public function getTotal()
	{
		$db    = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('MAX(link_id)')
			->from('#__finder_links');

		return $db->setQuery($query)->loadResult();
	}
}
statistics.php000060400000004111152455702220007444 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Statistics model class for Finder.
 *
 * @since  2.5
 */
class FinderModelStatistics extends JModelLegacy
{
	/**
	 * Method to get the component statistics
	 *
	 * @return  JObject  The component statistics
	 *
	 * @since   2.5
	 */
	public function getData()
	{
		// Initialise
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$data = new JObject;

		$query->select('COUNT(term_id)')
			->from($db->quoteName('#__finder_terms'));
		$db->setQuery($query);
		$data->term_count = $db->loadResult();

		$query->clear()
			->select('COUNT(link_id)')
			->from($db->quoteName('#__finder_links'));
		$db->setQuery($query);
		$data->link_count = $db->loadResult();

		$query->clear()
			->select('COUNT(id)')
			->from($db->quoteName('#__finder_taxonomy'))
			->where($db->quoteName('parent_id') . ' = 1');
		$db->setQuery($query);
		$data->taxonomy_branch_count = $db->loadResult();

		$query->clear()
			->select('COUNT(id)')
			->from($db->quoteName('#__finder_taxonomy'))
			->where($db->quoteName('parent_id') . ' > 1');
		$db->setQuery($query);
		$data->taxonomy_node_count = $db->loadResult();

		$query->clear()
			->select('t.title AS type_title, COUNT(a.link_id) AS link_count')
			->from($db->quoteName('#__finder_links') . ' AS a')
			->join('INNER', $db->quoteName('#__finder_types') . ' AS t ON t.id = a.type_id')
			->group('a.type_id, t.title')
			->order($db->quoteName('type_title') . ' ASC');
		$db->setQuery($query);
		$data->type_list = $db->loadObjectList();

		$lang  = JFactory::getLanguage();
		$plugins = JPluginHelper::getPlugin('finder');

		foreach ($plugins as $plugin)
		{
			$lang->load('plg_finder_' . $plugin->name . '.sys', JPATH_ADMINISTRATOR, null, false, true)
			|| $lang->load('plg_finder_' . $plugin->name . '.sys', JPATH_PLUGINS . '/finder/' . $plugin->name, null, false, true);
		}

		return $data;
	}
}
fields/searchfilter.php000060400000002173152455702220011201 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('JPATH_BASE') or die();

JFormHelper::loadFieldClass('list');

/**
 * Search Filter field for the Finder package.
 *
 * @since  2.5
 */
class JFormFieldSearchFilter extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  2.5
	 */
	protected $type = 'SearchFilter';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   2.5
	 */
	public function getOptions()
	{
		// Build the query.
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('f.title AS text, f.filter_id AS value')
			->from($db->quoteName('#__finder_filters') . ' AS f')
			->where('f.state = 1')
			->order('f.title ASC');
		$db->setQuery($query);
		$options = $db->loadObjectList();

		array_unshift($options, JHtml::_('select.option', '', JText::_('COM_FINDER_SELECT_SEARCH_FILTER'), 'value', 'text'));

		return $options;
	}
}
fields/contentmap.php000060400000006155152455702220010702 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2016 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('JPATH_PLATFORM') or die;

JFormHelper::loadFieldClass('groupedlist');

JLoader::register('FinderHelperLanguage', JPATH_ADMINISTRATOR . '/components/com_finder/helpers/language.php');

/**
 * Supports a select grouped list of finder content map.
 *
 * @since  3.6.0
 */
class JFormFieldContentMap extends JFormFieldGroupedList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.6.0
	 */
	public $type = 'ContentMap';

	/**
	 * Method to get the list of content map options grouped by first level.
	 *
	 * @return  array  The field option objects as a nested array in groups.
	 *
	 * @since   3.6.0
	 */
	protected function getGroups()
	{
		$groups = array();

		// Get the database object and a new query object.
		$db = JFactory::getDbo();

		// Levels subquery.
		$levelQuery = $db->getQuery(true);
		$levelQuery->select('title AS branch_title, 1 as level')
			->select($db->quoteName('id'))
			->from($db->quoteName('#__finder_taxonomy'))
			->where($db->quoteName('parent_id') . ' = 1');
		$levelQuery2 = $db->getQuery(true);
		$levelQuery2->select('b.title AS branch_title, 2 as level')
			->select($db->quoteName('a.id'))
			->from($db->quoteName('#__finder_taxonomy', 'a'))
			->join('LEFT', $db->quoteName('#__finder_taxonomy', 'b') . ' ON ' . $db->qn('a.parent_id') . ' = ' . $db->qn('b.id'))
			->where($db->quoteName('a.parent_id') . ' NOT IN (0, 1)');

		$levelQuery->union($levelQuery2);

		// Main query.
		$query = $db->getQuery(true)
			->select($db->quoteName('a.title', 'text'))
			->select($db->quoteName('a.id', 'value'))
			->select($db->quoteName('d.level'))
			->from($db->quoteName('#__finder_taxonomy', 'a'))
			->join('LEFT', '(' . $levelQuery . ') AS d ON ' . $db->qn('d.id') . ' = ' . $db->qn('a.id'))
			->where($db->quoteName('a.parent_id') . ' <> 0')
			->order('d.branch_title ASC, d.level ASC, a.title ASC');

		$db->setQuery($query);

		try
		{
			$contentMap = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			return;
		}

		// Build the grouped list array.
		if ($contentMap)
		{
			$lang = JFactory::getLanguage();

			foreach ($contentMap as $branch)
			{
				if ((int) $branch->level === 1)
				{
					$name = $branch->text;
				}
				else
				{
					$levelPrefix = str_repeat('- ', max(0, $branch->level - 1));

					if (trim($name, '**') === 'Language')
					{
						$text = FinderHelperLanguage::branchLanguageTitle($branch->text);
					}
					else
					{
						$key = FinderHelperLanguage::branchSingular($branch->text);
						$text = $lang->hasKey($key) ? JText::_($key) : $branch->text;
					}

					// Initialize the group if necessary.
					if (!isset($groups[$name]))
					{
						$groups[$name] = array();
					}

					$groups[$name][] = JHtml::_('select.option', $branch->value, $levelPrefix . $text);
				}
			}
		}

		// Merge any additional groups in the XML definition.
		$groups = array_merge(parent::getGroups(), $groups);

		return $groups;
	}
}
fields/contenttypes.php000060400000003662152455702220011271 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2016 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('JPATH_BASE') or die();

use Joomla\Utilities\ArrayHelper;

JLoader::register('FinderHelperLanguage', JPATH_ADMINISTRATOR . '/components/com_finder/helpers/language.php');

JFormHelper::loadFieldClass('list');

/**
 * Content Types Filter field for the Finder package.
 *
 * @since  3.6.0
 */
class JFormFieldContentTypes extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.6.0
	 */
	protected $type = 'ContentTypes';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.6.0
	 */
	public function getOptions()
	{
		$lang    = JFactory::getLanguage();
		$options = array();

		$db    = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select($db->quoteName('id', 'value'))
			->select($db->quoteName('title', 'text'))
			->from($db->quoteName('#__finder_types'));

		// Get the options.
		$db->setQuery($query);

		try
		{
			$contentTypes = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $db->getMessage());
		}

		// Translate.
		foreach ($contentTypes as $contentType)
		{
			$key = FinderHelperLanguage::branchSingular($contentType->text);
			$contentType->translatedText = $lang->hasKey($key) ? JText::_($key) : $contentType->text;
		}

		// Order by title.
		$contentTypes = ArrayHelper::sortObjects($contentTypes, 'translatedText', 1, true, true);

		// Convert the values to options.
		foreach ($contentTypes as $contentType)
		{
			$options[] = JHtml::_('select.option', $contentType->value, $contentType->translatedText);
		}

		// Merge any additional options in the XML definition.
		$options = array_merge(parent::getOptions(), $options);

		return $options;
	}
}
fields/directories.php000060400000004215152455702220011041 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

// Load the base adapter.
JLoader::register('FinderIndexerAdapter', JPATH_ADMINISTRATOR . '/components/com_finder/helpers/indexer/adapter.php');

JFormHelper::loadFieldClass('list');

/**
 * Renders a list of directories.
 *
 * @since       2.5
 * @deprecated  4.0  Use JFormFieldFolderlist
 */
class JFormFieldDirectories extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  2.5
	 */
	protected $type = 'Directories';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   2.5
	 */
	public function getOptions()
	{
		$values  = array();
		$options = array();
		$exclude = array(
			JPATH_ADMINISTRATOR,
			JPATH_INSTALLATION,
			JPATH_LIBRARIES,
			JPATH_PLUGINS,
			JPATH_SITE . '/cache',
			JPATH_SITE . '/components',
			JPATH_SITE . '/includes',
			JPATH_SITE . '/language',
			JPATH_SITE . '/modules',
			JPATH_THEMES,
			JFactory::getApplication()->get('log_path'),
			JFactory::getApplication()->get('tmp_path')
		);

		// Get the base directories.
		jimport('joomla.filesystem.folder');
		$dirs = JFolder::folders(JPATH_SITE, '.', false, true);

		// Iterate through the base directories and find the subdirectories.
		foreach ($dirs as $dir)
		{
			// Check if the directory should be excluded.
			if (in_array($dir, $exclude))
			{
				continue;
			}

			// Get the child directories.
			$return = JFolder::folders($dir, '.', true, true);

			// Merge the directories.
			if (is_array($return))
			{
				$values[] = $dir;
				$values = array_merge($values, $return);
			}
		}

		// Convert the values to options.
		foreach ($values as $value)
		{
			$options[] = JHtml::_('select.option', str_replace(JPATH_SITE . '/', '', $value), str_replace(JPATH_SITE . '/', '', $values));
		}

		// Add a null option.
		array_unshift($options, JHtml::_('select.option', '', '- ' . JText::_('JNONE') . ' -'));

		return $options;
	}
}
fields/branches.php000060400000001335152455702220010312 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('JPATH_BASE') or die();

JFormHelper::loadFieldClass('list');

/**
 * Search Branches field for the Finder package.
 *
 * @since  3.5
 */
class JFormFieldBranches extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.5
	 */
	protected $type = 'Branches';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.5
	 */
	public function getOptions()
	{
		return JHtml::_('finder.mapslist');
	}
}
maps.php000060400000024777152455702220006236 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_finder
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die();

/**
 * Maps model for the Finder package.
 *
 * @since  2.5
 */
class FinderModelMaps extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An associative array of configuration settings. [optional]
	 *
	 * @since   2.5
	 * @see     JControllerLegacy
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'state', 'a.state',
				'title', 'a.title',
				'branch',
				'branch_title', 'd.branch_title',
				'level', 'd.level',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission for the component.
	 *
	 * @since   2.5
	 */
	protected function canDelete($record)
	{
		return JFactory::getUser()->authorise('core.delete', $this->option);
	}

	/**
	 * Method to test whether a record can have its state changed.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission for the component.
	 *
	 * @since   2.5
	 */
	protected function canEditState($record)
	{
		return JFactory::getUser()->authorise('core.edit.state', $this->option);
	}

	/**
	 * Method to delete one or more records.
	 *
	 * @param   array  $pks  An array of record primary keys.
	 *
	 * @return  boolean  True if successful, false if an error occurs.
	 *
	 * @since   2.5
	 */
	public function delete(&$pks)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$pks = (array) $pks;
		$table = $this->getTable();

		// Include the content plugins for the on delete events.
		JPluginHelper::importPlugin('content');

		// Iterate the items to delete each one.
		foreach ($pks as $i => $pk)
		{
			if ($table->load($pk))
			{
				if ($this->canDelete($table))
				{
					$context = $this->option . '.' . $this->name;

					// Trigger the onContentBeforeDelete event.
					$result = $dispatcher->trigger('onContentBeforeDelete', array($context, $table));

					if (in_array(false, $result, true))
					{
						$this->setError($table->getError());

						return false;
					}

					if (!$table->delete($pk))
					{
						$this->setError($table->getError());

						return false;
					}

					// Trigger the onContentAfterDelete event.
					$dispatcher->trigger('onContentAfterDelete', array($context, $table));
				}
				else
				{
					// Prune items that you can't change.
					unset($pks[$i]);
					$error = $this->getError();

					if ($error)
					{
						$this->setError($error);
					}
					else
					{
						$this->setError(JText::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'));
					}
				}
			}
			else
			{
				$this->setError($table->getError());

				return false;
			}
		}

		// Clear the component's cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery  A JDatabaseQuery object
	 *
	 * @since   2.5
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();

		// Select all fields from the table.
		$query = $db->getQuery(true)
			->select('a.id, a.parent_id, a.title, a.state, a.access, a.ordering')
			->select('CASE WHEN a.parent_id = 1 THEN 1 ELSE 2 END AS level')
			->select('p.title AS parent_title')
			->from($db->quoteName('#__finder_taxonomy', 'a'))
			->leftJoin($db->quoteName('#__finder_taxonomy', 'p') . ' ON p.id = a.parent_id')
			->where('a.parent_id != 0');

		$childQuery = $db->getQuery(true)
			->select('parent_id')
			->select('COUNT(*) AS num_children')
			->from($db->quoteName('#__finder_taxonomy'))
			->where('parent_id != 0')
			->group('parent_id');

		// Join to get children.
		$query->select('b.num_children');
		$query->select('CASE WHEN a.parent_id = 1 THEN a.title ELSE p.title END AS branch_title');
		$query->leftJoin('(' . $childQuery . ') AS b ON b.parent_id = a.id');

		// Join to get the map links.
		$stateQuery = $db->getQuery(true)
			->select('m.node_id')
			->select('COUNT(NULLIF(l.published, 0)) AS count_published')
			->select('COUNT(NULLIF(l.published, 1)) AS count_unpublished')
			->from($db->quoteName('#__finder_taxonomy_map', 'm'))
			->leftJoin($db->quoteName('#__finder_links', 'l') . ' ON l.link_id = m.link_id')
			->group('m.node_id');

		$query->select('COALESCE(s.count_published, 0) AS count_published');
		$query->select('COALESCE(s.count_unpublished, 0) AS count_unpublished');
		$query->leftJoin('(' . $stateQuery . ') AS s ON s.node_id = a.id');

		// If the model is set to check item state, add to the query.
		$state = $this->getState('filter.state');

		if (is_numeric($state))
		{
			$query->where('a.state = ' . (int) $state);
		}

		// Filter over level.
		$level = $this->getState('filter.level');

		if (is_numeric($level) && (int) $level === 1)
		{
			$query->where('a.parent_id = 1');
		}

		// Filter the maps over the branch if set.
		$branchId = $this->getState('filter.branch');

		if (is_numeric($branchId))
		{
			$query->where('a.parent_id = ' . (int) $branchId);
		}

		// Filter the maps over the search string if set.
		if ($search = $this->getState('filter.search'))
		{
			$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
			$query->where('a.title LIKE ' . $search);
		}

		// Handle the list ordering.
		$listOrdering = $this->getState('list.ordering', 'd.branch_title');
		$listDirn     = $this->getState('list.direction', 'ASC');

		if ($listOrdering === 'd.branch_title')
		{
			$query->order("branch_title $listDirn, level ASC, a.title $listDirn");
		}
		elseif ($listOrdering === 'a.state')
		{
			$query->order("a.state $listDirn, branch_title $listDirn, level ASC");
		}

		return $query;
	}

	/**
	 * Returns a record count for the query.
	 *
	 * @param   JDatabaseQuery|string  $query  The query.
	 *
	 * @return  integer  Number of rows for query.
	 *
	 * @since   3.0
	 */
	protected function _getListCount($query)
	{
		$query = clone $query;
		$query->clear('select')->clear('join')->clear('order')->clear('limit')->clear('offset')->select('COUNT(*)');

		return (int) $this->getDbo()->setQuery($query)->loadResult();
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id. [optional]
	 *
	 * @return  string  A store id.
	 *
	 * @since   2.5
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.state');
		$id .= ':' . $this->getState('filter.branch');
		$id .= ':' . $this->getState('filter.level');

		return parent::getStoreId($id);
	}

	/**
	 * Returns a JTable object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate. [optional]
	 * @param   string  $prefix  A prefix for the table class name. [optional]
	 * @param   array   $config  Configuration array for model. [optional]
	 *
	 * @return  JTable  A database object
	 *
	 * @since   2.5
	 */
	public function getTable($type = 'Map', $prefix = 'FinderTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to auto-populate the model state.  Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field. [optional]
	 * @param   string  $direction  An optional direction. [optional]
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	protected function populateState($ordering = 'd.branch_title', $direction = 'ASC')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.state', $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'cmd'));
		$this->setState('filter.branch', $this->getUserStateFromRequest($this->context . '.filter.branch', 'filter_branch', '', 'cmd'));
		$this->setState('filter.level', $this->getUserStateFromRequest($this->context . '.filter.level', 'filter_level', '', 'cmd'));

		// Load the parameters.
		$params = JComponentHelper::getParams('com_finder');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to change the published state of one or more records.
	 *
	 * @param   array    $pks    A list of the primary keys to change.
	 * @param   integer  $value  The value of the published state. [optional]
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   2.5
	 */
	public function publish(&$pks, $value = 1)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$user = JFactory::getUser();
		$table = $this->getTable();
		$pks = (array) $pks;

		// Include the content plugins for the change of state event.
		JPluginHelper::importPlugin('content');

		// Access checks.
		foreach ($pks as $i => $pk)
		{
			$table->reset();

			if ($table->load($pk) && !$this->canEditState($table))
			{
				// Prune items that you can't change.
				unset($pks[$i]);
				$this->setError(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));

				return false;
			}
		}

		// Attempt to change the state of the records.
		if (!$table->publish($pks, $value, $user->get('id')))
		{
			$this->setError($table->getError());

			return false;
		}

		$context = $this->option . '.' . $this->name;

		// Trigger the onContentChangeState event.
		$result = $dispatcher->trigger('onContentChangeState', array($context, $pks, $value));

		if (in_array(false, $result, true))
		{
			$this->setError($table->getError());

			return false;
		}

		// Clear the component's cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to purge all maps from the taxonomy.
	 *
	 * @return  boolean  Returns true on success, false on failure.
	 *
	 * @since   2.5
	 */
	public function purge()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__finder_taxonomy'))
			->where($db->quoteName('parent_id') . ' > 1');
		$db->setQuery($query);
		$db->execute();

		$query->clear()
			->delete($db->quoteName('#__finder_taxonomy_map'));
		$db->setQuery($query);
		$db->execute();

		return true;
	}
}
forms/filter.xml000060400000007152152455702220007706 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field 
			name="filter_id"  
			type="text" 
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC" 
			class="readonly" 
			size="10" 
			default="0"
			readonly="true"  
		/>

		<field 
			name="title" 
			type="text" 
			label="JGLOBAL_TITLE"
			description="COM_FINDER_FILTER_TITLE_DESCRIPTION"
			class="input-xxlarge input-large-text"
			size="40"
			id="title"
			required="true" 
		/>

		<field 
			name="alias" 
			type="text" 
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			hint="JFIELD_ALIAS_PLACEHOLDER" 
			size="45" 
		/>

		<field
			name="created"
			type="calendar"
			label="JGLOBAL_FIELD_CREATED_LABEL"
			description="JGLOBAL_FIELD_CREATED_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="modified"
			type="calendar"
			label="JGLOBAL_FIELD_MODIFIED_LABEL"
			description="COM_FINDER_FIELD_MODIFIED_DESCRIPTION"
			class="readonly"
			translateformat="true"
			showtime="true"
			size="22"
			readonly="true"
			filter="user_utc"
		/>

		<field 
			name="created_by" 
			type="user"
			label="COM_FINDER_FIELD_CREATED_BY_LABEL" 
			description="COM_FINDER_FIELD_CREATED_BY_DESC" 
		/>

		<field 
			name="created_by_alias" 
			type="text"
			label="COM_FINDER_FIELD_CREATED_BY_ALIAS_LABEL" 
			description="COM_FINDER_FIELD_CREATED_BY_ALIAS_DESC"
			size="20" 
		/>
		
		<field 
			name="modified_by" 
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			class="readonly"
			readonly="true"
			filter="unset"
		 />

		<field 
			name="checked_out" 
			type="hidden" 
			filter="unset" 
		/>

		<field 
			name="checked_out_time" 
			type="hidden" 
			filter="unset" 
		/>

		<field 
			name="state" 
			type="list" 
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			class="chzn-color-state"
			filter="intval"
			size="1"
			default="1" 
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
		</field>

		<field
			name="map_count" 
			type="text" 
			label="COM_FINDER_FILTER_MAP_COUNT" 
			description="COM_FINDER_FILTER_MAP_COUNT_DESCRIPTION"
			class="readonly"
			size="10" 
			default="0" 
			readonly="true" 
		/>
	</fieldset>

	<fields name="params">
		<fieldset name="jbasic" label="COM_FINDER_FILTER_FIELDSET_PARAMS">
			<field
				name="w1"
				type="list"
				label="COM_FINDER_FILTER_WHEN_START_DATE_LABEL"
				description="COM_FINDER_FILTER_WHEN_START_DATE_DESCRIPTION"
				default=""
				filter="string"
				>
				<option value="">JNONE</option>
				<option value="-1">COM_FINDER_FILTER_WHEN_BEFORE</option>
				<option value="0">COM_FINDER_FILTER_WHEN_EXACTLY</option>
				<option value="1">COM_FINDER_FILTER_WHEN_AFTER</option>
			</field>

			<field 
				name="d1"
				type="calendar"
				label="COM_FINDER_FILTER_START_DATE_LABEL"
				description="COM_FINDER_FILTER_START_DATE_DESCRIPTION"
				translateformat="true"
				size="22"
				filter="user_utc"
			/>

			<field
				name="w2"
				type="list"
				label="COM_FINDER_FILTER_WHEN_END_DATE_LABEL"
				description="COM_FINDER_FILTER_WHEN_END_DATE_DESCRIPTION"
				default=""
				filter="string"
				>
				<option value="">JNONE</option>
				<option value="-1">COM_FINDER_FILTER_WHEN_BEFORE</option>
				<option value="0">COM_FINDER_FILTER_WHEN_EXACTLY</option>
				<option value="1">COM_FINDER_FILTER_WHEN_AFTER</option>
			</field>

			<field
				name="d2"
				type="calendar"
				label="COM_FINDER_FILTER_END_DATE_LABEL"
				description="COM_FINDER_FILTER_END_DATE_DESCRIPTION"
				translateformat="true"
				size="22"
				filter="user_utc"
			/>
		</fieldset>

	</fields>
</form>
forms/filter_maps.xml000060400000002737152455702220010732 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_FINDER_SEARCH_SEARCH_QUERY_LABEL"
			description="COM_FINDER_SEARCH_SEARCH_QUERY_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="state"
			type="status"
			label="COM_FINDER_FILTER_PUBLISHED"
			description="COM_FINDER_FILTER_PUBLISHED_DESC"
			filter="0,1"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="branch"
			type="branches"
			default="0"
			onchange="this.form.submit();"
		/>

		<field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="2"
			step="1"
			languages="*"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
		</field>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			onchange="this.form.submit();"
			default="d.branch_title ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="d.branch_title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="d.branch_title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="a.state ASC">JSTATUS_ASC</option>
			<option value="a.state DESC">JSTATUS_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_index.xml000060400000004050152455702220011067 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_FINDER_INDEX_SEARCH_LABEL"
			description="COM_FINDER_INDEX_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="state"
			type="status"
			label="COM_FINDER_FILTER_PUBLISHED"
			description="COM_FINDER_FILTER_PUBLISHED_DESC"
			filter="0,1"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="type"
			type="ContentTypes"
			label="JOPTION_FILTER_CATEGORY"
			description="JOPTION_FILTER_CATEGORY_DESC"
			onchange="this.form.submit();"
			>
			<option value="">COM_FINDER_MAPS_SELECT_TYPE</option>
		</field>

		<field
			name="content_map"
			type="ContentMap"
			label="COM_FINDER_FILTER_CONTENT_MAP_LABEL"
			description="COM_FINDER_FILTER_CONTENT_MAP_DESC"
			onchange="this.form.submit();"
			>
			<option value="">COM_FINDER_FILTER_SELECT_CONTENT_MAP</option>
		</field>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			onchange="this.form.submit();"
			default="l.title ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="l.published ASC">JSTATUS_ASC</option>
			<option value="l.published DESC">JSTATUS_DESC</option>
			<option value="l.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="l.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="t.title ASC">COM_FINDER_INDEX_HEADING_INDEX_TYPE_ASC</option>
			<option value="t.title DESC">COM_FINDER_INDEX_HEADING_INDEX_TYPE_DESC</option>
			<option value="l.indexdate ASC">COM_FINDER_INDEX_HEADING_INDEX_DATE_ASC</option>
			<option value="l.indexdate DESC">COM_FINDER_INDEX_HEADING_INDEX_DATE_DESC</option>
			<option value="l.url ASC">COM_FINDER_INDEX_HEADING_LINK_URL_ASC</option>
			<option value="l.url DESC">COM_FINDER_INDEX_HEADING_LINK_URL_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_filters.xml000060400000003270152455702220011433 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_FINDER_SEARCH_FILTER_SEARCH_LABEL"
			description="COM_FINDER_SEARCH_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="state"
			type="status"
			label="COM_FINDER_FILTER_PUBLISHED"
			description="COM_FINDER_FILTER_PUBLISHED_DESC"
			filter="0,1"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			onchange="this.form.submit();"
			default="a.title ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.state ASC">JSTATUS_ASC</option>
			<option value="a.state DESC">JSTATUS_DESC</option>
			<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="a.created_by_alias ASC">COM_FINDER_HEADING_CREATED_BY_ASC</option>
			<option value="a.created_by_alias DESC">COM_FINDER_HEADING_CREATED_BY_DESC</option>
			<option value="a.created ASC">COM_FINDER_HEADING_CREATED_ON_ASC</option>
			<option value="a.created DESC">COM_FINDER_HEADING_CREATED_ON_DESC</option>
			<option value="a.map_count ASC">COM_FINDER_HEADING_MAP_COUNT_ASC</option>
			<option value="a.map_count DESC">COM_FINDER_HEADING_MAP_COUNT_DESC</option>
			<option value="a.filter_id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.filter_id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_tags.xml000060400000005341152455702310010722 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_TAGS_FILTER_SEARCH_LABEL"
			description="COM_TAGS_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>
		<field
			name="published"
			type="status"
			label="COM_TAGS_FILTER_PUBLISHED"
			description="COM_TAGS_FILTER_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>
		<field
			name="access"
			type="accesslevel"
			label="JOPTION_FILTER_ACCESS"
			description="JOPTION_FILTER_ACCESS_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_ACCESS</option>
		</field>
		<field
			name="language"
			type="contentlanguage"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>
        <field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="10"
			step="1"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
        </field>
		<field
			name="extension"
			type="aliastag"
			label="COM_TAGS_FILTER_ALIASTYPE_LABEL"
			description="COM_TAGS_FIELD_ALIASTYPE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">COM_TAGS_SELECT_TAGTYPE</option>
		</field>
	</fields>
	<fields name="list">
		<field
            name="fullordering"
			type="list"
			label="COM_TAGS_LIST_FULL_ORDERING"
			description="COM_TAGS_LIST_FULL_ORDERING_DESC"
			onchange="this.form.submit();"
			default="a.lft ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.lft ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.lft DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.published ASC">JSTATUS_ASC</option>
			<option value="a.published DESC">JSTATUS_DESC</option>
			<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="a.access ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="a.access DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option value="a.language ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="a.language DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="COM_TAGS_LIST_LIMIT"
			description="COM_TAGS_LIST_LIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/tag.xml000060400000016201152455702310007167 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<field
		name="id"
		type="number"
		label="JGLOBAL_FIELD_ID_LABEL"
		description="JGLOBAL_FIELD_ID_DESC"
		default="0"
		class="readonly"
		readonly="true"
	/>

	<field
		name="hits"
		type="number"
		label="JGLOBAL_HITS"
		description="COM_TAGS_FIELD_HITS_DESC"
		class="readonly"
		default="0"
		readonly="true"
		filter="unset"
	/>

	<field
		name="parent_id"
		type="tag"
		label="COM_TAGS_FIELD_PARENT_LABEL"
		description="COM_TAGS_FIELD_PARENT_DESC"
		mode="nested"
		validate="notequals"
		field="id"
		parent="parent"
		>
		<option value="1">JNONE</option>
	</field>

	<field
		name="lft"
		type="hidden"
		filter="unset"
	/>

	<field
		name="rgt"
		type="hidden"
		filter="unset"
	/>

	<field
		name="level"
		type="hidden"
		filter="unset"
	/>

	<field
		name="path"
		type="text"
		label="CATEGORIES_PATH_LABEL"
		description="CATEGORIES_PATH_DESC"
		class="readonly"
		size="40"
		readonly="true"
	/>

	<field
		name="title"
		type="text"
		label="JGLOBAL_TITLE"
		description="JFIELD_TITLE_DESC"
		class="input-xxlarge input-large-text"
		size="40"
		required="true"
	/>

	<field
		name="note"
		type="text"
		label="COM_TAGS_FIELD_NOTE_LABEL"
		description="COM_TAGS_FIELD_NOTE_DESC"
		maxlength="255"
		class="span12"
		size="40"
	/>

	<field
		name="description"
		type="editor"
		label="JGLOBAL_DESCRIPTION"
		description="COM_TAGS_DESCRIPTION_DESC"
		filter="JComponentHelper::filterText"
		buttons="true"
		hide="readmore,pagebreak"
	/>

	<field
		name="published"
		type="list"
		label="JSTATUS"
		description="JFIELD_PUBLISHED_DESC"
		class="chzn-color-state"
		default="1"
		size="1"
		>
		<option value="1">JPUBLISHED</option>
		<option value="0">JUNPUBLISHED</option>
		<option value="2">JARCHIVED</option>
		<option value="-2">JTRASHED</option>
	</field>

	<field
		name="checked_out"
		type="hidden"
		filter="unset"
	/>

	<field
		name="checked_out_time"
		type="hidden"
		filter="unset"
	/>

	<field
		name="access"
		type="accesslevel"
		label="JFIELD_ACCESS_LABEL"
		description="JFIELD_ACCESS_DESC"
	/>

	<field
		name="metadesc"
		type="textarea"
		label="JFIELD_META_DESCRIPTION_LABEL"
		description="JFIELD_META_DESCRIPTION_DESC"
		rows="3"
		cols="40"
	/>

	<field
		name="metakey"
		type="textarea"
		label="JFIELD_META_KEYWORDS_LABEL"
		description="JFIELD_META_KEYWORDS_DESC"
		rows="3"
		cols="40"
	/>

	<field
		name="alias"
		type="text"
		label="JFIELD_ALIAS_LABEL"
		description="JFIELD_ALIAS_DESC"
		hint="JFIELD_ALIAS_PLACEHOLDER"
		size="40"
	/>

	<field
		name="created_user_id"
		type="user"
		label="JGLOBAL_FIELD_CREATED_BY_LABEL"
		description="JGLOBAL_FIELD_CREATED_BY_DESC"
	/>

	<field
		name="created_by_alias"
		type="text"
		label="JGLOBAL_FIELD_CREATED_BY_ALIAS_LABEL"
		description="JGLOBAL_FIELD_CREATED_BY_ALIAS_DESC"
		labelclass="control-label"
		size="20"
	/>

	<field
		name="created_time"
		type="calendar"
		label="JGLOBAL_CREATED_DATE"
		description="COM_TAGS_FIELD_CREATED_DATE_DESC"
		class="readonly"
		translateformat="true"
		showtime="true"
		filter="user_utc"
		readonly="true"
	/>

	<field
		name="modified_user_id"
		type="user"
		label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
		class="readonly"
		readonly="true"
		filter="unset"
	/>

	<field
		name="modified_time"
		type="calendar"
		label="JGLOBAL_FIELD_MODIFIED_LABEL"
		description="COM_TAGS_FIELD_MODIFIED_DESC"
		class="readonly"
		translateformat="true"
		showtime="true"
		filter="user_utc"
		readonly="true"
	/>

	<field
		name="language"
		type="contentlanguage"
		label="JFIELD_LANGUAGE_LABEL"
		description="COM_TAGS_FIELD_LANGUAGE_DESC"
		>
		<option value="*">JALL</option>
	</field>

	<field
		name="version_note"
		type="text"
		label="JGLOBAL_FIELD_VERSION_NOTE_LABEL"
		description="JGLOBAL_FIELD_VERSION_NOTE_DESC"
		maxlength="255"
		class="span12" size="45"
		labelclass="control-label"
	/>

	<fields name="params" label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS">
		<fieldset
			name="basic"
			label="COM_TAGS_BASIC_FIELDSET_LABEL"
		>

			<field
				name="tag_layout"
				type="componentlayout"
				label="JFIELD_ALT_LAYOUT_LABEL"
				description="JFIELD_ALT_COMPONENT_LAYOUT_DESC"
				labelclass="control-label"
				useglobal="true"
				extension="com_tags"
				view="tag"
			/>

			<field
				name="tag_link_class"
				type="text"
				label="COM_TAGS_FIELD_TAG_LINK_CLASS"
				description="COM_TAGS_FIELD_TAG_LINK_CLASS_DESC"
				labelclass="control-label"
				size="20"
				default="label label-info"
			/>

		</fieldset>
	</fields>

	<fields name="images">
		<fieldset name="images" label="JGLOBAL_FIELDSET_IMAGE_OPTIONS">
			<field
				name="image_intro"
				type="media"
				label="COM_TAGS_FIELD_INTRO_LABEL"
				description="COM_TAGS_FIELD_INTRO_DESC"
				labelclass="control-label"
			/>

			<field
				name="float_intro"
				type="list"
				label="COM_TAGS_FLOAT_LABEL"
				description="COM_TAGS_FLOAT_DESC"
				labelclass="control-label"
				>
				<option value="">JGLOBAL_SELECT_AN_OPTION</option>
				<option value="right">COM_TAGS_RIGHT</option>
				<option value="left">COM_TAGS_LEFT</option>
				<option value="none">COM_TAGS_NONE</option>
			</field>

			<field
				name="image_intro_alt"
				type="text"
				label="COM_TAGS_FIELD_IMAGE_ALT_LABEL"
				description="COM_TAGS_FIELD_IMAGE_ALT_DESC"
				labelclass="control-label"
				size="20"
			/>

			<field
				name="image_intro_caption"
				type="text"
				label="COM_TAGS_FIELD_IMAGE_CAPTION_LABEL"
				description="COM_TAGS_FIELD_IMAGE_CAPTION_DESC"
				size="20"
				labelclass="control-label"
			/>

			<field
				name="spacer1"
				type="spacer"
				hr="true"
			/>

			<field
				name="image_fulltext"
				type="media"
				label="COM_TAGS_FIELD_FULL_LABEL"
				description="COM_TAGS_FIELD_FULL_DESC"
				labelclass="control-label"
			/>

			<field
				name="float_fulltext"
				type="list"
				label="COM_TAGS_FLOAT_LABEL"
				description="COM_TAGS_FLOAT_DESC"
				labelclass="control-label"
				>
				<option value="">JGLOBAL_SELECT_AN_OPTION</option>
				<option value="right">COM_TAGS_RIGHT</option>
				<option value="left">COM_TAGS_LEFT</option>
				<option value="none">COM_TAGS_NONE</option>
			</field>

			<field
				name="image_fulltext_alt"
				type="text"
				label="COM_TAGS_FIELD_IMAGE_ALT_LABEL"
				description="COM_TAGS_FIELD_IMAGE_ALT_DESC"
				labelclass="control-label"
				size="20"
			/>

			<field
				name="image_fulltext_caption"
				type="text"
				label="COM_TAGS_FIELD_IMAGE_CAPTION_LABEL"
				description="COM_TAGS_FIELD_IMAGE_CAPTION_DESC"
				labelclass="control-label"
				size="20"
			/>
		</fieldset>
	</fields>

	<fields name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">
		<fieldset name="jmetadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">

			<field
				name="author"
				type="text"
				label="JAUTHOR"
				description="JFIELD_METADATA_AUTHOR_DESC"
				size="30"
			/>

			<field
				name="robots"
				type="list"
				label="JFIELD_METADATA_ROBOTS_LABEL"
				description="JFIELD_METADATA_ROBOTS_DESC"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="index, follow"></option>
				<option value="noindex, follow"></option>
				<option value="index, nofollow"></option>
				<option value="noindex, nofollow"></option>
			</field>
		</fieldset>
	</fields>
</form>
searches.php000060400000010650152455702320007055 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_search
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Methods supporting a list of search terms.
 *
 * @since  1.6
 */
class SearchModelSearches extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'search_term', 'a.search_term',
				'hits', 'a.hits',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.hits', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));

		// Special state for toggle results button.
		$this->setState('show_results', $this->getUserStateFromRequest($this->context . '.show_results', 'show_results', 1, 'int'));

		// Load the parameters.
		$params = JComponentHelper::getParams('com_search');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('show_results');
		$id .= ':' . $this->getState('filter.search');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.*'
			)
		);
		$query->from($db->quoteName('#__core_log_searches', 'a'));

		// Filter by search in title
		if ($search = $this->getState('filter.search'))
		{
			$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
			$query->where($db->quoteName('a.search_term') . ' LIKE ' . $search);
		}

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'a.hits')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}

	/**
	 * Override the parent getItems to inject optional data.
	 *
	 * @return  mixed  An array of objects on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function getItems()
	{
		$items = parent::getItems();

		// Determine if number of results for search item should be calculated
		// by default it is `off` as it is highly query intensive
		if ($this->getState('show_results'))
		{
			JPluginHelper::importPlugin('search');
			$app = JFactory::getApplication();

			if (!class_exists('JSite'))
			{
				// This fools the routers in the search plugins into thinking it's in the frontend
				JLoader::register('JSite', JPATH_ADMINISTRATOR . '/components/com_search/helpers/site.php');
			}

			foreach ($items as &$item)
			{
				$results = $app->triggerEvent('onContentSearch', array($item->search_term));
				$item->returns = 0;

				foreach ($results as $result)
				{
					$item->returns += count($result);
				}
			}
		}

		return $items;
	}

	/**
	 * Method to reset the search log table.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	public function reset()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__core_log_searches'));
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		return true;
	}
}
forms/filter_searches.xml000060400000001566152455702320011567 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_SEARCH_SEARCH_IN_PHRASE"
			description="COM_SEARCH_SEARCH_IN_PHRASE"
			hint="JSEARCH_FILTER"
		/>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			onchange="this.form.submit();"
			default="a.hits ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.search_term ASC">COM_SEARCH_HEADING_SEARCH_TERM_ASC</option>
			<option value="a.search_term DESC">COM_SEARCH_HEADING_SEARCH_TERM_DESC</option>
			<option value="a.hits ASC">JGLOBAL_HITS_ASC</option>
			<option value="a.hits DESC">JGLOBAL_HITS_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
default.php000060400000142237152455702320006713 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_joomlaupdate
 *
 * @copyright   (C) 2012 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Extension\ExtensionHelper;
use Joomla\CMS\Filter\InputFilter;
use Joomla\CMS\Http\HttpFactory;
use Joomla\Registry\Registry;

jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');

/**
 * Joomla! update overview Model
 *
 * @since  2.5.4
 */
class JoomlaupdateModelDefault extends JModelLegacy
{
	/**
	 * @var   array  $updateInformation  null
	 * Holds the update information evaluated in getUpdateInformation.
	 *
	 * @since 3.10.0
	 */
	private $updateInformation = null;

	/**
	 * Detects if the Joomla! update site currently in use matches the one
	 * configured in this component. If they don't match, it changes it.
	 *
	 * @return  void
	 *
	 * @since    2.5.4
	 */
	public function applyUpdateSite()
	{
		// Determine the intended update URL.
		$params = JComponentHelper::getParams('com_joomlaupdate');

		switch ($params->get('updatesource', 'nochange'))
		{
			// "Minor & Patch Release for Current version AND Next Major Release".
			case 'next':
				$updateURL = 'https://update.joomla.org/core/sts/list_sts.xml';
				break;

			// "Testing"
			case 'testing':
				$updateURL = 'https://update.joomla.org/core/test/list_test.xml';
				break;

			// "Custom"
			// TODO: check if the customurl is valid and not just "not empty".
			case 'custom':
				if (trim($params->get('customurl', '')) != '')
				{
					$updateURL = trim($params->get('customurl', ''));
				}
				else
				{
					return JError::raiseWarning(403, JText::_('COM_JOOMLAUPDATE_CONFIG_UPDATESOURCE_CUSTOM_ERROR'));
				}
				break;

			/**
			 * "Minor & Patch Release for Current version (recommended and default)".
			 * The commented "case" below are for documenting where 'default' and legacy options falls
			 * case 'default':
			 * case 'lts':
			 * case 'sts': (It's shown as "Default" because that option does not exist any more)
			 * case 'nochange':
			 */
			default:
				$updateURL = 'https://update.joomla.org/core/list.xml';
		}

		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select($db->quoteName('us') . '.*')
			->from($db->quoteName('#__update_sites_extensions') . ' AS ' . $db->quoteName('map'))
			->join(
				'INNER', $db->quoteName('#__update_sites') . ' AS ' . $db->quoteName('us')
				. ' ON (' . 'us.update_site_id = map.update_site_id)'
			)
			->where('map.extension_id = ' . $db->quote(700));
		$db->setQuery($query);
		$update_site = $db->loadObject();

		if ($update_site->location != $updateURL)
		{
			// Modify the database record.
			$update_site->last_check_timestamp = 0;
			$update_site->location = $updateURL;
			$db->updateObject('#__update_sites', $update_site, 'update_site_id');

			// Remove cached updates.
			$query->clear()
				->delete($db->quoteName('#__updates'))
				->where($db->quoteName('extension_id') . ' = ' . $db->quote('700'));
			$db->setQuery($query);
			$db->execute();
		}
	}

	/**
	 * Makes sure that the Joomla! update cache is up-to-date.
	 *
	 * @param   boolean  $force  Force reload, ignoring the cache timeout.
	 *
	 * @return  void
	 *
	 * @since    2.5.4
	 */
	public function refreshUpdates($force = false)
	{
		if ($force)
		{
			$cache_timeout = 0;
		}
		else
		{
			$cache_timeout = 3600 * JComponentHelper::getParams('com_installer')->get('cachetimeout', 6, 'int');
		}

		$updater               = JUpdater::getInstance();
		$minimumStability      = JUpdater::STABILITY_STABLE;
		$comJoomlaupdateParams = JComponentHelper::getParams('com_joomlaupdate');

		if (in_array($comJoomlaupdateParams->get('updatesource', 'nochange'), array('testing', 'custom')))
		{
			$minimumStability = $comJoomlaupdateParams->get('minimum_stability', JUpdater::STABILITY_STABLE);
		}

		$reflection = new ReflectionObject($updater);
		$reflectionMethod = $reflection->getMethod('findUpdates');
		$methodParameters = $reflectionMethod->getParameters();

		if (count($methodParameters) >= 4)
		{
			// Reinstall support is available in JUpdater
			$updater->findUpdates(700, $cache_timeout, $minimumStability, true);
		}
		else
		{
			$updater->findUpdates(700, $cache_timeout, $minimumStability);
		}
	}

	/**
	 * Returns an array with the Joomla! update information.
	 *
	 * @return  array
	 *
	 * @since   2.5.4
	 */
	public function getUpdateInformation()
	{
		if ($this->updateInformation)
		{
			return $this->updateInformation;
		}

		// Initialise the return array.
		$this->updateInformation = array(
			'installed' => JVERSION,
			'latest'    => null,
			'object'    => null,
			'hasUpdate' => false,
			'current'   => JVERSION, // This is deprecated please use 'installed' or JVERSION directly
		);

		// Fetch the update information from the database.
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('*')
			->from($db->quoteName('#__updates'))
			->where($db->quoteName('extension_id') . ' = ' . $db->quote(700));
		$db->setQuery($query);
		$updateObject = $db->loadObject();

		if (is_null($updateObject))
		{
			$this->updateInformation['latest'] = JVERSION;

			return $this->updateInformation;
		}

		// Check whether this is a valid update or not
		if (version_compare($updateObject->version, JVERSION, '<'))
		{
			// This update points to an outdated version we should not offer to update to this
			$this->updateInformation['latest'] = JVERSION;

			return $this->updateInformation;
		}

		$minimumStability      = JUpdater::STABILITY_STABLE;
		$comJoomlaupdateParams = JComponentHelper::getParams('com_joomlaupdate');

		if (in_array($comJoomlaupdateParams->get('updatesource', 'nochange'), array('testing', 'custom')))
		{
			$minimumStability = $comJoomlaupdateParams->get('minimum_stability', JUpdater::STABILITY_STABLE);
		}

		// Fetch the full update details from the update details URL.
		jimport('joomla.updater.update');
		$update = new JUpdate;
		$update->loadFromXML($updateObject->detailsurl, $minimumStability);

		// Make sure we use the current information we got from the detailsurl
		$this->updateInformation['object'] = $update;
		$this->updateInformation['latest'] = $updateObject->version;

		// Check whether we have got an update from the detailsurl or not.
		if (version_compare($this->updateInformation['latest'], JVERSION, '>'))
		{
			$this->updateInformation['hasUpdate'] = true;
		}

		return $this->updateInformation;
	}

	/**
	 * Returns an array with the configured FTP options.
	 *
	 * @return  array
	 *
	 * @since   2.5.4
	 */
	public function getFTPOptions()
	{
		$config = JFactory::getConfig();

		return array(
			'host'      => $config->get('ftp_host'),
			'port'      => $config->get('ftp_port'),
			'username'  => $config->get('ftp_user'),
			'password'  => $config->get('ftp_pass'),
			'directory' => $config->get('ftp_root'),
			'enabled'   => $config->get('ftp_enable'),
		);
	}

	/**
	 * Removes all of the updates from the table and enable all update streams.
	 *
	 * @return  boolean  Result of operation.
	 *
	 * @since   3.0
	 */
	public function purge()
	{
		$db = $this->getDbo();

		// Reset the last update check timestamp
		$query = $db->getQuery(true)
			->update($db->quoteName('#__update_sites'))
			->set($db->quoteName('last_check_timestamp') . ' = 0');
		$db->setQuery($query);
		$db->execute();

		// We should delete all core updates here
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__updates'))
			->where($db->quoteName('element') . ' = ' . $db->quote('joomla'))
			->where($db->quoteName('type') . ' = ' . $db->quote('file'));
		$db->setQuery($query);

		if ($db->execute())
		{
			$this->_message = JText::_('COM_JOOMLAUPDATE_CHECKED_UPDATES');

			return true;
		}
		else
		{
			$this->_message = JText::_('COM_JOOMLAUPDATE_FAILED_TO_CHECK_UPDATES');

			return false;
		}
	}

	/**
	 * Downloads the update package to the site.
	 *
	 * @return  boolean|string  False on failure, basename of the file in any other case.
	 *
	 * @since   2.5.4
	 */
	public function download()
	{
		$updateInfo = $this->getUpdateInformation();
		$packageURL = trim($updateInfo['object']->downloadurl->_data);
		$sources    = $updateInfo['object']->get('downloadSources', array());

		// We have to manually follow the redirects here so we set the option to false.
		$httpOptions = new Registry;
		$httpOptions->set('follow_location', false);

		try
		{
			$head = HttpFactory::getHttp($httpOptions)->head($packageURL);
		}
		catch (RuntimeException $e)
		{
			// Passing false here -> download failed message
			$response['basename'] = false;

			return $response;
		}

		// Follow the Location headers until the actual download URL is known
		while (isset($head->headers['location']))
		{
			$packageURL = $head->headers['location'];

			try
			{
				$head = HttpFactory::getHttp($httpOptions)->head($packageURL);
			}
			catch (RuntimeException $e)
			{
				// Passing false here -> download failed message
				$response['basename'] = false;

				return $response;
			}
		}

		// Remove protocol, path and query string from URL
		$basename = basename($packageURL);

		if (strpos($basename, '?') !== false)
		{
			$basename = substr($basename, 0, strpos($basename, '?'));
		}

		// Find the path to the temp directory and the local package.
		$config   = JFactory::getConfig();
		$tempdir  = (string) InputFilter::getInstance(array(), array(), 1, 1)->clean($config->get('tmp_path'), 'path');
		$target   = $tempdir . '/' . $basename;
		$response = array();

		// Do we have a cached file?
		$exists = JFile::exists($target);

		if (!$exists)
		{
			// Not there, let's fetch it.
			$mirror = 0;

			while (!($download = $this->downloadPackage($packageURL, $target)) && isset($sources[$mirror]))
			{
				$name       = $sources[$mirror];
				$packageURL = trim($name->url);
				$mirror++;
			}

			$response['basename'] = $download;
		}
		else
		{
			// Is it a 0-byte file? If so, re-download please.
			$filesize = @filesize($target);

			if (empty($filesize))
			{
				$mirror = 0;

				while (!($download = $this->downloadPackage($packageURL, $target)) && isset($sources[$mirror]))
				{
					$name       = $sources[$mirror];
					$packageURL = trim($name->url);
					$mirror++;
				}

				$response['basename'] = $download;
			}

			// Yes, it's there, skip downloading.
			$response['basename'] = $basename;
		}

		$response['check'] = $this->isChecksumValid($target, $updateInfo['object']);

		return $response;
	}

	/**
	 * Return the result of the checksum of a package with the SHA256/SHA384/SHA512 tags in the update server manifest
	 *
	 * @param   string   $packagefile   Location of the package to be installed
	 * @param   JUpdate  $updateObject  The Update Object
	 *
	 * @return  boolean  False in case the validation did not work; true in any other case.
	 *
	 * @note    This method has been forked from (JInstallerHelper::isChecksumValid) so it
	 *          does not depend on an up-to-date InstallerHelper at the update time
	 *
	 * @since   3.9.0
	 */
	private function isChecksumValid($packagefile, $updateObject)
	{
		$hashes = array('sha256', 'sha384', 'sha512');

		foreach ($hashes as $hash)
		{
			if ($updateObject->get($hash, false))
			{
				$hashPackage = hash_file($hash, $packagefile);
				$hashRemote  = $updateObject->$hash->_data;

				if ($hashPackage !== $hashRemote)
				{
					// Return false in case the hash did not match
					return false;
				}
			}
		}

		// Well nothing was provided or all worked
		return true;
	}

	/**
	 * Downloads a package file to a specific directory
	 *
	 * @param   string  $url     The URL to download from
	 * @param   string  $target  The directory to store the file
	 *
	 * @return  boolean True on success
	 *
	 * @since   2.5.4
	 */
	protected function downloadPackage($url, $target)
	{
		JLoader::import('helpers.download', JPATH_COMPONENT_ADMINISTRATOR);

		try
		{
			JLog::add(JText::sprintf('COM_JOOMLAUPDATE_UPDATE_LOG_URL', $url), JLog::INFO, 'Update');
		}
		catch (RuntimeException $exception)
		{
			// Informational log only
		}

		// Get the handler to download the package
		try
		{
			$http = JHttpFactory::getHttp(null, array('curl', 'stream'));
		}
		catch (RuntimeException $e)
		{
			return false;
		}

		jimport('joomla.filesystem.file');

		// Make sure the target does not exist.
		JFile::delete($target);

		// Download the package
		try
		{
			$result = $http->get($url);
		}
		catch (RuntimeException $e)
		{
			return false;
		}

		if (!$result || ($result->code != 200 && $result->code != 310))
		{
			return false;
		}

		// Write the file to disk
		JFile::write($target, $result->body);

		return basename($target);
	}

	/**
	 * Create restoration file.
	 *
	 * @param   string  $basename  Optional base path to the file.
	 *
	 * @return  boolean True if successful; false otherwise.
	 *
	 * @since  2.5.4
	 */
	public function createRestorationFile($basename = null)
	{
		// Get a password
		$password = JUserHelper::genRandomPassword(32);
		$app = JFactory::getApplication();
		$app->setUserState('com_joomlaupdate.password', $password);

		// Do we have to use FTP?
		$method = JFactory::getApplication()->getUserStateFromRequest('com_joomlaupdate.method', 'method', 'direct', 'cmd');

		// Get the absolute path to site's root.
		$siteroot = JPATH_SITE;

		// If the package name is not specified, get it from the update info.
		if (empty($basename))
		{
			$updateInfo = $this->getUpdateInformation();
			$packageURL = $updateInfo['object']->downloadurl->_data;
			$basename = basename($packageURL);
		}

		// Get the package name.
		$config  = JFactory::getConfig();
		$tempdir = $config->get('tmp_path');
		$file    = $tempdir . '/' . $basename;

		$filesize = @filesize($file);
		$app->setUserState('com_joomlaupdate.password', $password);
		$app->setUserState('com_joomlaupdate.filesize', $filesize);

		$data = "<?php\ndefined('_AKEEBA_RESTORATION') or die('Restricted access');\n";
		$data .= '$restoration_setup = array(' . "\n";
		$data .= <<<ENDDATA
	'kickstart.security.password' => '$password',
	'kickstart.tuning.max_exec_time' => '5',
	'kickstart.tuning.run_time_bias' => '75',
	'kickstart.tuning.min_exec_time' => '0',
	'kickstart.procengine' => '$method',
	'kickstart.setup.sourcefile' => '$file',
	'kickstart.setup.destdir' => '$siteroot',
	'kickstart.setup.restoreperms' => '0',
	'kickstart.setup.filetype' => 'zip',
	'kickstart.setup.dryrun' => '0',
	'kickstart.setup.renamefiles' => array(),
	'kickstart.setup.postrenamefiles' => false
ENDDATA;

		if ($method != 'direct')
		{
			/*
			 * Fetch the FTP parameters from the request. Note: The password should be
			 * allowed as raw mode, otherwise something like !@<sdf34>43H% would be
			 * sanitised to !@43H% which is just plain wrong.
			 */
			$ftp_host = $app->input->get('ftp_host', '');
			$ftp_port = $app->input->get('ftp_port', '21');
			$ftp_user = $app->input->get('ftp_user', '');
			$ftp_pass = addcslashes($app->input->get('ftp_pass', '', 'raw'), "'\\");
			$ftp_root = $app->input->get('ftp_root', '');

			// Is the tempdir really writable?
			$writable = @is_writeable($tempdir);

			if ($writable)
			{
				// Let's be REALLY sure.
				$fp = @fopen($tempdir . '/test.txt', 'w');

				if ($fp === false)
				{
					$writable = false;
				}
				else
				{
					fclose($fp);
					unlink($tempdir . '/test.txt');
				}
			}

			// If the tempdir is not writable, create a new writable subdirectory.
			if (!$writable)
			{
				$FTPOptions = JClientHelper::getCredentials('ftp');
				$ftp = JClientFtp::getInstance($FTPOptions['host'], $FTPOptions['port'], array(), $FTPOptions['user'], $FTPOptions['pass']);
				$dest = JPath::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $tempdir . '/admintools'), '/');

				if (!@mkdir($tempdir . '/admintools'))
				{
					$ftp->mkdir($dest);
				}

				if (!@chmod($tempdir . '/admintools', 511))
				{
					$ftp->chmod($dest, 511);
				}

				$tempdir .= '/admintools';
			}

			// Just in case the temp-directory was off-root, try using the default tmp directory.
			$writable = @is_writeable($tempdir);

			if (!$writable)
			{
				$tempdir = JPATH_ROOT . '/tmp';

				// Does the JPATH_ROOT/tmp directory exist?
				if (!is_dir($tempdir))
				{
					JFolder::create($tempdir, 511);
					$htaccessContents = "order deny,allow\ndeny from all\nallow from none\n";
					JFile::write($tempdir . '/.htaccess', $htaccessContents);
				}

				// If it exists and it is unwritable, try creating a writable admintools subdirectory.
				if (!is_writable($tempdir))
				{
					$FTPOptions = JClientHelper::getCredentials('ftp');
					$ftp = JClientFtp::getInstance($FTPOptions['host'], $FTPOptions['port'], array(), $FTPOptions['user'], $FTPOptions['pass']);
					$dest = JPath::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $tempdir . '/admintools'), '/');

					if (!@mkdir($tempdir . '/admintools'))
					{
						$ftp->mkdir($dest);
					}

					if (!@chmod($tempdir . '/admintools', 511))
					{
						$ftp->chmod($dest, 511);
					}

					$tempdir .= '/admintools';
				}
			}

			// If we still have no writable directory, we'll try /tmp and the system's temp-directory.
			$writable = @is_writeable($tempdir);

			if (!$writable)
			{
				if (@is_dir('/tmp') && @is_writable('/tmp'))
				{
					$tempdir = '/tmp';
				}
				else
				{
					// Try to find the system temp path.
					$tmpfile = @tempnam('dummy', '');
					$systemp = @dirname($tmpfile);
					@unlink($tmpfile);

					if (!empty($systemp))
					{
						if (@is_dir($systemp) && @is_writable($systemp))
						{
							$tempdir = $systemp;
						}
					}
				}
			}

			$data .= <<<ENDDATA
	,
	'kickstart.ftp.ssl' => '0',
	'kickstart.ftp.passive' => '1',
	'kickstart.ftp.host' => '$ftp_host',
	'kickstart.ftp.port' => '$ftp_port',
	'kickstart.ftp.user' => '$ftp_user',
	'kickstart.ftp.pass' => '$ftp_pass',
	'kickstart.ftp.dir' => '$ftp_root',
	'kickstart.ftp.tempdir' => '$tempdir'
ENDDATA;
		}

		$data .= ');';

		// Remove the old file, if it's there...
		$configpath = JPATH_COMPONENT_ADMINISTRATOR . '/restoration.php';

		if (JFile::exists($configpath))
		{
			JFile::delete($configpath);
		}

		// Write new file. First try with JFile.
		$result = JFile::write($configpath, $data);

		// In case JFile used FTP but direct access could help.
		if (!$result)
		{
			if (function_exists('file_put_contents'))
			{
				$result = @file_put_contents($configpath, $data);

				if ($result !== false)
				{
					$result = true;
				}
			}
			else
			{
				$fp = @fopen($configpath, 'wt');

				if ($fp !== false)
				{
					$result = @fwrite($fp, $data);

					if ($result !== false)
					{
						$result = true;
					}

					@fclose($fp);
				}
			}
		}

		return $result;
	}

	/**
	 * Runs the schema update SQL files, the PHP update script and updates the
	 * manifest cache and #__extensions entry. Essentially, it is identical to
	 * JInstallerFile::install() without the file copy.
	 *
	 * @return  boolean True on success.
	 *
	 * @since   2.5.4
	 */
	public function finaliseUpgrade()
	{
		$installer = JInstaller::getInstance();

		$manifest = $installer->isManifest(JPATH_MANIFESTS . '/files/joomla.xml');

		if ($manifest === false)
		{
			$installer->abort(JText::_('JLIB_INSTALLER_ABORT_DETECTMANIFEST'));

			return false;
		}

		$installer->manifest = $manifest;

		$installer->setUpgrade(true);
		$installer->setOverwrite(true);

		$installer->extension = JTable::getInstance('extension');
		$installer->extension->load(700);

		$installer->setAdapter($installer->extension->type);

		$installer->setPath('manifest', JPATH_MANIFESTS . '/files/joomla.xml');
		$installer->setPath('source', JPATH_MANIFESTS . '/files');
		$installer->setPath('extension_root', JPATH_ROOT);

		// Run the script file.
		JLoader::register('JoomlaInstallerScript', JPATH_ADMINISTRATOR . '/components/com_admin/script.php');

		$manifestClass = new JoomlaInstallerScript;

		ob_start();
		ob_implicit_flush(false);

		if ($manifestClass && method_exists($manifestClass, 'preflight'))
		{
			if ($manifestClass->preflight('update', $installer) === false)
			{
				$installer->abort(JText::_('JLIB_INSTALLER_ABORT_FILE_INSTALL_CUSTOM_INSTALL_FAILURE'));

				return false;
			}
		}

		// Create msg object; first use here.
		$msg = ob_get_contents();
		ob_end_clean();

		// Get a database connector object.
		$db = $this->getDbo();

		/*
		 * Check to see if a file extension by the same name is already installed.
		 * If it is, then update the table because if the files aren't there
		 * we can assume that it was (badly) uninstalled.
		 * If it isn't, add an entry to extensions.
		 */
		$query = $db->getQuery(true)
			->select($db->quoteName('extension_id'))
			->from($db->quoteName('#__extensions'))
			->where($db->quoteName('type') . ' = ' . $db->quote('file'))
			->where($db->quoteName('element') . ' = ' . $db->quote('joomla'));
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (RuntimeException $e)
		{
			// Install failed, roll back changes.
			$installer->abort(
				JText::sprintf('JLIB_INSTALLER_ABORT_FILE_ROLLBACK', JText::_('JLIB_INSTALLER_UPDATE'), $e->getMessage())
			);

			return false;
		}

		$id = $db->loadResult();
		$row = JTable::getInstance('extension');

		if ($id)
		{
			// Load the entry and update the manifest_cache.
			$row->load($id);

			// Update name.
			$row->set('name', 'files_joomla');

			// Update manifest.
			$row->manifest_cache = $installer->generateManifestCache();

			if (!$row->store())
			{
				// Install failed, roll back changes.
				$installer->abort(
					JText::sprintf('JLIB_INSTALLER_ABORT_FILE_ROLLBACK', JText::_('JLIB_INSTALLER_UPDATE'), $row->getError())
				);

				return false;
			}
		}
		else
		{
			// Add an entry to the extension table with a whole heap of defaults.
			$row->set('name', 'files_joomla');
			$row->set('type', 'file');
			$row->set('element', 'joomla');

			// There is no folder for files so leave it blank.
			$row->set('folder', '');
			$row->set('enabled', 1);
			$row->set('protected', 0);
			$row->set('access', 0);
			$row->set('client_id', 0);
			$row->set('params', '');
			$row->set('system_data', '');
			$row->set('manifest_cache', $installer->generateManifestCache());

			if (!$row->store())
			{
				// Install failed, roll back changes.
				$installer->abort(JText::sprintf('JLIB_INSTALLER_ABORT_FILE_INSTALL_ROLLBACK', $row->getError()));

				return false;
			}

			// Set the insert id.
			$row->set('extension_id', $db->insertid());

			// Since we have created a module item, we add it to the installation step stack
			// so that if we have to rollback the changes we can undo it.
			$installer->pushStep(array('type' => 'extension', 'extension_id' => $row->extension_id));
		}

		$result = $installer->parseSchemaUpdates($manifest->update->schemas, $row->extension_id);

		if ($result === false)
		{
			// Install failed, rollback changes.
			$installer->abort(JText::sprintf('JLIB_INSTALLER_ABORT_FILE_UPDATE_SQL_ERROR', $db->stderr(true)));

			return false;
		}

		// Start Joomla! 1.6.
		ob_start();
		ob_implicit_flush(false);

		if ($manifestClass && method_exists($manifestClass, 'update'))
		{
			if ($manifestClass->update($installer) === false)
			{
				// Install failed, rollback changes.
				$installer->abort(JText::_('JLIB_INSTALLER_ABORT_FILE_INSTALL_CUSTOM_INSTALL_FAILURE'));

				return false;
			}
		}

		// Append messages.
		$msg .= ob_get_contents();
		ob_end_clean();

		// Clobber any possible pending updates.
		$update = JTable::getInstance('update');
		$uid = $update->find(
			array('element' => 'joomla', 'type' => 'file', 'client_id' => '0', 'folder' => '')
		);

		if ($uid)
		{
			$update->delete($uid);
		}

		// And now we run the postflight.
		ob_start();
		ob_implicit_flush(false);

		if ($manifestClass && method_exists($manifestClass, 'postflight'))
		{
			$manifestClass->postflight('update', $installer);
		}

		// Append messages.
		$msg .= ob_get_contents();
		ob_end_clean();

		if ($msg != '')
		{
			$installer->set('extension_message', $msg);
		}

		// Refresh versionable assets cache.
		JFactory::getApplication()->flushAssets();

		return true;
	}

	/**
	 * Removes the extracted package file.
	 *
	 * @return  void
	 *
	 * @since   2.5.4
	 */
	public function cleanUp()
	{
		// Remove the update package.
		$config = JFactory::getConfig();
		$tempdir = $config->get('tmp_path');

		$file = JFactory::getApplication()->getUserState('com_joomlaupdate.file', null);
		$target = $tempdir . '/' . $file;

		if (!@unlink($target))
		{
			JFile::delete($target);
		}

		// Remove the restoration.php file.
		$target = JPATH_COMPONENT_ADMINISTRATOR . '/restoration.php';

		if (!@unlink($target))
		{
			JFile::delete($target);
		}

		// Remove joomla.xml from the site's root.
		$target = JPATH_ROOT . '/joomla.xml';

		if (!@unlink($target))
		{
			JFile::delete($target);
		}

		// Unset the update filename from the session.
		JFactory::getApplication()->setUserState('com_joomlaupdate.file', null);
		$oldVersion = JFactory::getApplication()->getUserState('com_joomlaupdate.oldversion');

		// Trigger event after joomla update.
		JFactory::getApplication()->triggerEvent('onJoomlaAfterUpdate', array($oldVersion));
		JFactory::getApplication()->setUserState('com_joomlaupdate.oldversion', null);
	}

	/**
	 * Uploads what is presumably an update ZIP file under a mangled name in the temporary directory.
	 *
	 * @return  void
	 *
	 * @since   3.6.0
	 */
	public function upload()
	{
		// Get the uploaded file information.
		$input = JFactory::getApplication()->input;

		// Do not change the filter type 'raw'. We need this to let files containing PHP code to upload. See JInputFiles::get.
		$userfile = $input->files->get('install_package', null, 'raw');

		// Make sure that file uploads are enabled in php.
		if (!(bool) ini_get('file_uploads'))
		{
			throw new RuntimeException(JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLFILE'), 500);
		}

		// Make sure that zlib is loaded so that the package can be unpacked.
		if (!extension_loaded('zlib'))
		{
			throw new RuntimeException('COM_INSTALLER_MSG_INSTALL_WARNINSTALLZLIB', 500);
		}

		// If there is no uploaded file, we have a problem...
		if (!is_array($userfile))
		{
			throw new RuntimeException(JText::_('COM_INSTALLER_MSG_INSTALL_NO_FILE_SELECTED'), 500);
		}

		// Is the PHP tmp directory missing?
		if ($userfile['error'] && ($userfile['error'] == UPLOAD_ERR_NO_TMP_DIR))
		{
			throw new RuntimeException(
				JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR') . '<br />' .
				JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTSET'),
				500
			);
		}

		// Is the max upload size too small in php.ini?
		if ($userfile['error'] && ($userfile['error'] == UPLOAD_ERR_INI_SIZE))
		{
			throw new RuntimeException(
				JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR') . '<br />' . JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLUPLOADSIZE'),
				500
			);
		}

		// Check if there was a different problem uploading the file.
		if ($userfile['error'] || $userfile['size'] < 1)
		{
			throw new RuntimeException(JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR'), 500);
		}

		// Build the appropriate paths.
		$config   = JFactory::getConfig();
		$tmp_dest = tempnam($config->get('tmp_path'), 'ju');
		$tmp_src  = $userfile['tmp_name'];

		// Move uploaded file.
		jimport('joomla.filesystem.file');

		if (version_compare(JVERSION, '3.4.0', 'ge'))
		{
			$result = JFile::upload($tmp_src, $tmp_dest, false, true);
		}
		else
		{
			// Old Joomla! versions didn't have UploadShield and don't need the fourth parameter to accept uploads
			$result = JFile::upload($tmp_src, $tmp_dest);
		}

		if (!$result)
		{
			throw new RuntimeException(JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR'), 500);
		}

		JFactory::getApplication()->setUserState('com_joomlaupdate.temp_file', $tmp_dest);
	}

	/**
	 * Checks the super admin credentials are valid for the currently logged in users
	 *
	 * @param   array  $credentials  The credentials to authenticate the user with
	 *
	 * @return  boolean
	 *
	 * @since   3.6.0
	 */
	public function captiveLogin($credentials)
	{
		// Make sure the username matches
		$username = isset($credentials['username']) ? $credentials['username'] : null;
		$user     = JFactory::getUser();

		if (strtolower($user->username) != strtolower($username))
		{
			return false;
		}

		// Make sure the user is authorised
		if (!$user->authorise('core.admin'))
		{
			return false;
		}

		// Get the global JAuthentication object.
		$authenticate = JAuthentication::getInstance();
		$response     = $authenticate->authenticate($credentials);

		if ($response->status !== JAuthentication::STATUS_SUCCESS)
		{
			return false;
		}

		return true;
	}

	/**
	 * Does the captive (temporary) file we uploaded before still exist?
	 *
	 * @return  boolean
	 *
	 * @since   3.6.0
	 */
	public function captiveFileExists()
	{
		$file = JFactory::getApplication()->getUserState('com_joomlaupdate.temp_file', null);

		JLoader::import('joomla.filesystem.file');

		if (empty($file) || !JFile::exists($file))
		{
			return false;
		}

		return true;
	}

	/**
	 * Remove the captive (temporary) file we uploaded before and the .
	 *
	 * @return  void
	 *
	 * @since   3.6.0
	 */
	public function removePackageFiles()
	{
		$files = array(
			JFactory::getApplication()->getUserState('com_joomlaupdate.temp_file', null),
			JFactory::getApplication()->getUserState('com_joomlaupdate.file', null),
		);

		JLoader::import('joomla.filesystem.file');

		foreach ($files as $file)
		{
			if (JFile::exists($file))
			{
				if (!@unlink($file))
				{
					JFile::delete($file);
				}
			}
		}
	}

	/**
	 * Gets PHP options.
	 * TODO: Outsource, build common code base for pre install and pre update check
	 *
	 * @return array Array of PHP config options
	 *
	 * @since   3.10.0
	 */
	public function getPhpOptions()
	{
		$options = array();

		/*
		 * Check the PHP Version. It is already checked in JUpdate.
		 * A Joomla! Update which is not supported by current PHP
		 * version is not shown. So this check is actually unnecessary.
		 */
		$option         = new stdClass;
		$option->label  = JText::sprintf('INSTL_PHP_VERSION_NEWER', $this->getTargetMinimumPHPVersion());
		$option->state  = $this->isPhpVersionSupported();
		$option->notice = null;
		$options[]      = $option;

		// Only check if required PHP version is less than 7.
		if (version_compare($this->getTargetMinimumPHPVersion(), '7', '<'))
		{
			// Check for magic quotes gpc.
			$option         = new stdClass;
			$option->label  = JText::_('INSTL_MAGIC_QUOTES_GPC');
			$option->state  = (ini_get('magic_quotes_gpc') == false);
			$option->notice = null;
			$options[]      = $option;

			// Check for register globals.
			$option         = new stdClass;
			$option->label  = JText::_('INSTL_REGISTER_GLOBALS');
			$option->state  = (ini_get('register_globals') == false);
			$option->notice = null;
			$options[]      = $option;
		}

		// Check for zlib support.
		$option         = new stdClass;
		$option->label  = JText::_('INSTL_ZLIB_COMPRESSION_SUPPORT');
		$option->state  = extension_loaded('zlib');
		$option->notice = null;
		$options[]      = $option;

		// Check for XML support.
		$option         = new stdClass;
		$option->label  = JText::_('INSTL_XML_SUPPORT');
		$option->state  = extension_loaded('xml');
		$option->notice = null;
		$options[]      = $option;

		// Check for mbstring options.
		if (extension_loaded('mbstring'))
		{
			// Check for default MB language.
			$option = new stdClass;
			$option->label  = JText::_('INSTL_MB_LANGUAGE_IS_DEFAULT');
			$option->state  = strtolower(ini_get('mbstring.language')) === 'neutral';
			$option->notice = $option->state ? null : JText::_('INSTL_NOTICEMBLANGNOTDEFAULT');
			$options[] = $option;

			// Check for MB function overload.
			$option = new stdClass;
			$option->label  = JText::_('INSTL_MB_STRING_OVERLOAD_OFF');
			$option->state  = ini_get('mbstring.func_overload') == 0;
			$option->notice = $option->state ? null : JText::_('INSTL_NOTICEMBSTRINGOVERLOAD');
			$options[] = $option;
		}

		// Check for a missing native parse_ini_file implementation.
		$option = new stdClass;
		$option->label  = JText::_('INSTL_PARSE_INI_FILE_AVAILABLE');
		$option->state  = $this->getIniParserAvailability();
		$option->notice = null;
		$options[] = $option;

		// Check for missing native json_encode / json_decode support.
		$option = new stdClass;
		$option->label  = JText::_('INSTL_JSON_SUPPORT_AVAILABLE');
		$option->state  = function_exists('json_encode') && function_exists('json_decode');
		$option->notice = null;
		$options[] = $option;

		$updateInformation = $this->getUpdateInformation();

		// Check if configured database is compatible with Joomla 4
		if (version_compare($updateInformation['latest'], '4', '>='))
		{
			$option = new stdClass;
			$option->label  = JText::sprintf('INSTL_DATABASE_SUPPORTED', $this->getConfiguredDatabaseType());
			$option->state  = $this->isDatabaseTypeSupported();
			$option->notice = null;
			$options[]      = $option;
		}

		// Check if database structure is up to date
		$option = new stdClass;
		$option->label  = JText::_('COM_JOOMLAUPDATE_VIEW_DEFAULT_DATABASE_STRUCTURE_TITLE');
		$option->state  = $this->getDatabaseSchemaCheck();
		$option->notice = $option->state ? null : JText::_('COM_JOOMLAUPDATE_VIEW_DEFAULT_DATABASE_STRUCTURE_NOTICE');
		$options[] = $option;

		return $options;
	}

	/**
	 * Gets PHP Settings.
	 * TODO: Outsource, build common code base for pre install and pre update check
	 *
	 * @return  array
	 *
	 * @since   3.10.0
	 */
	public function getPhpSettings()
	{
		$settings = array();

		// Check for display errors.
		$setting = new stdClass;
		$setting->label = JText::_('INSTL_DISPLAY_ERRORS');
		$setting->state = (bool) ini_get('display_errors');
		$setting->recommended = false;
		$settings[] = $setting;

		// Check for file uploads.
		$setting = new stdClass;
		$setting->label = JText::_('INSTL_FILE_UPLOADS');
		$setting->state = (bool) ini_get('file_uploads');
		$setting->recommended = true;
		$settings[] = $setting;

		// Only check if required PHP version is less than 7.
		if (version_compare($this->getTargetMinimumPHPVersion(), '7', '<'))
		{
			// Check for magic quotes runtimes.
			$setting = new stdClass;
			$setting->label = JText::_('INSTL_MAGIC_QUOTES_RUNTIME');
			$setting->state = (bool) ini_get('magic_quotes_runtime');
			$setting->recommended = false;
			$settings[] = $setting;

			// Check for safe mode.
			$setting = new stdClass;
			$setting->label = JText::_('INSTL_SAFE_MODE');
			$setting->state = (bool) ini_get('safe_mode');
			$setting->recommended = false;
			$settings[] = $setting;
		}

		// Check for output buffering.
		$setting = new stdClass;
		$setting->label = JText::_('INSTL_OUTPUT_BUFFERING');
		$setting->state = (int) ini_get('output_buffering') !== 0;
		$setting->recommended = false;
		$settings[] = $setting;

		// Check for session auto-start.
		$setting = new stdClass;
		$setting->label = JText::_('INSTL_SESSION_AUTO_START');
		$setting->state = (bool) ini_get('session.auto_start');
		$setting->recommended = false;
		$settings[] = $setting;

		// Check for native ZIP support.
		$setting = new stdClass;
		$setting->label = JText::_('INSTL_ZIP_SUPPORT_AVAILABLE');
		$setting->state = function_exists('zip_open') && function_exists('zip_read');
		$setting->recommended = true;
		$settings[] = $setting;

		return $settings;
	}

	/**
	 * Returns the configured database type id (mysqli or sqlsrv or ...)
	 *
	 * @return string
	 *
	 * @since 3.10.0
	 */
	private function getConfiguredDatabaseType()
	{
		return JFactory::getApplication()->get('dbtype');
	}

	/**
	 * Returns true, if J! version is < 4 or current configured
	 * database type is compatible with the update.
	 *
	 * @return boolean
	 *
	 * @since 3.10.0
	 */
	public function isDatabaseTypeSupported()
	{
		$updateInformation = $this->getUpdateInformation();

		// Check if configured database is compatible with Joomla 4
		if (version_compare($updateInformation['latest'], '4', '>='))
		{
			$unsupportedDatabaseTypes = array('sqlsrv', 'sqlazure');
			$currentDatabaseType = $this->getConfiguredDatabaseType();

			return !in_array($currentDatabaseType, $unsupportedDatabaseTypes);
		}

		return true;
	}


	/**
	 * Returns true, if current installed php version is compatible with the update.
	 *
	 * @return boolean
	 *
	 * @since 3.10.0
	 */
	public function isPhpVersionSupported()
	{
		return version_compare(PHP_VERSION, $this->getTargetMinimumPHPVersion(), '>=');
	}

	/**
	 * Returns the PHP minimum version for the update.
	 * Returns JOOMLA_MINIMUM_PHP, if there is no information given.
	 *
	 * @return string
	 *
	 * @since 3.10.0
	 */
	private function getTargetMinimumPHPVersion()
	{
		$updateInformation = $this->getUpdateInformation();

		return isset($updateInformation['object']->php_minimum) ?
			$updateInformation['object']->php_minimum->_data :
			JOOMLA_MINIMUM_PHP;
	}

	/**
	 * Checks the availability of the parse_ini_file and parse_ini_string functions.
	 * TODO: Outsource, build common code base for pre install and pre update check
	 *
	 * @return  boolean  True if the method exists.
	 *
	 * @since   3.10.0
	 */
	public function getIniParserAvailability()
	{
		$disabledFunctions = ini_get('disable_functions');

		if (!empty($disabledFunctions))
		{
			// Attempt to detect them in the disable_functions blacklist.
			$disabledFunctions = explode(',', trim($disabledFunctions));
			$numberOfDisabledFunctions = count($disabledFunctions);

			for ($i = 0; $i < $numberOfDisabledFunctions; $i++)
			{
				$disabledFunctions[$i] = trim($disabledFunctions[$i]);
			}

			$result = !in_array('parse_ini_string', $disabledFunctions);
		}
		else
		{
			// Attempt to detect their existence; even pure PHP implementations of them will trigger a positive response, though.
			$result = function_exists('parse_ini_string');
		}

		return $result;
	}


	/**
	 * Check if database structure is up to date
	 *
	 * @return  boolean  True if ok, false if not.
	 *
	 * @since   3.10.0
	 */
	private function getDatabaseSchemaCheck()
	{
		JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_installer/models', 'InstallerModel');

		// Get the database model
		$model = JModelLegacy::getInstance('Database', 'InstallerModel');

		// Check if no default text filters found
		if (!$model->getDefaultTextFilters())
		{
			return false;
		}

		// Check if database update version does not match CMS version
		if (version_compare($model->getUpdateVersion(), JVERSION) != 0)
		{
			return false;
		}

		// Get the schema change set
		$changeSet = $model->getItems();

		$changeSetCheck = $changeSet->check();

		// Check if schema errors found
		if (!empty($changeSetCheck))
		{
			return false;
		}

		// Check if database schema version does not match CMS version
		if ($model->getSchemaVersion() != $changeSet->getSchema())
		{
			return false;
		}

		// No database problems found
		return true;
	}

	/**
	 * Gets an array containing all installed extensions, that are not core extensions.
	 *
	 * @return  array  name,version,updateserver
	 *
	 * @since   3.10.0
	 */
	public function getNonCoreExtensions()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		$query->select(
			$db->qn('ex.name') . ', ' .
			$db->qn('ex.extension_id') . ', ' .
			$db->qn('ex.manifest_cache') . ', ' .
			$db->qn('ex.type') . ', ' .
			$db->qn('ex.folder') . ', ' .
			$db->qn('ex.element') . ', ' .
			$db->qn('ex.client_id')
		)->from(
			$db->qn('#__extensions', 'ex')
		)->where(
			$db->qn('ex.package_id') . ' = 0'
		);

		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$rows = array_filter($rows, 'JoomlaupdateModelDefault::isNonCoreExtension');

		foreach ($rows as $extension)
		{
			$decode = json_decode($extension->manifest_cache);

			// Remove unused fields so they do not cause javascript errors during pre-update check
			unset($decode->description);
			unset($decode->copyright);
			unset($decode->creationDate);

			$this->translateExtensionName($extension);
			$extension->version = isset($decode->version)
				? $decode->version
				: JText::_('COM_JOOMLAUPDATE_PREUPDATE_UNKNOWN_EXTENSION_MANIFESTCACHE_VERSION');
			unset($extension->manifest_cache);
			$extension->manifest_cache = $decode;
		}

		return $rows;
	}

	/**
	 * Checks if extension is non core extension.
	 *
	 * @param   object  $extension  The extension to be checked
	 *
	 * @return  bool  true if extension is not a core extension
	 *
	 * @since   3.10.0
	 */
	private static function isNonCoreExtension($extension)
	{
		return !\JExtensionHelper::checkIfCoreExtension($extension->type, $extension->element, $extension->client_id, $extension->folder);
	}

	/**
	 * Gets an array containing all installed and enabled plugins, that are not core plugins.
	 *
	 * @param   array  $folderFilter  Limit the list of plugins to a specific set of folder values
	 *
	 * @return  array  name,version,updateserver
	 *
	 * @since   3.10.0
	 */
	public function getNonCorePlugins($folderFilter = array())
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true);

		$query->select(
			$db->qn('ex.name') . ', ' .
			$db->qn('ex.extension_id') . ', ' .
			$db->qn('ex.manifest_cache') . ', ' .
			$db->qn('ex.type') . ', ' .
			$db->qn('ex.folder') . ', ' .
			$db->qn('ex.element') . ', ' .
			$db->qn('ex.client_id') . ', ' .
			$db->qn('ex.package_id')
		)->from(
			$db->qn('#__extensions', 'ex')
		)->where(
			$db->qn('ex.type') . ' = ' . $db->quote('plugin')
		)->where(
			$db->qn('ex.enabled') . ' = 1'
		);

		if (count($folderFilter) > 0)
		{
			$folderFilter = array_map(array($db, 'quote'), $folderFilter);

			$query->where($db->qn('folder') . ' IN (' . implode(',', $folderFilter) . ')');
		}

		$db->setQuery($query);
		$rows = $db->loadObjectList();
		$rows = array_filter($rows, 'JoomlaupdateModelDefault::isNonCoreExtension');

		foreach ($rows as $plugin)
		{
			$decode = json_decode($plugin->manifest_cache);

			// Remove unused fields so they do not cause javascript errors during pre-update check
			unset($decode->description);
			unset($decode->copyright);
			unset($decode->creationDate);

			$this->translateExtensionName($plugin);
			$plugin->version = isset($decode->version)
				? $decode->version
				: JText::_('COM_JOOMLAUPDATE_PREUPDATE_UNKNOWN_EXTENSION_MANIFESTCACHE_VERSION');
			unset($plugin->manifest_cache);
			$plugin->manifest_cache = $decode;
		}

		return $rows;
	}

	/**
	 * Called by controller's fetchExtensionCompatibility, which is called via AJAX.
	 *
	 * @param   string  $extensionID          The ID of the checked extension
	 * @param   string  $joomlaTargetVersion  Target version of Joomla
	 *
	 * @return object
	 *
	 * @since 3.10.0
	 */
	public function fetchCompatibility($extensionID, $joomlaTargetVersion)
	{
		$updateSites = $this->getUpdateSitesInfo($extensionID);

		if (empty($updateSites))
		{
			return (object) array('state' => 2);
		}

		foreach ($updateSites as $updateSite)
		{
			if ($updateSite['type'] === 'collection')
			{
				$updateFileUrls = $this->getCollectionDetailsUrls($updateSite, $joomlaTargetVersion);

				foreach ($updateFileUrls as $updateFileUrl)
				{
					$compatibleVersions = $this->checkCompatibility($updateFileUrl, $joomlaTargetVersion);

					// Return the compatible versions
					return (object) array('state' => 1, 'compatibleVersions' => $compatibleVersions);
				}
			}
			else
			{
				$compatibleVersions = $this->checkCompatibility($updateSite['location'], $joomlaTargetVersion);

				// Return the compatible versions
				return (object) array('state' => 1, 'compatibleVersions' => $compatibleVersions);
			}
		}

		// In any other case we mark this extension as not compatible
		return (object) array('state' => 0);
	}

	/**
	 * Returns records with update sites and extension information for a given extension ID.
	 *
	 * @param   int  $extensionID  The extension ID
	 *
	 * @return  array
	 *
	 * @since 3.10.0
	 */
	private function getUpdateSitesInfo($extensionID)
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		$query->select(
			$db->qn('us.type') . ', ' .
			$db->qn('us.location') . ', ' .
			$db->qn('e.element') . ' AS ' . $db->qn('ext_element') . ', ' .
			$db->qn('e.type') . ' AS ' . $db->qn('ext_type') . ', ' .
			$db->qn('e.folder') . ' AS ' . $db->qn('ext_folder')
		)->from(
			$db->qn('#__update_sites', 'us')
		)->leftJoin(
				$db->qn('#__update_sites_extensions', 'ue')
				. ' ON ' . $db->qn('ue.update_site_id') . ' = ' . $db->qn('us.update_site_id')
		)->leftJoin(
				$db->qn('#__extensions', 'e')
				. ' ON ' . $db->qn('e.extension_id') . ' = ' . $db->qn('ue.extension_id')
		)->where($db->qn('e.extension_id') . ' = ' . (int) $extensionID);

		$db->setQuery($query);

		$result = $db->loadAssocList();

		if (!is_array($result))
		{
			return array();
		}

		return $result;
	}

	/**
	 * Method to get details URLs from a colletion update site for given extension and Joomla target version.
	 *
	 * @param   array   $updateSiteInfo       The update site and extension information record to process
	 * @param   string  $joomlaTargetVersion  The Joomla! version to test against,
	 *
	 * @return  array  An array of URLs.
	 *
	 * @since   3.10.0
	 */
	private function getCollectionDetailsUrls($updateSiteInfo, $joomlaTargetVersion)
	{
		$return = array();

		$http = new JHttp;

		try
		{
			$response = $http->get($updateSiteInfo['location']);
		}
		catch (RuntimeException $e)
		{
			$response = null;
		}

		if ($response === null || $response->code !== 200)
		{
			return $return;
		}

		$updateSiteXML = simplexml_load_string($response->body);

		foreach ($updateSiteXML->extension as $extension)
		{
			$attribs = new stdClass;

			$attribs->element               = '';
			$attribs->type                  = '';
			$attribs->folder                = '';
			$attribs->targetplatformversion = '';

			foreach ($extension->attributes() as $key => $value)
			{
				$attribs->$key = (string) $value;
			}

			if ($attribs->element === $updateSiteInfo['ext_element']
				&& $attribs->type === $updateSiteInfo['ext_type']
				&& $attribs->folder === $updateSiteInfo['ext_folder']
				&& preg_match('/^' . $attribs->targetplatformversion . '/', $joomlaTargetVersion))
			{
				$return[] = (string) $extension['detailsurl'];
			}
		}

		return $return;
	}

	/**
	 * Method to check non core extensions for compatibility.
	 *
	 * @param   string  $updateFileUrl        The items update XML url.
	 * @param   string  $joomlaTargetVersion  The Joomla! version to test against
	 *
	 * @return  array  An array of strings with compatible version numbers
	 *
	 * @since   3.10.0
	 */
	private function checkCompatibility($updateFileUrl, $joomlaTargetVersion)
	{
		// Get the minimum stability information from com_installer
		$minimumStability = JComponentHelper::getParams('com_installer')->get('minimum_stability', JUpdater::STABILITY_STABLE);

		$update = new JUpdate;
		$update->set('jversion.full', $joomlaTargetVersion);
		$update->loadFromXML($updateFileUrl, $minimumStability);

		$compatibleVersions = $update->get('compatibleVersions');

		// Check if old version of the updater library
		if (!isset($compatibleVersions))
		{
			$downloadUrl = $update->get('downloadurl');
			$updateVersion = $update->get('version');

			return empty($downloadUrl) || empty($downloadUrl->_data) || empty($updateVersion) ? array() : array($updateVersion->_data);
		}

		usort($compatibleVersions, 'version_compare');

		return $compatibleVersions;
	}

	/**
	 * Translates an extension name
	 *
	 * @param   object  &$item  The extension of which the name needs to be translated
	 *
	 * @return  void
	 *
	 * @since   3.10.0
	 */
	protected function translateExtensionName(&$item)
	{
		// ToDo: Cleanup duplicated code. from com_installer/models/extension.php
		$lang = JFactory::getLanguage();
		$path = $item->client_id ? JPATH_ADMINISTRATOR : JPATH_SITE;

		$extension = $item->element;
		$source = JPATH_SITE;

		switch ($item->type)
		{
			case 'component':
				$extension = $item->element;
				$source = $path . '/components/' . $extension;
				break;
			case 'module':
				$extension = $item->element;
				$source = $path . '/modules/' . $extension;
				break;
			case 'file':
				$extension = 'files_' . $item->element;
				break;
			case 'library':
				$extension = 'lib_' . $item->element;
				break;
			case 'plugin':
				$extension = 'plg_' . $item->folder . '_' . $item->element;
				$source = JPATH_PLUGINS . '/' . $item->folder . '/' . $item->element;
				break;
			case 'template':
				$extension = 'tpl_' . $item->element;
				$source = $path . '/templates/' . $item->element;
		}

		$lang->load("$extension.sys", JPATH_ADMINISTRATOR, null, false, true)
		|| $lang->load("$extension.sys", $source, null, false, true);
		$lang->load($extension, JPATH_ADMINISTRATOR, null, false, true)
		|| $lang->load($extension, $source, null, false, true);

		// Translate the extension name if possible
		$item->name = strip_tags(JText::_($item->name));
	}

	/**
	 * Checks whether a given template is active
	 *
	 * @param   string  $template  The template name to be checked
	 *
	 * @return  boolean
	 *
	 * @since   3.10.4
	 */
	public function isTemplateActive($template)
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		$query->select(
			$db->qn(
				array(
					'id',
					'home'
				)
			)
		)->from(
			$db->qn('#__template_styles')
		)->where(
			$db->qn('template') . ' = ' . $db->q($template)
		);

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

		$home = array_filter(
			$templates,
			function($value)
			{
				return $value->home > 0;
			}
		);

		$ids = JArrayHelper::getColumn($templates, 'id');

		$menu = false;

		if (count($ids))
		{
			$query = $db->getQuery(true);

			$query->select(
				'COUNT(*)'
			)->from(
				$db->qn('#__menu')
			)->where(
				$db->qn('template_style_id') . ' IN(' . implode(',', $ids) . ')'
			);

			$menu = $db->setQuery($query)->loadResult() > 0;
		}

		return $home || $menu;
	}
}
fields/modal/contact.php000060400000023366152455702350011270 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_contact
 *
 * @copyright   (C) 2013 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Language\LanguageHelper;

/**
 * Supports a modal contact picker.
 *
 * @since  1.6
 */
class JFormFieldModal_Contact extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var     string
	 * @since   1.6
	 */
	protected $type = 'Modal_Contact';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   1.6
	 */
	protected function getInput()
	{
		$allowNew       = ((string) $this->element['new'] == 'true');
		$allowEdit      = ((string) $this->element['edit'] == 'true');
		$allowClear     = ((string) $this->element['clear'] != 'false');
		$allowSelect    = ((string) $this->element['select'] != 'false');
		$allowPropagate = ((string) $this->element['propagate'] == 'true');

		$languages = LanguageHelper::getContentLanguages(array(0, 1));

		// Load language
		JFactory::getLanguage()->load('com_contact', JPATH_ADMINISTRATOR);

		// The active contact id field.
		$value = (int) $this->value > 0 ? (int) $this->value : '';

		// Create the modal id.
		$modalId = 'Contact_' . $this->id;

		// Add the modal field script to the document head.
		JHtml::_('jquery.framework');
		JHtml::_('script', 'system/modal-fields.js', array('version' => 'auto', 'relative' => true));

		// Script to proxy the select modal function to the modal-fields.js file.
		if ($allowSelect)
		{
			static $scriptSelect = null;

			if (is_null($scriptSelect))
			{
				$scriptSelect = array();
			}

			if (!isset($scriptSelect[$this->id]))
			{
				JFactory::getDocument()->addScriptDeclaration("
				function jSelectContact_" . $this->id . "(id, title, object) {
					window.processModalSelect('Contact', '" . $this->id . "', id, title, '', object);
				}
				");

				JText::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED');

				$scriptSelect[$this->id] = true;
			}
		}

		// Setup variables for display.
		$linkContacts = 'index.php?option=com_contact&amp;view=contacts&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';
		$linkContact  = 'index.php?option=com_contact&amp;view=contact&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';
		$modalTitle   = JText::_('COM_CONTACT_CHANGE_CONTACT');

		if (isset($this->element['language']))
		{
			$linkContacts .= '&amp;forcedLanguage=' . $this->element['language'];
			$linkContact   .= '&amp;forcedLanguage=' . $this->element['language'];
			$modalTitle     .= ' &#8212; ' . $this->element['label'];
		}

		$urlSelect = $linkContacts . '&amp;function=jSelectContact_' . $this->id;
		$urlEdit   = $linkContact . '&amp;task=contact.edit&amp;id=\' + document.getElementById("' . $this->id . '_id").value + \'';
		$urlNew    = $linkContact . '&amp;task=contact.add';

		if ($value)
		{
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true)
				->select($db->quoteName('name'))
				->from($db->quoteName('#__contact_details'))
				->where($db->quoteName('id') . ' = ' . (int) $value);
			$db->setQuery($query);

			try
			{
				$title = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				JError::raiseWarning(500, $e->getMessage());
			}
		}

		$title = empty($title) ? JText::_('COM_CONTACT_SELECT_A_CONTACT') : htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

		// The current contact display field.
		$html  = '<span class="input-append">';
		$html .= '<input class="input-medium" id="' . $this->id . '_name" type="text" value="' . $title . '" disabled="disabled" size="35" />';

		// Select contact button
		if ($allowSelect)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"'
				. ' id="' . $this->id . '_select"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalSelect' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_CONTACT_CHANGE_CONTACT') . '">'
				. '<span class="icon-file" aria-hidden="true"></span> ' . JText::_('JSELECT')
				. '</button>';
		}

		// New contact button
		if ($allowNew)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"'
				. ' id="' . $this->id . '_new"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalNew' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_CONTACT_NEW_CONTACT') . '">'
				. '<span class="icon-new" aria-hidden="true"></span> ' . JText::_('JACTION_CREATE')
				. '</button>';
		}

		// Edit contact button
		if ($allowEdit)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"'
				. ' id="' . $this->id . '_edit"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalEdit' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_CONTACT_EDIT_CONTACT') . '">'
				. '<span class="icon-edit" aria-hidden="true"></span> ' . JText::_('JACTION_EDIT')
				. '</button>';
		}

		// Clear contact button
		if ($allowClear)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn' . ($value ? '' : ' hidden') . '"'
				. ' id="' . $this->id . '_clear"'
				. ' onclick="window.processModalParent(\'' . $this->id . '\'); return false;">'
				. '<span class="icon-remove" aria-hidden="true"></span>' . JText::_('JCLEAR')
				. '</button>';
		}

		// Propagate contact button
		if ($allowPropagate && count($languages) > 2)
		{
			// Strip off language tag at the end
			$tagLength = (int) strlen($this->element['language']);
			$callbackFunctionStem = substr("jSelectContact_" . $this->id, 0, -$tagLength);

			$html .= '<a'
			. ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"'
			. ' id="' . $this->id . '_propagate"'
			. ' href="#"'
			. ' title="' . JHtml::tooltipText('JGLOBAL_ASSOCIATIONS_PROPAGATE_TIP') . '"'
			. ' onclick="Joomla.propagateAssociation(\'' . $this->id . '\', \'' . $callbackFunctionStem . '\');">'
			. '<span class="icon-refresh" aria-hidden="true"></span>' . JText::_('JGLOBAL_ASSOCIATIONS_PROPAGATE_BUTTON')
			. '</a>';
		}

		$html .= '</span>';

		// Select contact modal
		if ($allowSelect)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalSelect' . $modalId,
				array(
					'title'       => $modalTitle,
					'url'         => $urlSelect,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn" data-dismiss="modal">' . JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>',
				)
			);
		}

		// New contact modal
		if ($allowNew)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalNew' . $modalId,
				array(
					'title'       => JText::_('COM_CONTACT_NEW_CONTACT'),
					'backdrop'    => 'static',
					'keyboard'    => false,
					'closeButton' => false,
					'url'         => $urlNew,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'add\', \'contact\', \'cancel\', \'contact-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>'
							. '<button type="button" class="btn btn-primary"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'add\', \'contact\', \'save\', \'contact-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JSAVE') . '</button>'
							. '<button type="button" class="btn btn-success"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'add\', \'contact\', \'apply\', \'contact-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JAPPLY') . '</button>',
				)
			);
		}

		// Edit contact modal.
		if ($allowEdit)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalEdit' . $modalId,
				array(
					'title'       => JText::_('COM_CONTACT_EDIT_CONTACT'),
					'backdrop'    => 'static',
					'keyboard'    => false,
					'closeButton' => false,
					'url'         => $urlEdit,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id
							. '\', \'edit\', \'contact\', \'cancel\', \'contact-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>'
							. '<button type="button" class="btn btn-primary"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'edit\', \'contact\', \'save\', \'contact-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JSAVE') . '</button>'
							. '<button type="button" class="btn btn-success"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'edit\', \'contact\', \'apply\', \'contact-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JAPPLY') . '</button>',
				)
			);
		}

		// Note: class='required' for client side validation.
		$class = $this->required ? ' class="required modal-value"' : '';

		$html .= '<input type="hidden" id="' . $this->id . '_id"' . $class . ' data-required="' . (int) $this->required . '" name="' . $this->name
			. '" data-text="' . htmlspecialchars(JText::_('COM_CONTACT_SELECT_A_CONTACT', true), ENT_COMPAT, 'UTF-8') . '" value="' . $value . '" />';

		return $html;
	}

	/**
	 * Method to get the field label markup.
	 *
	 * @return  string  The field label markup.
	 *
	 * @since   3.4
	 */
	protected function getLabel()
	{
		return str_replace($this->id, $this->id . '_id', parent::getLabel());
	}
}
forms/fields/mail.xml000060400000000353152455702350010611 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="params" label="COM_FIELDS_FIELD_BASIC_LABEL">
		<fieldset name="basic">
			<field
				name="display"
				type="hidden"
				default="2"
			/>
		</fieldset>
	</fields>
</form>
contacts.php000060400000023723152455702350007106 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_contact
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Methods supporting a list of contact records.
 *
 * @since  1.6
 */
class ContactModelContacts extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JControllerLegacy
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'name', 'a.name',
				'alias', 'a.alias',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'catid', 'a.catid', 'category_id', 'category_title',
				'user_id', 'a.user_id',
				'published', 'a.published',
				'access', 'a.access', 'access_level',
				'created', 'a.created',
				'created_by', 'a.created_by',
				'ordering', 'a.ordering',
				'featured', 'a.featured',
				'language', 'a.language', 'language_title',
				'publish_up', 'a.publish_up',
				'publish_down', 'a.publish_down',
				'ul.name', 'linked_user',
				'tag',
				'level', 'c.level',
			);

			$assoc = JLanguageAssociations::isEnabled();

			if ($assoc)
			{
				$config['filter_fields'][] = 'association';
			}
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.name', $direction = 'asc')
	{
		$app = JFactory::getApplication();

		$forcedLanguage = $app->input->get('forcedLanguage', '', 'cmd');

		// Adjust the context to support modal layouts.
		if ($layout = $app->input->get('layout'))
		{
			$this->context .= '.' . $layout;
		}

		// Adjust the context to support forced languages.
		if ($forcedLanguage)
		{
			$this->context .= '.' . $forcedLanguage;
		}

		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.published', $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '', 'string'));
		$this->setState('filter.category_id',
						$this->getUserStateFromRequest($this->context . '.filter.category_id', 'filter_category_id', '', 'string')
		);
		$this->setState('filter.access', $this->getUserStateFromRequest($this->context . '.filter.access', 'filter_access', '', 'cmd'));
		$this->setState('filter.language', $this->getUserStateFromRequest($this->context . '.filter.language', 'filter_language', '', 'string'));
		$this->setState('filter.tag', $this->getUserStateFromRequest($this->context . '.filter.tag', 'filter_tag', '', 'string'));
		$this->setState('filter.level', $this->getUserStateFromRequest($this->context . '.filter.level', 'filter_level', null, 'int'));

		// List state information.
		parent::populateState($ordering, $direction);

		// Force a language.
		if (!empty($forcedLanguage))
		{
			$this->setState('filter.language', $forcedLanguage);
		}
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.published');
		$id .= ':' . serialize($this->getState('filter.category_id'));
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.language');
		$id .= ':' . $this->getState('filter.tag');
		$id .= ':' . $this->getState('filter.level');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$user = JFactory::getUser();

		// Select the required fields from the table.
		$query->select(
			$db->quoteName(
				explode(', ', $this->getState(
					'list.select',
					'a.id, a.name, a.alias, a.checked_out, a.checked_out_time, a.catid, a.user_id' .
					', a.published, a.access, a.created, a.created_by, a.ordering, a.featured, a.language' .
					', a.publish_up, a.publish_down'
					)
				)
			)
		);
		$query->from($db->quoteName('#__contact_details', 'a'));

		// Join over the users for the linked user.
		$query->select(
				array(
					$db->quoteName('ul.name', 'linked_user'),
					$db->quoteName('ul.email')
				)
			)
			->join(
				'LEFT',
				$db->quoteName('#__users', 'ul') . ' ON ' . $db->quoteName('ul.id') . ' = ' . $db->quoteName('a.user_id')
			);

		// Join over the language
		$query->select($db->quoteName('l.title', 'language_title'))
			->select($db->quoteName('l.image', 'language_image'))
			->join(
				'LEFT',
				$db->quoteName('#__languages', 'l') . ' ON ' . $db->quoteName('l.lang_code') . ' = ' . $db->quoteName('a.language')
			);

		// Join over the users for the checked out user.
		$query->select($db->quoteName('uc.name', 'editor'))
			->join(
				'LEFT',
				$db->quoteName('#__users', 'uc') . ' ON ' . $db->quoteName('uc.id') . ' = ' . $db->quoteName('a.checked_out')
			);

		// Join over the asset groups.
		$query->select($db->quoteName('ag.title', 'access_level'))
			->join(
				'LEFT',
				$db->quoteName('#__viewlevels', 'ag') . ' ON ' . $db->quoteName('ag.id') . ' = ' . $db->quoteName('a.access')
			);

		// Join over the categories.
		$query->select($db->quoteName('c.title', 'category_title'))
			->join(
				'LEFT',
				$db->quoteName('#__categories', 'c') . ' ON ' . $db->quoteName('c.id') . ' = ' . $db->quoteName('a.catid')
			);

		// Join over the associations.
		$assoc = JLanguageAssociations::isEnabled();

		if ($assoc)
		{
			$subQuery = $db->getQuery(true)
				->select('COUNT(' . $db->quoteName('asso1.id') . ') > 1')
				->from($db->quoteName('#__associations', 'asso1'))
				->join('INNER', $db->quoteName('#__associations', 'asso2') . ' ON ' . $db->quoteName('asso1.key') . ' = ' . $db->quoteName('asso2.key'))
				->where(
					array(
						$db->quoteName('asso1.id') . ' = ' . $db->quoteName('a.id'),
						$db->quoteName('asso1.context') . ' = ' . $db->quote('com_contact.item'),
					)
				);

			$query->select('(' . $subQuery . ') AS ' . $db->quoteName('association'));
		}

		// Filter by access level.
		if ($access = $this->getState('filter.access'))
		{
			$query->where($db->quoteName('a.access') . ' = ' . (int) $access);
		}

		// Implement View Level Access
		if (!$user->authorise('core.admin'))
		{
			$groups = implode(',', $user->getAuthorisedViewLevels());
			$query->where($db->quoteName('a.access') . ' IN (' . $groups . ')');
		}

		// Filter by published state
		$published = $this->getState('filter.published');

		if (is_numeric($published))
		{
			$query->where($db->quoteName('a.published') . ' = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(' . $db->quoteName('a.published') . ' = 0 OR ' . $db->quoteName('a.published') . ' = 1)');
		}

		// Filter by search in name.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where(
					'(' . $db->quoteName('a.name') . ' LIKE ' . $search . ' OR ' . $db->quoteName('a.alias') . ' LIKE ' . $search . ')'
				);
			}
		}

		// Filter on the language.
		if ($language = $this->getState('filter.language'))
		{
			$query->where($db->quoteName('a.language') . ' = ' . $db->quote($language));
		}

		// Filter by a single tag.
		$tagId = $this->getState('filter.tag');

		if (is_numeric($tagId))
		{
			$query->where($db->quoteName('tagmap.tag_id') . ' = ' . (int) $tagId)
				->join(
					'LEFT',
					$db->quoteName('#__contentitem_tag_map', 'tagmap')
					. ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id')
					. ' AND ' . $db->quoteName('tagmap.type_alias') . ' = ' . $db->quote('com_contact.contact')
				);
		}

		// Filter by categories and by level
		$categoryId = $this->getState('filter.category_id', array());
		$level = $this->getState('filter.level');

		if (!is_array($categoryId))
		{
			$categoryId = $categoryId ? array($categoryId) : array();
		}

		// Case: Using both categories filter and by level filter
		if (count($categoryId))
		{
			$categoryId = ArrayHelper::toInteger($categoryId);
			$categoryTable = JTable::getInstance('Category', 'JTable');
			$subCatItemsWhere = array();
		
			foreach ($categoryId as $filter_catid)
			{
				$categoryTable->load($filter_catid);
				$subCatItemsWhere[] = '(' .
					($level ? 'c.level <= ' . ((int) $level + (int) $categoryTable->level - 1) . ' AND ' : '') .
					'c.lft >= ' . (int) $categoryTable->lft . ' AND ' .
					'c.rgt <= ' . (int) $categoryTable->rgt . ')';
			}
		
			$query->where('(' . implode(' OR ', $subCatItemsWhere) . ')');
		}

		// Case: Using only the by level filter
		elseif ($level)
		{
			$query->where('c.level <= ' . (int) $level);
		}

		// Add the list ordering clause.
		$orderCol = $this->state->get('list.ordering', 'a.name');
		$orderDirn = $this->state->get('list.direction', 'asc');

		if ($orderCol == 'a.ordering' || $orderCol == 'category_title')
		{
			$orderCol = $db->quoteName('c.title') . ' ' . $orderDirn . ', ' . $db->quoteName('a.ordering');
		}

		$query->order($db->escape($orderCol . ' ' . $orderDirn));

		return $query;
	}
}
fields/usermessages.php000060400000003240152455702370011236 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_messages
 *
 * @copyright   (C) 2010 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JFormHelper::loadFieldClass('user');

/**
 * Supports a modal select of users that have access to com_messages
 *
 * @since  1.6
 */
class JFormFieldUserMessages extends JFormFieldUser
{
	/**
	 * The form field type.
	 *
	 * @var		string
	 * @since   1.6
	 */
	public $type = 'UserMessages';

	/**
	 * Method to get the filtering groups (null means no filtering)
	 *
	 * @return  array|null	array of filtering groups or null.
	 *
	 * @since   1.6
	 */
	protected function getGroups()
	{
		// Compute usergroups
		$db = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('id')
			->from('#__usergroups');
		$db->setQuery($query);

		try
		{
			$groups = $db->loadColumn();
		}
		catch (RuntimeException $e)
		{
			JError::raiseNotice(500, $e->getMessage());

			return null;
		}

		foreach ($groups as $i => $group)
		{
			if (JAccess::checkGroup($group, 'core.admin'))
			{
				continue;
			}

			if (!JAccess::checkGroup($group, 'core.manage', 'com_messages'))
			{
				unset($groups[$i]);
				continue;
			}

			if (!JAccess::checkGroup($group, 'core.login.admin'))
			{
				unset($groups[$i]);
				continue;
			}
		}

		return array_values($groups);
	}

	/**
	 * Method to get the users to exclude from the list of users
	 *
	 * @return  array|null array of users to exclude or null to to not exclude them
	 *
	 * @since   1.6
	 */
	protected function getExcluded()
	{
		return array(JFactory::getUser()->id);
	}
}
fields/messagestates.php000060400000001670152455702370011405 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_messages
 *
 * @copyright   (C) 2016 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('MessagesHelper', JPATH_ADMINISTRATOR . '/components/com_messages/helpers/messages.php');

JFormHelper::loadFieldClass('list');

/**
 * Message States field.
 *
 * @since  3.6.0
 */
class JFormFieldMessageStates extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var     string
	 * @since   3.6.0
	 */
	protected $type = 'MessageStates';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.6.0
	 */
	protected function getOptions()
	{
		// Merge state options with any additional options in the XML definition.
		return array_merge(parent::getOptions(), MessagesHelper::getStateOptions());
	}
}
config.php000060400000006555152455702370006543 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_messages
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Message configuration model.
 *
 * @since  1.6
 */
class MessagesModelConfig extends JModelForm
{
	/**
	 * Method to auto-populate the model state.
	 *
	 * This method should only be called once per instantiation and is designed
	 * to be called on the first call to the getState() method unless the model
	 * configuration flag to ignore the request is set.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$user = JFactory::getUser();

		$this->setState('user.id', $user->get('id'));

		// Load the parameters.
		$params = JComponentHelper::getParams('com_messages');
		$this->setState('params', $params);
	}

	/**
	 * Method to get a single record.
	 *
	 * @return  mixed  Object on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function &getItem()
	{
		$item = new JObject;

		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('cfg_name, cfg_value')
			->from('#__messages_cfg')
			->where($db->quoteName('user_id') . ' = ' . (int) $this->getState('user.id'));

		$db->setQuery($query);

		try
		{
			$rows = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		foreach ($rows as $row)
		{
			$item->set($row->cfg_name, $row->cfg_value);
		}

		$this->preprocessData('com_messages.config', $item);

		return $item;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm	 A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_messages.config', 'config', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		$db = $this->getDbo();

		if ($userId = (int) $this->getState('user.id'))
		{
			$query = $db->getQuery(true)
				->delete($db->quoteName('#__messages_cfg'))
				->where($db->quoteName('user_id') . '=' . (int) $userId);
			$db->setQuery($query);

			try
			{
				$db->execute();
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}

			if (count($data))
			{
				$query = $db->getQuery(true)
					->insert($db->quoteName('#__messages_cfg'))
					->columns($db->quoteName(array('user_id', 'cfg_name', 'cfg_value')));

				foreach ($data as $k => $v)
				{
					$query->values($userId . ', ' . $db->quote($k) . ', ' . $db->quote($v));
				}

				$db->setQuery($query);

				try
				{
					$db->execute();
				}
				catch (RuntimeException $e)
				{
					$this->setError($e->getMessage());

					return false;
				}
			}

			return true;
		}
		else
		{
			$this->setError('COM_MESSAGES_ERR_INVALID_USER');

			return false;
		}
	}
}
messages.php000060400000035633152455702370007104 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_postinstall
 *
 * @copyright   (C) 2013 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Model class to manage postinstall messages
 *
 * @since  3.2
 */
class PostinstallModelMessages extends FOFModel
{
	/**
	 * Builds the SELECT query
	 *
	 * @param   boolean  $overrideLimits  Are we requested to override the set limits?
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   3.2
	 */
	public function buildQuery($overrideLimits = false)
	{
		$query = parent::buildQuery($overrideLimits);

		$db = $this->getDbo();

		// Add a forced extension filtering to the list
		$eid = $this->getState('eid', 700);
		$query->where($db->qn('extension_id') . ' = ' . $db->q($eid));

		// Force filter only enabled messages
		$published = $this->getState('published', 1, 'int');
		$query->where($db->qn('enabled') . ' = ' . (int) $published);

		return $query;
	}

	/**
	 * Returns the name of an extension, as registered in the #__extensions table
	 *
	 * @param   integer  $eid  The extension ID
	 *
	 * @return  string  The extension name
	 *
	 * @since   3.2
	 */
	public function getExtensionName($eid)
	{
		// Load the extension's information from the database
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->select(array('name', 'element', 'client_id'))
			->from($db->qn('#__extensions'))
			->where($db->qn('extension_id') . ' = ' . (int) $eid);

		$db->setQuery($query, 0, 1);

		$extension = $db->loadObject();

		if (!is_object($extension))
		{
			return '';
		}

		// Load language files
		$basePath = JPATH_ADMINISTRATOR;

		if ($extension->client_id == 0)
		{
			$basePath = JPATH_SITE;
		}

		$lang = JFactory::getLanguage();
		$lang->load($extension->element, $basePath);

		// Return the localised name
		return JText::_(strtoupper($extension->name));
	}

	/**
	 * Resets all messages for an extension
	 *
	 * @param   integer  $eid  The extension ID whose messages we'll reset
	 *
	 * @return  mixed  False if we fail, a db cursor otherwise
	 *
	 * @since   3.2
	 */
	public function resetMessages($eid)
	{
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->update($db->qn('#__postinstall_messages'))
			->set($db->qn('enabled') . ' = 1')
			->where($db->qn('extension_id') . ' = ' . (int) $eid);
		$db->setQuery($query);

		return $db->execute();
	}

	/**
	 * Hides all messages for an extension
	 *
	 * @param   integer  $eid  The extension ID whose messages we'll hide
	 *
	 * @return  mixed  False if we fail, a db cursor otherwise
	 *
	 * @since   3.8.7
	 */
	public function hideMessages($eid)
	{
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->update($db->qn('#__postinstall_messages'))
			->set($db->qn('enabled') . ' = 0')
			->where($db->qn('extension_id') . ' = ' . (int) $eid);
		$db->setQuery($query);

		return $db->execute();
	}

	/**
	 * List post-processing. This is used to run the programmatic display
	 * conditions against each list item and decide if we have to show it or
	 * not.
	 *
	 * Do note that this a core method of the RAD Layer which operates directly
	 * on the list it's being fed. A little touch of modern magic.
	 *
	 * @param   array  &$resultArray  A list of items to process
	 *
	 * @return  void
	 *
	 * @since   3.2
	 */
	protected function onProcessList(&$resultArray)
	{
		$unset_keys          = array();
		$language_extensions = array();

		// Order the results DESC so the newest is on the top.
		$resultArray = array_reverse($resultArray);

		foreach ($resultArray as $key => $item)
		{
			// Filter out messages based on dynamically loaded programmatic conditions.
			if (!empty($item->condition_file) && !empty($item->condition_method))
			{
				jimport('joomla.filesystem.file');

				$file = FOFTemplateUtils::parsePath($item->condition_file, true);

				if (JFile::exists($file))
				{
					require_once $file;

					$result = call_user_func($item->condition_method);

					if ($result === false)
					{
						$unset_keys[] = $key;
					}
				}
			}

			// Load the necessary language files.
			if (!empty($item->language_extension))
			{
				$hash = $item->language_client_id . '-' . $item->language_extension;

				if (!in_array($hash, $language_extensions))
				{
					$language_extensions[] = $hash;
					JFactory::getLanguage()->load($item->language_extension, $item->language_client_id == 0 ? JPATH_SITE : JPATH_ADMINISTRATOR);
				}
			}
		}

		if (!empty($unset_keys))
		{
			foreach ($unset_keys as $key)
			{
				unset($resultArray[$key]);
			}
		}
	}

	/**
	 * Get the dropdown options for the list of component with post-installation messages
	 *
	 * @since 3.4
	 *
	 * @return  array  Compatible with JHtmlSelect::genericList
	 */
	public function getComponentOptions()
	{
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->select('extension_id')
			->from($db->qn('#__postinstall_messages'))
			->group(array($db->qn('extension_id')));
		$db->setQuery($query);
		$extension_ids = $db->loadColumn();

		$options = array();

		JFactory::getLanguage()->load('files_joomla.sys', JPATH_SITE, null, false, false);

		foreach ($extension_ids as $eid)
		{
			$options[] = JHtml::_('select.option', $eid, $this->getExtensionName($eid));
		}

		return $options;
	}

	/**
	 * Adds or updates a post-installation message (PIM) definition. You can use this in your post-installation script using this code:
	 *
	 * require_once JPATH_LIBRARIES . '/fof/include.php';
	 * FOFModel::getTmpInstance('Messages', 'PostinstallModel')->addPostInstallationMessage($options);
	 *
	 * The $options array contains the following mandatory keys:
	 *
	 * extension_id        The numeric ID of the extension this message is for (see the #__extensions table)
	 *
	 * type                One of message, link or action. Their meaning is:
	 *                         message  Informative message. The user can dismiss it.
	 *                         link     The action button links to a URL. The URL is defined in the action parameter.
	 *                         action   A PHP action takes place when the action button is clicked. You need to specify the action_file
	 *                                  (RAD path to the PHP file) and action (PHP function name) keys. See below for more information.
	 *
	 * title_key           The JText language key for the title of this PIM.
	 *                     Example: COM_FOOBAR_POSTINSTALL_MESSAGEONE_TITLE
	 *
	 * description_key     The JText language key for the main body (description) of this PIM
	 *                     Example: COM_FOOBAR_POSTINSTALL_MESSAGEONE_DESCRIPTION
	 *
	 * action_key          The JText language key for the action button. Ignored and not required when type=message
	 *                     Example: COM_FOOBAR_POSTINSTALL_MESSAGEONE_ACTION
	 *
	 * language_extension  The extension name which holds the language keys used above.
	 *                     For example, com_foobar, mod_something, plg_system_whatever, tpl_mytemplate
	 *
	 * language_client_id  Should we load the frontend (0) or backend (1) language keys?
	 *
	 * version_introduced  Which was the version of your extension where this message appeared for the first time?
	 *                     Example: 3.2.1
	 *
	 * enabled             Must be 1 for this message to be enabled. If you omit it, it defaults to 1.
	 *
	 * condition_file      The RAD path to a PHP file containing a PHP function which determines whether this message should be shown to
	 *                     the user. @see FOFTemplateUtils::parsePath() for RAD path format. Joomla! will include this file before calling
	 *                     the condition_method.
	 *                     Example:   admin://components/com_foobar/helpers/postinstall.php
	 *
	 * condition_method    The name of a PHP function which will be used to determine whether to show this message to the user. This must be
	 *                     a simple PHP user function (not a class method, static method etc) which returns true to show the message and false
	 *                     to hide it. This function is defined in the condition_file.
	 *                     Example: com_foobar_postinstall_messageone_condition
	 *
	 * When type=message no additional keys are required.
	 *
	 * When type=link the following additional keys are required:
	 *
	 * action  The URL which will open when the user clicks on the PIM's action button
	 *         Example:    index.php?option=com_foobar&view=tools&task=installSampleData
	 *
	 * When type=action the following additional keys are required:
	 *
	 * action_file  The RAD path to a PHP file containing a PHP function which performs the action of this PIM. @see FOFTemplateUtils::parsePath()
	 *              for RAD path format. Joomla! will include this file before calling the function defined in the action key below.
	 *              Example:   admin://components/com_foobar/helpers/postinstall.php
	 *
	 * action       The name of a PHP function which will be used to run the action of this PIM. This must be a simple PHP user function
	 *              (not a class method, static method etc) which returns no result.
	 *              Example: com_foobar_postinstall_messageone_action
	 *
	 * @param   array  $options  See description
	 *
	 * @return  $this
	 *
	 * @throws  Exception
	 */
	public function addPostInstallationMessage(array $options)
	{
		// Make sure there are options set
		if (!is_array($options))
		{
			throw new Exception('Post-installation message definitions must be of type array', 500);
		}

		// Initialise array keys
		$defaultOptions = array(
			'extension_id'       => '',
			'type'               => '',
			'title_key'          => '',
			'description_key'    => '',
			'action_key'         => '',
			'language_extension' => '',
			'language_client_id' => '',
			'action_file'        => '',
			'action'             => '',
			'condition_file'     => '',
			'condition_method'   => '',
			'version_introduced' => '',
			'enabled'            => '1',
		);

		$options = array_merge($defaultOptions, $options);

		// Array normalisation. Removes array keys not belonging to a definition.
		$defaultKeys = array_keys($defaultOptions);
		$allKeys     = array_keys($options);
		$extraKeys   = array_diff($allKeys, $defaultKeys);

		if (!empty($extraKeys))
		{
			foreach ($extraKeys as $key)
			{
				unset($options[$key]);
			}
		}

		// Normalisation of integer values
		$options['extension_id']       = (int) $options['extension_id'];
		$options['language_client_id'] = (int) $options['language_client_id'];
		$options['enabled']            = (int) $options['enabled'];

		// Normalisation of 0/1 values
		foreach (array('language_client_id', 'enabled') as $key)
		{
			$options[$key] = $options[$key] ? 1 : 0;
		}

		// Make sure there's an extension_id
		if (!(int) $options['extension_id'])
		{
			throw new Exception('Post-installation message definitions need an extension_id', 500);
		}

		// Make sure there's a valid type
		if (!in_array($options['type'], array('message', 'link', 'action')))
		{
			throw new Exception('Post-installation message definitions need to declare a type of message, link or action', 500);
		}

		// Make sure there's a title key
		if (empty($options['title_key']))
		{
			throw new Exception('Post-installation message definitions need a title key', 500);
		}

		// Make sure there's a description key
		if (empty($options['description_key']))
		{
			throw new Exception('Post-installation message definitions need a description key', 500);
		}

		// If the type is anything other than message you need an action key
		if (($options['type'] != 'message') && empty($options['action_key']))
		{
			throw new Exception('Post-installation message definitions need an action key when they are of type "' . $options['type'] . '"', 500);
		}

		// You must specify the language extension
		if (empty($options['language_extension']))
		{
			throw new Exception('Post-installation message definitions need to specify which extension contains their language keys', 500);
		}

		// The action file and method are only required for the "action" type
		if ($options['type'] == 'action')
		{
			if (empty($options['action_file']))
			{
				throw new Exception('Post-installation message definitions need an action file when they are of type "action"', 500);
			}

			$file_path = FOFTemplateUtils::parsePath($options['action_file'], true);

			if (!@is_file($file_path))
			{
				throw new Exception('The action file ' . $options['action_file'] . ' of your post-installation message definition does not exist', 500);
			}

			if (empty($options['action']))
			{
				throw new Exception('Post-installation message definitions need an action (function name) when they are of type "action"', 500);
			}
		}

		if ($options['type'] == 'link')
		{
			if (empty($options['link']))
			{
				throw new Exception('Post-installation message definitions need an action (URL) when they are of type "link"', 500);
			}
		}

		// The condition file and method are only required when the type is not "message"
		if ($options['type'] != 'message')
		{
			if (empty($options['condition_file']))
			{
				throw new Exception('Post-installation message definitions need a condition file when they are of type "' . $options['type'] . '"', 500);
			}

			$file_path = FOFTemplateUtils::parsePath($options['condition_file'], true);

			if (!@is_file($file_path))
			{
				throw new Exception('The condition file ' . $options['condition_file'] . ' of your post-installation message definition does not exist', 500);
			}

			if (empty($options['condition_method']))
			{
				throw new Exception(
					'Post-installation message definitions need a condition method (function name) when they are of type "'
					. $options['type'] . '"',
					500
				);
			}
		}

		// Check if the definition exists
		$table     = $this->getTable();
		$tableName = $table->getTableName();

		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->select('*')
			->from($db->qn($tableName))
			->where($db->qn('extension_id') . ' = ' . (int) $options['extension_id'])
			->where($db->qn('type') . ' = ' . $db->q($options['type']))
			->where($db->qn('title_key') . ' = ' . $db->q($options['title_key']));

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

		// Is the existing definition the same as the one we're trying to save?
		if (!empty($existingRow))
		{
			$same = true;

			foreach ($options as $k => $v)
			{
				if ($existingRow[$k] != $v)
				{
					$same = false;
					break;
				}
			}

			// Trying to add the same row as the existing one; quit
			if ($same)
			{
				return $this;
			}

			// Otherwise it's not the same row. Remove the old row before insert a new one.
			$query = $db->getQuery(true)
				->delete($db->qn($tableName))
				->where($db->q('extension_id') . ' = ' . (int) $options['extension_id'])
				->where($db->q('type') . ' = ' . $db->q($options['type']))
				->where($db->q('title_key') . ' = ' . $db->q($options['title_key']));

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

		// Insert the new row
		$options = (object) $options;
		$db->insertObject($tableName, $options);

		return $this;
	}
}
forms/message.xml000060400000001217152455702370010047 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="user_id_to"
			type="usermessages"
			label="COM_MESSAGES_FIELD_USER_ID_TO_LABEL"
			description="COM_MESSAGES_FIELD_USER_ID_TO_DESC"
			default="0"
			required="true" 
		/>

		<field
			name="subject"
			type="text"
			label="COM_MESSAGES_FIELD_SUBJECT_LABEL"
			description="COM_MESSAGES_FIELD_SUBJECT_DESC"
			required="true" 
		/>

		<field
			name="message"
			type="editor"
			label="COM_MESSAGES_FIELD_MESSAGE_LABEL"
			description="COM_MESSAGES_FIELD_MESSAGE_DESC"
			required="true"
			filter="JComponentHelper::filterText"
			buttons="false" 
		/>
	</fieldset>
</form>
forms/filter_messages.xml000060400000003052152455702370011576 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_MESSAGES_FILTER_SEARCH_LABEL"
			description="COM_MESSAGES_SEARCH_IN_SUBJECT"
			hint="JSEARCH_FILTER"
		/>
		<field
			name="state"
			type="messagestates"
			label="COM_MESSAGES_FILTER_STATES_LABEL"
			description="COM_MESSAGES_FILTER_STATES_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
			<option value="*">JALL</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="a.date_time DESC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.subject ASC">COM_MESSAGES_HEADING_SUBJECT_ASC</option>
			<option value="a.subject DESC">COM_MESSAGES_HEADING_SUBJECT_DESC</option>
			<option value="a.state ASC">COM_MESSAGES_HEADING_READ_ASC</option>
			<option value="a.state DESC">COM_MESSAGES_HEADING_READ_DESC</option>
			<option value="a.user_id_from ASC">COM_MESSAGES_HEADING_FROM_ASC</option>
			<option value="a.user_id_from DESC">COM_MESSAGES_HEADING_FROM_DESC</option>
			<option value="a.date_time ASC">JDATE_ASC</option>
			<option value="a.date_time DESC">JDATE_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="5"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/config.xml000060400000001451152455702370007670 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="lock"
			type="radio"
			label="COM_MESSAGES_FIELD_LOCK_LABEL"
			description="COM_MESSAGES_FIELD_LOCK_DESC"
			class="btn-group btn-group-yesno"
			default="0"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>

		<field
			name="mail_on_new"
			type="radio"
			label="COM_MESSAGES_FIELD_MAIL_ON_NEW_LABEL"
			description="COM_MESSAGES_FIELD_MAIL_ON_NEW_DESC"
			class="btn-group btn-group-yesno"
			default="1"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>

		<field
			name="auto_purge"
			type="number"
			label="COM_MESSAGES_FIELD_AUTO_PURGE_LABEL"
			description="COM_MESSAGES_FIELD_AUTO_PURGE_DESC" 
			size="6"
			default="7"
		/>
	</fieldset>
</form>
message.php000060400000032103152455702370006706 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_messages
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Router\Route;

/**
 * Private Message model.
 *
 * @since  1.6
 */
class MessagesModelMessage extends JModelAdmin
{
	/**
	 * Message
	 */
	protected $item;

	/**
	 * Method to auto-populate the model state.
	 *
	 * This method should only be called once per instantiation and is designed
	 * to be called on the first call to the getState() method unless the model
	 * configuration flag to ignore the request is set.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		parent::populateState();

		$input = JFactory::getApplication()->input;

		$user  = JFactory::getUser();
		$this->setState('user.id', $user->get('id'));

		$messageId = (int) $input->getInt('message_id');
		$this->setState('message.id', $messageId);

		$replyId = (int) $input->getInt('reply_id');
		$this->setState('reply.id', $replyId);
	}

	/**
	 * Check that recipient user is the one trying to delete and then call parent delete method
	 *
	 * @param   array  &$pks  An array of record primary keys.
	 *
	 * @return  boolean  True if successful, false if an error occurs.
	 *
	 * @since  3.1
	 */
	public function delete(&$pks)
	{
		$pks   = (array) $pks;
		$table = $this->getTable();
		$user  = JFactory::getUser();

		// Iterate the items to delete each one.
		foreach ($pks as $i => $pk)
		{
			if ($table->load($pk))
			{
				if ($table->user_id_to != $user->id)
				{
					// Prune items that you can't change.
					unset($pks[$i]);

					try
					{
						JLog::add(JText::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'), JLog::WARNING, 'jerror');
					}
					catch (RuntimeException $exception)
					{
						JFactory::getApplication()->enqueueMessage(JText::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'), 'warning');
					}

					return false;
				}
			}
			else
			{
				$this->setError($table->getError());

				return false;
			}
		}

		return parent::delete($pks);
	}

	/**
	 * Returns a Table object, always creating it.
	 *
	 * @param   type    $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A database object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'Message', $prefix = 'MessagesTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed    Object on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function getItem($pk = null)
	{
		if (!isset($this->item))
		{
			if ($this->item = parent::getItem($pk))
			{
				// Invalid message_id returns 0
				if ($this->item->user_id_to === '0')
				{
					$this->setError(JText::_('JERROR_ALERTNOAUTHOR'));

					return false;
				}

				// Prime required properties.
				if (empty($this->item->message_id))
				{
					// Prepare data for a new record.
					if ($replyId = $this->getState('reply.id'))
					{
						// If replying to a message, preload some data.
						$db    = $this->getDbo();
						$query = $db->getQuery(true)
							->select($db->quoteName(array('subject', 'user_id_from', 'user_id_to')))
							->from($db->quoteName('#__messages'))
							->where($db->quoteName('message_id') . ' = ' . (int) $replyId);

						try
						{
							$message = $db->setQuery($query)->loadObject();
						}
						catch (RuntimeException $e)
						{
							$this->setError($e->getMessage());

							return false;
						}

						if (!$message || $message->user_id_to != JFactory::getUser()->id)
						{
							$this->setError(JText::_('JERROR_ALERTNOAUTHOR'));

							return false;
						}

						$this->item->set('user_id_to', $message->user_id_from);
						$re = JText::_('COM_MESSAGES_RE');

						if (stripos($message->subject, $re) !== 0)
						{
							$this->item->set('subject', $re . ' ' . $message->subject);
						}
					}
				}
				elseif ($this->item->user_id_to != JFactory::getUser()->id)
				{
					$this->setError(JText::_('JERROR_ALERTNOAUTHOR'));

					return false;
				}
				else
				{
					// Mark message read
					$db    = $this->getDbo();
					$query = $db->getQuery(true)
						->update($db->quoteName('#__messages'))
						->set($db->quoteName('state') . ' = 1')
						->where($db->quoteName('message_id') . ' = ' . $this->item->message_id);
					$db->setQuery($query)->execute();
				}
			}

			// Get the user name for an existing message.
			if ($this->item->user_id_from && $fromUser = new JUser($this->item->user_id_from))
			{
				$this->item->set('from_user_name', $fromUser->name);
			}
		}

		return $this->item;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm   A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_messages.message', 'message', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_messages.edit.message.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		$this->preprocessData('com_messages.message', $data);

		return $data;
	}

	/**
	 * Checks that the current user matches the message recipient and calls the parent publish method
	 *
	 * @param   array    &$pks   A list of the primary keys to change.
	 * @param   integer  $value  The value of the published state.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   3.1
	 */
	public function publish(&$pks, $value = 1)
	{
		$user  = JFactory::getUser();
		$table = $this->getTable();
		$pks   = (array) $pks;

		// Check that the recipient matches the current user
		foreach ($pks as $i => $pk)
		{
			$table->reset();

			if ($table->load($pk))
			{
				if ($table->user_id_to != $user->id)
				{
					// Prune items that you can't change.
					unset($pks[$i]);

					try
					{
						JLog::add(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), JLog::WARNING, 'jerror');
					}
					catch (RuntimeException $exception)
					{
						JFactory::getApplication()->enqueueMessage(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), 'warning');
					}

					return false;
				}
			}
		}

		return parent::publish($pks, $value);
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		$table = $this->getTable();

		// Bind the data.
		if (!$table->bind($data))
		{
			$this->setError($table->getError());

			return false;
		}

		// Assign empty values.
		if (empty($table->user_id_from))
		{
			$table->user_id_from = JFactory::getUser()->get('id');
		}

		if ((int) $table->date_time == 0)
		{
			$table->date_time = JFactory::getDate()->toSql();
		}

		// Check the data.
		if (!$table->check())
		{
			$this->setError($table->getError());

			return false;
		}

		// Load the user details (already valid from table check).
		$toUser = \JUser::getInstance($table->user_id_to);

		// Check if recipient can access com_messages.
		if (!$toUser->authorise('core.login.admin') || !$toUser->authorise('core.manage', 'com_messages'))
		{
			$this->setError(\JText::_('COM_MESSAGES_ERROR_RECIPIENT_NOT_AUTHORISED'));

			return false;
		}

		// Load the recipient user configuration.
		$model  = JModelLegacy::getInstance('Config', 'MessagesModel', array('ignore_request' => true));
		$model->setState('user.id', $table->user_id_to);
		$config = $model->getItem();

		if (empty($config))
		{
			$this->setError($model->getError());

			return false;
		}

		if ($config->get('lock', false))
		{
			$this->setError(JText::_('COM_MESSAGES_ERR_SEND_FAILED'));

			return false;
		}

		// Store the data.
		if (!$table->store())
		{
			$this->setError($table->getError());

			return false;
		}

		if ($config->get('mail_on_new', true))
		{
			$fromUser         = JUser::getInstance($table->user_id_from);
			$debug            = JFactory::getConfig()->get('debug_lang');
			$default_language = JComponentHelper::getParams('com_languages')->get('administrator');
			$lang             = JLanguage::getInstance($toUser->getParam('admin_language', $default_language), $debug);
			$lang->load('com_messages', JPATH_ADMINISTRATOR);

			// Build the email subject and message
			$app      = JFactory::getApplication();
			$linkMode = $app->get('force_ssl', 0) >= 1 ? Route::TLS_FORCE : Route::TLS_IGNORE;
			$sitename = $app->get('sitename');
			$fromName = $fromUser->get('name');
			$siteURL  = JRoute::link('administrator', 'index.php?option=com_messages&view=message&message_id=' . $table->message_id, false, $linkMode, true);
			$subject  = html_entity_decode($table->subject, ENT_COMPAT, 'UTF-8');
			$message  = strip_tags(html_entity_decode($table->message, ENT_COMPAT, 'UTF-8'));

			$subj	  = sprintf($lang->_('COM_MESSAGES_NEW_MESSAGE'), $fromName, $sitename);
			$msg 	  = $subject . "\n\n" . $message . "\n\n" . sprintf($lang->_('COM_MESSAGES_PLEASE_LOGIN'), $siteURL);

			// Send the email
			$mailer = JFactory::getMailer();

			if (!$mailer->addReplyTo($fromUser->email, $fromUser->name))
			{
				try
				{
					JLog::add(JText::_('COM_MESSAGES_ERROR_COULD_NOT_SEND_INVALID_REPLYTO'), JLog::WARNING, 'jerror');
				}
				catch (RuntimeException $exception)
				{
					JFactory::getApplication()->enqueueMessage(JText::_('COM_MESSAGES_ERROR_COULD_NOT_SEND_INVALID_REPLYTO'), 'warning');
				}

				// The message is still saved in the database, we do not allow this failure to cause the entire save routine to fail
				return true;
			}

			if (!$mailer->addRecipient($toUser->email, $toUser->name))
			{
				try
				{
					JLog::add(JText::_('COM_MESSAGES_ERROR_COULD_NOT_SEND_INVALID_RECIPIENT'), JLog::WARNING, 'jerror');
				}
				catch (RuntimeException $exception)
				{
					JFactory::getApplication()->enqueueMessage(JText::_('COM_MESSAGES_ERROR_COULD_NOT_SEND_INVALID_RECIPIENT'), 'warning');
				}

				// The message is still saved in the database, we do not allow this failure to cause the entire save routine to fail
				return true;
			}

			$mailer->setSubject($subj);
			$mailer->setBody($msg);

			// The Send method will raise an error via JError on a failure, we do not need to check it ourselves here
			$mailer->Send();
		}

		return true;
	}

	/**
	 * Sends a message to the site's super users
	 *
	 * @param   string  $subject  The message subject
	 * @param   string  $message  The message
	 *
	 * @return  boolean
	 *
	 * @since   3.9.0
	 */
	public function notifySuperUsers($subject, $message, $fromUser = null)
	{
		$db = $this->getDbo();

		try
		{
			/** @var JTableAsset $table */
			$table  = $this->getTable('Asset', 'JTable');
			$rootId = $table->getRootId();

			/** @var JAccessRule[] $rules */
			$rules     = JAccess::getAssetRules($rootId)->getData();
			$rawGroups = $rules['core.admin']->getData();

			if (empty($rawGroups))
			{
				$this->setError(JText::_('COM_MESSAGES_ERROR_MISSING_ROOT_ASSET_GROUPS'));

				return false;
			}

			$groups = array();

			foreach ($rawGroups as $g => $enabled)
			{
				if ($enabled)
				{
					$groups[] = $db->quote($g);
				}
			}

			if (empty($groups))
			{
				$this->setError(JText::_('COM_MESSAGES_ERROR_NO_GROUPS_SET_AS_SUPER_USER'));

				return false;
			}

			$query = $db->getQuery(true)
				->select($db->quoteName('map.user_id'))
				->from($db->quoteName('#__user_usergroup_map', 'map'))
				->join('LEFT', $db->quoteName('#__users', 'u') . ' ON ' . $db->quoteName('u.id') . ' = ' . $db->quoteName('map.user_id'))
				->where($db->quoteName('map.group_id') . ' IN(' . implode(',', $groups) . ')')
				->where($db->quoteName('u.block') . ' = 0')
				->where($db->quoteName('u.sendEmail') . ' = 1');

			$userIDs = $db->setQuery($query)->loadColumn(0);

			if (empty($userIDs))
			{
				$this->setError(JText::_('COM_MESSAGES_ERROR_NO_USERS_SET_AS_SUPER_USER'));

				return false;
			}

			foreach ($userIDs as $id)
			{
				/*
				 * All messages must have a valid from user, we have use cases where an unauthenticated user may trigger this
				 * so we will set the from user as the to user
				 */
				$data = array(
					'user_id_from' => $id,
					'user_id_to'   => $id,
					'subject'      => $subject,
					'message'      => $message,
				);

				if (!$this->save($data))
				{
					return false;
				}
			}

			return true;
		}
		catch (Exception $exception)
		{
			$this->setError($exception->getMessage());

			return false;
		}
	}
}
fields/impmade.php000060400000002032152455702440010140 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Impressions field.
 *
 * @since  1.6
 */
class JFormFieldImpMade extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $type = 'ImpMade';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string	The field input markup.
	 *
	 * @since   1.6
	 */
	protected function getInput()
	{
		$onclick = ' onclick="document.getElementById(\'' . $this->id . '\').value=\'0\';"';

		return '<input class="input-small" type="text" name="' . $this->name . '" id="' . $this->id . '" value="'
			. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '" readonly="readonly" /> <a class="btn" ' . $onclick . '>'
			. '<span class="icon-refresh" aria-hidden="true"></span> ' . JText::_('COM_BANNERS_RESET_IMPMADE') . '</a>';
	}
}
fields/bannerclient.php000060400000001531152455702440011173 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('BannersHelper', JPATH_ADMINISTRATOR . '/components/com_banners/helpers/banners.php');

JFormHelper::loadFieldClass('list');

/**
 * Bannerclient field.
 *
 * @since  1.6
 */
class JFormFieldBannerClient extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $type = 'BannerClient';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   1.6
	 */
	public function getOptions()
	{
		return array_merge(parent::getOptions(), BannersHelper::getClientOptions());
	}
}
fields/clicks.php000060400000002022152455702440007773 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Clicks field.
 *
 * @since  1.6
 */
class JFormFieldClicks extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $type = 'Clicks';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string	The field input markup.
	 *
	 * @since   1.6
	 */
	protected function getInput()
	{
		$onclick = ' onclick="document.getElementById(\'' . $this->id . '\').value=\'0\';"';

		return '<input class="input-small" type="text" name="' . $this->name . '" id="' . $this->id . '" value="'
			. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '" readonly="readonly" /> <a class="btn" ' . $onclick . '>'
			. '<span class="icon-refresh" aria-hidden="true"></span> ' . JText::_('COM_BANNERS_RESET_CLICKS') . '</a>';
	}
}
fields/imptotal.php000060400000003046152455702440010363 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Total Impressions field.
 *
 * @since  1.6
 */
class JFormFieldImpTotal extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $type = 'ImpTotal';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string	The field input markup.
	 *
	 * @since   1.6
	 */
	protected function getInput()
	{
		$class    = ' class="validate-numeric text_area"';
		$onchange = ' onchange="document.getElementById(\'' . $this->id . '_unlimited\').checked=document.getElementById(\'' . $this->id
			. '\').value==\'\';"';
		$onclick  = ' onclick="if (document.getElementById(\'' . $this->id . '_unlimited\').checked) document.getElementById(\'' . $this->id
			. '\').value=\'\';"';
		$value    = empty($this->value) ? '' : $this->value;
		$checked  = empty($this->value) ? ' checked="checked"' : '';

		return '<input type="text" name="' . $this->name . '" id="' . $this->id . '" size="9" value="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8')
			. '" ' . $class . $onchange . ' />'
			. '<fieldset class="checkbox impunlimited"><input id="' . $this->id . '_unlimited" type="checkbox"' . $checked . $onclick . ' />'
			. '<label for="' . $this->id . '_unlimited" id="jform-imp" type="text">' . JText::_('COM_BANNERS_UNLIMITED') . '</label></fieldset>';
	}
}
clients.php000060400000017214152455702440006727 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Methods supporting a list of banner records.
 *
 * @since  1.6
 */
class BannersModelClients extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JControllerLegacy
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'name', 'a.name',
				'contact', 'a.contact',
				'state', 'a.state',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'purchase_type', 'a.purchase_type'
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.name', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.state', $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'string'));
		$this->setState('filter.purchase_type', $this->getUserStateFromRequest($this->context . '.filter.purchase_type', 'filter_purchase_type'));

		// Load the parameters.
		$this->setState('params', JComponentHelper::getParams('com_banners'));

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.state');
		$id .= ':' . $this->getState('filter.purchase_type');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db    = $this->getDbo();
		$query = $db->getQuery(true);

		$defaultPurchase = JComponentHelper::getParams('com_banners')->get('purchase_type', 3);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id AS id,'
				. 'a.name AS name,'
				. 'a.contact AS contact,'
				. 'a.checked_out AS checked_out,'
				. 'a.checked_out_time AS checked_out_time, '
				. 'a.state AS state,'
				. 'a.metakey AS metakey,'
				. 'a.purchase_type as purchase_type'
			)
		);

		$query->from($db->quoteName('#__banner_clients') . ' AS a');

		// Join over the banners for counting
		$query->select('COUNT(b.id) as nbanners')
			->join('LEFT', '#__banners AS b ON a.id = b.cid');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor')
			->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');

		// Filter by published state
		$published = $this->getState('filter.state');

		if (is_numeric($published))
		{
			$query->where('a.state = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.state IN (0, 1))');
		}

		$query->group('a.id, a.name, a.contact, a.checked_out, a.checked_out_time, a.state, a.metakey, a.purchase_type, uc.name');

		// Filter by search in title
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where('a.name LIKE ' . $search);
			}
		}

		// Filter by purchase type
		$purchaseType = $this->getState('filter.purchase_type');

		if (!empty($purchaseType))
		{
			if ($defaultPurchase == $purchaseType)
			{
				$query->where('(a.purchase_type = ' . (int) $purchaseType . ' OR a.purchase_type = -1)');
			}
			else
			{
				$query->where('a.purchase_type = ' . (int) $purchaseType);
			}
		}

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'a.name')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}

	/**
	 * Overrides the getItems method to attach additional metrics to the list.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   3.6
	 */
	public function getItems()
	{
		// Get a storage key.
		$store = $this->getStoreId('getItems');

		// Try to load the data from internal storage.
		if (!empty($this->cache[$store]))
		{
			return $this->cache[$store];
		}

		// Load the list items.
		$items = parent::getItems();

		// If empty or an error, just return.
		if (empty($items))
		{
			return array();
		}

		// Getting the following metric by joins is WAY TOO SLOW.
		// Faster to do three queries for very large banner trees.

		// Get the clients in the list.
		$db = $this->getDbo();
		$clientIds = ArrayHelper::getColumn($items, 'id');

		// Quote the strings.
		$clientIds = implode(
			',',
			array_map(array($db, 'quote'), $clientIds)
		);

		// Get the published banners count.
		$query = $db->getQuery(true)
			->select('cid, COUNT(cid) AS count_published')
			->from('#__banners')
			->where('state = 1')
			->where('cid IN (' . $clientIds . ')')
			->group('cid');

		$db->setQuery($query);

		try
		{
			$countPublished = $db->loadAssocList('cid', 'count_published');
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		// Get the unpublished banners count.
		$query->clear('where')
			->where('state = 0')
			->where('cid IN (' . $clientIds . ')');
		$db->setQuery($query);

		try
		{
			$countUnpublished = $db->loadAssocList('cid', 'count_published');
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		// Get the trashed banners count.
		$query->clear('where')
			->where('state = -2')
			->where('cid IN (' . $clientIds . ')');
		$db->setQuery($query);

		try
		{
			$countTrashed = $db->loadAssocList('cid', 'count_published');
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		// Get the archived banners count.
		$query->clear('where')
			->where('state = 2')
			->where('cid IN (' . $clientIds . ')');
		$db->setQuery($query);

		try
		{
			$countArchived = $db->loadAssocList('cid', 'count_published');
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		// Inject the values back into the array.
		foreach ($items as $item)
		{
			$item->count_published   = isset($countPublished[$item->id]) ? $countPublished[$item->id] : 0;
			$item->count_unpublished = isset($countUnpublished[$item->id]) ? $countUnpublished[$item->id] : 0;
			$item->count_trashed     = isset($countTrashed[$item->id]) ? $countTrashed[$item->id] : 0;
			$item->count_archived    = isset($countArchived[$item->id]) ? $countArchived[$item->id] : 0;
		}

		// Add the items to the internal cache.
		$this->cache[$store] = $items;

		return $this->cache[$store];
	}
}
tracks.php000060400000031761152455702440006560 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Archive\Archive;
use Joomla\String\StringHelper;

JLoader::register('BannersHelper', JPATH_ADMINISTRATOR . '/components/com_banners/helpers/banners.php');

/**
 * Methods supporting a list of tracks.
 *
 * @since  1.6
 */
class BannersModelTracks extends JModelList
{
	/**
	 * The base name
	 *
	 * @var    string
	 * @since  1.6
	 */
	protected $basename;

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JControllerLegacy
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'b.name', 'banner_name',
				'cl.name', 'client_name', 'client_id',
				'c.title', 'category_title', 'category_id',
				'track_type', 'a.track_type', 'type',
				'count', 'a.count',
				'track_date', 'a.track_date', 'end', 'begin',
				'level', 'c.level',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'b.name', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.category_id', $this->getUserStateFromRequest($this->context . '.filter.category_id', 'filter_category_id', '', 'cmd'));
		$this->setState('filter.client_id', $this->getUserStateFromRequest($this->context . '.filter.client_id', 'filter_client_id', '', 'cmd'));
		$this->setState('filter.type', $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'cmd'));
		$this->setState('filter.level', $this->getUserStateFromRequest($this->context . '.filter.level', 'filter_level', '', 'cmd'));
		$this->setState('filter.begin', $this->getUserStateFromRequest($this->context . '.filter.begin', 'filter_begin', '', 'string'));
		$this->setState('filter.end', $this->getUserStateFromRequest($this->context . '.filter.end', 'filter_end', '', 'string'));

		// Load the parameters.
		$this->setState('params', JComponentHelper::getParams('com_banners'));

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select($db->quoteName(array('a.track_date', 'a.track_type', 'a.count')))
			->select($db->quoteName('b.name', 'banner_name'))
			->select($db->quoteName('cl.name', 'client_name'))
			->select($db->quoteName('c.title', 'category_title'));

		// From tracks table.
		$query->from($db->quoteName('#__banner_tracks', 'a'));

		// Join with the banners.
		$query->join('LEFT', $db->quoteName('#__banners', 'b') . ' ON ' . $db->quoteName('b.id') . ' = ' . $db->quoteName('a.banner_id'));

		// Join with the client.
		$query->join('LEFT', $db->quoteName('#__banner_clients', 'cl') . ' ON ' . $db->quoteName('cl.id') . ' = ' . $db->quoteName('b.cid'));

		// Join with the category.
		$query->join('LEFT', $db->quoteName('#__categories', 'c') . ' ON ' . $db->quoteName('c.id') . ' = ' . $db->quoteName('b.catid'));

		// Filter by type.
		$type = $this->getState('filter.type');

		if (!empty($type))
		{
			$query->where($db->quoteName('a.track_type') . ' = ' . (int) $type);
		}

		// Filter by client.
		$clientId = $this->getState('filter.client_id');

		if (is_numeric($clientId))
		{
			$query->where($db->quoteName('b.cid') . ' = ' . (int) $clientId);
		}

		// Filter by category.
		$categoryId = $this->getState('filter.category_id');

		if (is_numeric($categoryId))
		{
			$query->where($db->quoteName('b.catid') . ' = ' . (int) $categoryId);
		}

		// Filter by begin date.

		$begin = $this->getState('filter.begin');

		if (!empty($begin))
		{
			$query->where($db->quoteName('a.track_date') . ' >= ' . $db->quote($begin));
		}

		// Filter by end date.
		$end = $this->getState('filter.end');

		if (!empty($end))
		{
			$query->where($db->quoteName('a.track_date') . ' <= ' . $db->quote($end));
		}

		// Filter on the level.
		if ($level = $this->getState('filter.level'))
		{
			$query->where($db->quoteName('c.level') . ' <= ' . (int) $level);
		}

		// Filter by search in banner name or client name.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			$search = $db->quote('%' . StringHelper::strtolower($search) . '%');
			$query->where('(LOWER(b.name) LIKE ' . $search . ' OR LOWER(cl.name) LIKE ' . $search . ')');
		}

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'b.name')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}

	/**
	 * Method to delete rows.
	 *
	 * @return  boolean  Returns true on success, false on failure.
	 */
	public function delete()
	{
		$user       = JFactory::getUser();
		$categoryId = $this->getState('category_id');

		// Access checks.
		if ($categoryId)
		{
			$allow = $user->authorise('core.delete', 'com_banners.category.' . (int) $categoryId);
		}
		else
		{
			$allow = $user->authorise('core.delete', 'com_banners');
		}

		if ($allow)
		{
			// Delete tracks from this banner
			$db    = $this->getDbo();
			$query = $db->getQuery(true)
				->delete($db->quoteName('#__banner_tracks'));

			// Filter by type
			$type = $this->getState('filter.type');

			if (!empty($type))
			{
				$query->where('track_type = ' . (int) $type);
			}

			// Filter by begin date
			$begin = $this->getState('filter.begin');

			if (!empty($begin))
			{
				$query->where('track_date >= ' . $db->quote($begin));
			}

			// Filter by end date
			$end = $this->getState('filter.end');

			if (!empty($end))
			{
				$query->where('track_date <= ' . $db->quote($end));
			}

			$where = '1 = 1';

			// Filter by client
			$clientId = $this->getState('filter.client_id');

			if (!empty($clientId))
			{
				$where .= ' AND cid = ' . (int) $clientId;
			}

			// Filter by category
			if (!empty($categoryId))
			{
				$where .= ' AND catid = ' . (int) $categoryId;
			}

			$query->where('banner_id IN (SELECT id FROM ' . $db->quoteName('#__banners') . ' WHERE ' . $where . ')');

			$db->setQuery($query);
			$this->setError((string) $query);

			try
			{
				$db->execute();
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}
		}
		else
		{
			JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));
		}

		return true;
	}

	/**
	 * Get file name
	 *
	 * @return  string  The file name
	 *
	 * @since   1.6
	 */
	public function getBaseName()
	{
		if (!isset($this->basename))
		{
			$basename   = str_replace('__SITE__', JFactory::getApplication()->get('sitename'), $this->getState('basename'));
			$categoryId = $this->getState('filter.category_id');

			if (is_numeric($categoryId))
			{
				if ($categoryId > 0)
				{
					$basename = str_replace('__CATID__', $categoryId, $basename);
				}
				else
				{
					$basename = str_replace('__CATID__', '', $basename);
				}

				$categoryName = $this->getCategoryName();
				$basename = str_replace('__CATNAME__', $categoryName, $basename);
			}
			else
			{
				$basename = str_replace(array('__CATID__', '__CATNAME__'), '', $basename);
			}

			$clientId = $this->getState('filter.client_id');

			if (is_numeric($clientId))
			{
				if ($clientId > 0)
				{
					$basename = str_replace('__CLIENTID__', $clientId, $basename);
				}
				else
				{
					$basename = str_replace('__CLIENTID__', '', $basename);
				}

				$clientName = $this->getClientName();
				$basename = str_replace('__CLIENTNAME__', $clientName, $basename);
			}
			else
			{
				$basename = str_replace(array('__CLIENTID__', '__CLIENTNAME__'), '', $basename);
			}

			$type = $this->getState('filter.type');

			if ($type > 0)
			{
				$basename = str_replace('__TYPE__', $type, $basename);
				$typeName = JText::_('COM_BANNERS_TYPE' . $type);
				$basename = str_replace('__TYPENAME__', $typeName, $basename);
			}
			else
			{
				$basename = str_replace(array('__TYPE__', '__TYPENAME__'), '', $basename);
			}

			$begin = $this->getState('filter.begin');

			if (!empty($begin))
			{
				$basename = str_replace('__BEGIN__', $begin, $basename);
			}
			else
			{
				$basename = str_replace('__BEGIN__', '', $basename);
			}

			$end = $this->getState('filter.end');

			if (!empty($end))
			{
				$basename = str_replace('__END__', $end, $basename);
			}
			else
			{
				$basename = str_replace('__END__', '', $basename);
			}

			$this->basename = $basename;
		}

		return $this->basename;
	}

	/**
	 * Get the category name.
	 *
	 * @return  string  The category name
	 *
	 * @since   1.6
	 */
	protected function getCategoryName()
	{
		$categoryId = $this->getState('filter.category_id');

		if ($categoryId)
		{
			$db    = $this->getDbo();
			$query = $db->getQuery(true)
				->select('title')
				->from($db->quoteName('#__categories'))
				->where($db->quoteName('id') . '=' . $db->quote($categoryId));
			$db->setQuery($query);

			try
			{
				$name = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}

			return $name;
		}

		return JText::_('COM_BANNERS_NOCATEGORYNAME');
	}

	/**
	 * Get the client name
	 *
	 * @return  string  The client name.
	 *
	 * @since   1.6
	 */
	protected function getClientName()
	{
		$clientId = $this->getState('filter.client_id');

		if ($clientId)
		{
			$db    = $this->getDbo();
			$query = $db->getQuery(true)
				->select('name')
				->from($db->quoteName('#__banner_clients'))
				->where($db->quoteName('id') . '=' . $db->quote($clientId));
			$db->setQuery($query);

			try
			{
				$name = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}

			return $name;
		}

		return JText::_('COM_BANNERS_NOCLIENTNAME');
	}

	/**
	 * Get the file type.
	 *
	 * @return  string  The file type
	 *
	 * @since   1.6
	 */
	public function getFileType()
	{
		return $this->getState('compressed') ? 'zip' : 'csv';
	}

	/**
	 * Get the mime type.
	 *
	 * @return  string  The mime type.
	 *
	 * @since   1.6
	 */
	public function getMimeType()
	{
		return $this->getState('compressed') ? 'application/zip' : 'text/csv';
	}

	/**
	 * Get the content
	 *
	 * @return  string  The content.
	 *
	 * @since   1.6
	 */
	public function getContent()
	{
		if (!isset($this->content))
		{
			$this->content = '"' . str_replace('"', '""', JText::_('COM_BANNERS_HEADING_NAME')) . '","'
				. str_replace('"', '""', JText::_('COM_BANNERS_HEADING_CLIENT')) . '","'
				. str_replace('"', '""', JText::_('JCATEGORY')) . '","'
				. str_replace('"', '""', JText::_('COM_BANNERS_HEADING_TYPE')) . '","'
				. str_replace('"', '""', JText::_('COM_BANNERS_HEADING_COUNT')) . '","'
				. str_replace('"', '""', JText::_('JDATE')) . '"' . "\n";

			foreach ($this->getItems() as $item)
			{
				$this->content .= '"' . str_replace('"', '""', $item->banner_name) . '","'
					. str_replace('"', '""', $item->client_name) . '","'
					. str_replace('"', '""', $item->category_title) . '","'
					. str_replace('"', '""', ($item->track_type == 1 ? JText::_('COM_BANNERS_IMPRESSION') : JText::_('COM_BANNERS_CLICK'))) . '","'
					. str_replace('"', '""', $item->count) . '","'
					. str_replace('"', '""', $item->track_date) . '"' . "\n";
			}

			if ($this->getState('compressed'))
			{
				$app = JFactory::getApplication('administrator');

				$files = array(
					'track' => array(
						'name' => $this->getBasename() . '.csv',
						'data' => $this->content,
						'time' => time()
					)
				);
				$ziproot = $app->get('tmp_path') . '/' . uniqid('banners_tracks_') . '.zip';

				// Run the packager
				jimport('joomla.filesystem.folder');
				jimport('joomla.filesystem.file');
				$delete = JFolder::files($app->get('tmp_path') . '/', uniqid('banners_tracks_'), false, true);

				if (!empty($delete))
				{
					if (!JFile::delete($delete))
					{
						// JFile::delete throws an error
						$this->setError(JText::_('COM_BANNERS_ERR_ZIP_DELETE_FAILURE'));

						return false;
					}
				}

				$archive = new Archive;

				if (!$packager = $archive->getAdapter('zip'))
				{
					$this->setError(JText::_('COM_BANNERS_ERR_ZIP_ADAPTER_FAILURE'));

					return false;
				}
				elseif (!$packager->create($ziproot, $files))
				{
					$this->setError(JText::_('COM_BANNERS_ERR_ZIP_CREATE_FAILURE'));

					return false;
				}

				$this->content = file_get_contents($ziproot);
			}
		}

		return $this->content;
	}
}
banners.php000060400000021130152455702440006706 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_banners
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\Utilities\ArrayHelper;

JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');

/**
 * Banners model for the Joomla Banners component.
 *
 * @since  1.6
 */
class BannersModelBanners extends JModelList
{
	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.tag_search');
		$id .= ':' . $this->getState('filter.client_id');
		$id .= ':' . serialize($this->getState('filter.category_id'));
		$id .= ':' . serialize($this->getState('filter.keywords'));

		return parent::getStoreId($id);
	}

	/**
	 * Method to get a JDatabaseQuery object for retrieving the data set from a database.
	 *
	 * @return  JDatabaseQuery   A JDatabaseQuery object to retrieve the data set.
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		$db         = $this->getDbo();
		$query      = $db->getQuery(true);
		$ordering   = $this->getState('filter.ordering');
		$tagSearch  = $this->getState('filter.tag_search');
		$cid        = $this->getState('filter.client_id');
		$categoryId = $this->getState('filter.category_id');
		$keywords   = $this->getState('filter.keywords');
		$randomise  = ($ordering === 'random');
		$nullDate   = $db->quote($db->getNullDate());
		$nowDate    = $db->quote(JFactory::getDate()->toSql());

		$query->select(
			'a.id as id,'
				. 'a.type as type,'
				. 'a.name as name,'
				. 'a.clickurl as clickurl,'
				. 'a.cid as cid,'
				. 'a.description as description,'
				. 'a.params as params,'
				. 'a.custombannercode as custombannercode,'
				. 'a.track_impressions as track_impressions,'
				. 'cl.track_impressions as client_track_impressions'
		)
			->from('#__banners as a')
			->join('LEFT', '#__banner_clients AS cl ON cl.id = a.cid')
			->where('a.state=1')
			->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')')
			->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')')
			->where('(a.imptotal = 0 OR a.impmade < a.imptotal)');

		if ($cid)
		{
			$query->where('a.cid = ' . (int) $cid)
				->where('cl.state = 1');
		}

		// Filter by a single or group of categories
		if (is_numeric($categoryId))
		{
			$type = $this->getState('filter.category_id.include', true) ? '= ' : '<> ';

			// Add subcategory check
			$includeSubcategories = $this->getState('filter.subcategories', false);
			$categoryEquals = 'a.catid ' . $type . (int) $categoryId;

			if ($includeSubcategories)
			{
				$levels = (int) $this->getState('filter.max_category_levels', '1');

				// Create a subquery for the subcategory list
				$subQuery = $db->getQuery(true);
				$subQuery->select('sub.id')
					->from('#__categories as sub')
					->join('INNER', '#__categories as this ON sub.lft > this.lft AND sub.rgt < this.rgt')
					->where('this.id = ' . (int) $categoryId)
					->where('sub.level <= this.level + ' . $levels);

				// Add the subquery to the main query
				$query->where('(' . $categoryEquals . ' OR a.catid IN (' . (string) $subQuery . '))');
			}
			else
			{
				$query->where($categoryEquals);
			}
		}
		elseif (is_array($categoryId) && (count($categoryId) > 0))
		{
			$categoryId = ArrayHelper::toInteger($categoryId);
			$categoryId = implode(',', $categoryId);

			if ($categoryId != '0')
			{
				$type = $this->getState('filter.category_id.include', true) ? 'IN' : 'NOT IN';
				$query->where('a.catid ' . $type . ' (' . $categoryId . ')');
			}
		}

		if ($tagSearch)
		{
			if (!$keywords)
			{
				$query->where('0 != 0');
			}
			else
			{
				$temp   = array();
				$config = JComponentHelper::getParams('com_banners');
				$prefix = $config->get('metakey_prefix');

				if ($categoryId)
				{
					$query->join('LEFT', '#__categories as cat ON a.catid = cat.id');
				}

				foreach ($keywords as $keyword)
				{
					$condition1 = 'a.own_prefix=1 '
						. ' AND a.metakey_prefix=SUBSTRING(' . $db->quote($keyword) . ',1,LENGTH( a.metakey_prefix)) '
						. ' OR a.own_prefix=0 '
						. ' AND cl.own_prefix=1 '
						. ' AND cl.metakey_prefix=SUBSTRING(' . $db->quote($keyword) . ',1,LENGTH(cl.metakey_prefix)) '
						. ' OR a.own_prefix=0 '
						. ' AND cl.own_prefix=0 '
						. ' AND ' . ($prefix == substr($keyword, 0, strlen($prefix)) ? '0 = 0' : '0 != 0');

					$regexp = $db->quote("[[:<:]]" . $db->escape($keyword) . "[[:>:]]");
					$condition2 = "a.metakey " . $query->regexp($regexp) . " ";

					if ($cid)
					{
						$condition2 .= " OR cl.metakey " . $query->regexp($regexp) . " ";
					}

					if ($categoryId)
					{
						$condition2 .= " OR cat.metakey " . $query->regexp($regexp) . " ";
					}

					$temp[] = "($condition1) AND ($condition2)";
				}

				$query->where('(' . implode(' OR ', $temp) . ')');
			}
		}

		// Filter by language
		if ($this->getState('filter.language'))
		{
			$query->where('a.language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		}

		$query->order('a.sticky DESC,' . ($randomise ? $query->Rand() : 'a.ordering'));

		return $query;
	}

	/**
	 * Get a list of banners.
	 *
	 * @return  array
	 *
	 * @since   1.6
	 */
	public function getItems()
	{
		if ($this->getState('filter.tag_search'))
		{
			// Filter out empty keywords.
			$keywords = array_values(array_filter(array_map('trim', $this->getState('filter.keywords')), 'strlen'));

			// Re-set state before running the query.
			$this->setState('filter.keywords', $keywords);

			// If no keywords are provided, avoid running the query.
			if (!$keywords)
			{
				$this->cache['items'] = array();

				return $this->cache['items'];
			}
		}

		if (!isset($this->cache['items']))
		{
			$this->cache['items'] = parent::getItems();

			foreach ($this->cache['items'] as &$item)
			{
				$item->params = new Registry($item->params);
			}
		}

		return $this->cache['items'];
	}

	/**
	 * Makes impressions on a list of banners
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function impress()
	{
		$trackDate = JFactory::getDate()->format('Y-m-d H:00:00');
		$trackDate = JFactory::getDate($trackDate)->toSql();

		$items     = $this->getItems();
		$db        = $this->getDbo();
		$query     = $db->getQuery(true);

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

		foreach ($items as $item)
		{
			$bid[] = (int) $item->id;
		}

		// Increment impression made
		$query->clear()
			->update('#__banners')
			->set('impmade = (impmade + 1)')
			->where('id IN (' . implode(',', $bid) . ')');
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (JDatabaseExceptionExecuting $e)
		{
			JError::raiseError(500, $e->getMessage());
		}

		foreach ($items as $item)
		{
			// Track impressions
			$trackImpressions = $item->track_impressions;

			if ($trackImpressions < 0 && $item->cid)
			{
				$trackImpressions = $item->client_track_impressions;
			}

			if ($trackImpressions < 0)
			{
				$config           = JComponentHelper::getParams('com_banners');
				$trackImpressions = $config->get('track_impressions');
			}

			if ($trackImpressions > 0)
			{
				// Is track already created?
				// Update count
				$query->clear();
				$query->update('#__banner_tracks')
					->set($db->quoteName('count') . ' = (' . $db->quoteName('count') . ' + 1)')
					->where('track_type=1')
					->where('banner_id=' . (int) $item->id)
					->where('track_date=' . $db->quote($trackDate));

				$db->setQuery($query);

				try
				{
					$db->execute();
				}
				catch (JDatabaseExceptionExecuting $e)
				{
					JError::raiseError(500, $e->getMessage());
				}

				if ($db->getAffectedRows() === 0)
				{
					// Insert new count
					$query->clear();

					$query->insert('#__banner_tracks')
						->columns(
							array(
								$db->quoteName('count'), $db->quoteName('track_type'),
								$db->quoteName('banner_id'), $db->quoteName('track_date')
							)
						)
						->values('1, 1, ' . (int) $item->id . ', ' . $db->quote($trackDate));

					$db->setQuery($query);

					try
					{
						$db->execute();
					}
					catch (JDatabaseExceptionExecuting $e)
					{
						JError::raiseError(500, $e->getMessage());
					}
				}
			}
		}
	}
}
banner.php000060400000010221152455702440006522 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_banners
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');

/**
 * Banner model for the Joomla Banners component.
 *
 * @since  1.5
 */
class BannersModelBanner extends JModelLegacy
{
	/**
	 * Cached item object
	 *
	 * @var    object
	 * @since  1.6
	 */
	protected $_item;

	/**
	 * Clicks the URL, incrementing the counter
	 *
	 * @return  void
	 *
	 * @since   1.5
	 */
	public function click()
	{
		$item = $this->getItem();

		if (empty($item))
		{
			throw new Exception(JText::_('JERROR_PAGE_NOT_FOUND'), 404);
		}

		$id = $this->getState('banner.id');

		// Update click count
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->update('#__banners')
			->set('clicks = (clicks + 1)')
			->where('id = ' . (int) $id);

		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (RuntimeException $e)
		{
			JError::raiseError(500, $e->getMessage());
		}

		// Track clicks
		$trackClicks = $item->track_clicks;

		if ($trackClicks < 0 && $item->cid)
		{
			$trackClicks = $item->client_track_clicks;
		}

		if ($trackClicks < 0)
		{
			$config = JComponentHelper::getParams('com_banners');
			$trackClicks = $config->get('track_clicks');
		}

		if ($trackClicks > 0)
		{
			$trackDate = JFactory::getDate()->format('Y-m-d H:00:00');
			$trackDate = JFactory::getDate($trackDate)->toSql();

			$query->clear()
				->select($db->quoteName('count'))
				->from('#__banner_tracks')
				->where('track_type=2')
				->where('banner_id=' . (int) $id)
				->where('track_date=' . $db->quote($trackDate));

			$db->setQuery($query);

			try
			{
				$db->execute();
			}
			catch (RuntimeException $e)
			{
				JError::raiseError(500, $e->getMessage());
			}

			$count = $db->loadResult();

			$query->clear();

			if ($count)
			{
				// Update count
				$query->update('#__banner_tracks')
					->set($db->quoteName('count') . ' = (' . $db->quoteName('count') . ' + 1)')
					->where('track_type=2')
					->where('banner_id=' . (int) $id)
					->where('track_date=' . $db->quote($trackDate));
			}
			else
			{
				// Insert new count
				$query->insert('#__banner_tracks')
					->columns(
						array(
							$db->quoteName('count'), $db->quoteName('track_type'),
							$db->quoteName('banner_id'), $db->quoteName('track_date')
						)
					)
					->values('1, 2,' . (int) $id . ',' . $db->quote($trackDate));
			}

			$db->setQuery($query);

			try
			{
				$db->execute();
			}
			catch (RuntimeException $e)
			{
				JError::raiseError(500, $e->getMessage());
			}
		}
	}

	/**
	 * Get the data for a banner.
	 *
	 * @return  object
	 *
	 * @since   1.6
	 */
	public function &getItem()
	{
		if (!isset($this->_item))
		{
			/** @var JCacheControllerCallback $cache */
			$cache = JFactory::getCache('com_banners', 'callback');

			$id = $this->getState('banner.id');

			// For PHP 5.3 compat we can't use $this in the lambda function below, so grab the database driver now to use it
			$db = $this->getDbo();

			$loader = function ($id) use ($db)
			{
				$query = $db->getQuery(true)
					->select(
						array(
							$db->quoteName('a.clickurl', 'clickurl'),
							$db->quoteName('a.cid', 'cid'),
							$db->quoteName('a.track_clicks', 'track_clicks'),
							$db->quoteName('cl.track_clicks', 'client_track_clicks'),
						)
					)
					->from($db->quoteName('#__banners', 'a'))
					->join('LEFT', '#__banner_clients AS cl ON cl.id = a.cid')
					->where('a.id = ' . (int) $id);

				$db->setQuery($query);

				return $db->loadObject();
			};

			try
			{
				$this->_item = $cache->get($loader, array($id), md5(__METHOD__ . $id));
			}
			catch (JCacheException $e)
			{
				$this->_item = $loader($id);
			}
		}

		return $this->_item;
	}

	/**
	 * Get the URL for a banner
	 *
	 * @return  string
	 *
	 * @since   1.5
	 */
	public function getUrl()
	{
		$item = $this->getItem();
		$url = $item->clickurl;

		// Check for links
		if (!preg_match('#http[s]?://|index[2]?\.php#', $url))
		{
			$url = "http://$url";
		}

		return $url;
	}
}
client.php000060400000006522152455702440006544 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Client model.
 *
 * @since  1.6
 */
class BannersModelClient extends JModelAdmin
{
	/**
	 * The type alias for this content type.
	 *
	 * @var    string
	 * @since  3.2
	 */
	public $typeAlias = 'com_banners.client';

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 *
	 * @since   1.6
	 */
	protected function canDelete($record)
	{
		if (empty($record->id) || $record->state != -2)
		{
			return false;
		}

		if (!empty($record->catid))
		{
			return JFactory::getUser()->authorise('core.delete', 'com_banners.category.' . (int) $record->catid);
		}

		return parent::canDelete($record);
	}

	/**
	 * Method to test whether a record can have its state changed.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record.
	 *                   Defaults to the permission set in the component.
	 *
	 * @since   1.6
	 */
	protected function canEditState($record)
	{
		$user = JFactory::getUser();

		if (!empty($record->catid))
		{
			return $user->authorise('core.edit.state', 'com_banners.category.' . (int) $record->catid);
		}

		return $user->authorise('core.edit.state', 'com_banners');
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable	A JTable object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'Client', $prefix = 'BannersTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm|boolean  A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_banners.client', 'client', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_banners.edit.client.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		$this->preprocessData('com_banners.client', $data);

		return $data;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @param   JTable  $table  A JTable object.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function prepareTable($table)
	{
		$table->name = htmlspecialchars_decode($table->name, ENT_QUOTES);
	}
}
forms/banner.xml000060400000020526152455702440007672 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset name="details" addfieldpath="/administrator/components/com_banners/models/fields">

		<field
			name="id"
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			default="0"
			readonly="true"
			class="readonly"
		/>

		<field
			name="name"
			type="text"
			label="COM_BANNERS_FIELD_NAME_LABEL"
			description="COM_BANNERS_FIELD_NAME_DESC"
			class="input-xxlarge input-large-text"
			size="40"
			required="true"
		/>

		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="COM_BANNERS_FIELD_ALIAS_DESC"
			size="40"
			hint="JFIELD_ALIAS_PLACEHOLDER"
		/>

		<field
			name="catid"
			type="categoryedit"
			label="JCATEGORY"
			description="COM_BANNERS_FIELD_CATEGORY_DESC"
			extension="com_banners"
			required="true"
			addfieldpath="/administrator/components/com_categories/models/fields"
			default=""
		/>

		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="COM_BANNERS_FIELD_STATE_DESC"
			class="chzn-color-state"
			size="1"
			default="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="2">JARCHIVED</option>
			<option value="-2">JTRASHED</option>
		</field>

		<field
			name="ordering"
			type="ordering"
			label="JFIELD_ORDERING_LABEL"
			description="JFIELD_ORDERING_DESC"
			table="#__banners"
		/>

		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="COM_BANNERS_FIELD_LANGUAGE_DESC"
			>
			<option value="*">JALL</option>
		</field>

		<field
			name="version_note"
			type="text"
			label="JGLOBAL_FIELD_VERSION_NOTE_LABEL"
			description="JGLOBAL_FIELD_VERSION_NOTE_DESC"
			maxlength="255"
			class="span12"
			size="45"
			labelclass="control-label"
		/>

		<field
			name="description"
			type="editor"
			label="JGLOBAL_DESCRIPTION"
			description="COM_BANNERS_FIELD_DESCRIPTION_DESC"
			filter="JComponentHelper::filterText"
			buttons="true"
			hide="readmore,pagebreak,module,article,contact,menu"
		/>

		<field
			name="type"
			type="list"
			label="COM_BANNERS_FIELD_TYPE_LABEL"
			description="COM_BANNERS_FIELD_TYPE_DESC"
			default="0"
			>
			<option value="0">COM_BANNERS_FIELD_VALUE_IMAGE</option>
			<option value="1">COM_BANNERS_FIELD_VALUE_CUSTOM</option>
		</field>

		<field
			name="custombannercode"
			type="textarea"
			label="COM_BANNERS_FIELD_CUSTOMCODE_LABEL"
			description="COM_BANNERS_FIELD_CUSTOMCODE_DESC"
			rows="3"
			cols="30"
			filter="raw"
		/>

		<field
			name="clickurl"
			type="url"
			label="COM_BANNERS_FIELD_CLICKURL_LABEL"
			description="COM_BANNERS_FIELD_CLICKURL_DESC"
			filter="url"
			validate="url"
		/>
	</fieldset>

	<fieldset name="publish" label="COM_BANNERS_GROUP_LABEL_PUBLISHING_DETAILS">

		<field
			name="created"
			type="calendar"
			label="COM_BANNERS_FIELD_CREATED_LABEL"
			description="COM_BANNERS_FIELD_CREATED_DESC"
			size="22"
			translateformat="true"
			showtime="true"
			filter="user_utc"
		/>

		<field
			name="created_by"
			type="user"
			label="COM_BANNERS_FIELD_CREATED_BY_LABEL"
			description="COM_BANNERS_FIELD_CREATED_BY_DESC"
		/>

		<field
			name="created_by_alias"
			type="text"
			label="COM_BANNERS_FIELD_CREATED_BY_ALIAS_LABEL"
			description="COM_BANNERS_FIELD_CREATED_BY_ALIAS_DESC"
			size="20"
		/>

		<field
			name="modified"
			type="calendar"
			label="JGLOBAL_FIELD_MODIFIED_LABEL"
			description="COM_BANNERS_FIELD_MODIFIED_DESC"
			class="readonly"
			size="22"
			readonly="true"
			translateformat="true"
			showtime="true"
			filter="user_utc"
		/>

		<field
			name="modified_by"
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			description="COM_BANNERS_FIELD_MODIFIED_BY_DESC"
			class="readonly"
			readonly="true"
			filter="unset"
		/>

		<field
			name="version"
			type="text"
			label="COM_BANNERS_FIELD_VERSION_LABEL"
			description="COM_BANNERS_FIELD_VERSION_DESC"
			class="readonly"
			size="6"
			readonly="true"
			filter="unset"
		/>

		<field
			name="publish_up"
			type="calendar"
			label="COM_BANNERS_FIELD_PUBLISH_UP_LABEL"
			description="COM_BANNERS_FIELD_PUBLISH_UP_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="publish_down"
			type="calendar"
			label="COM_BANNERS_FIELD_PUBLISH_DOWN_LABEL"
			description="COM_BANNERS_FIELD_PUBLISH_DOWN_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>
	</fieldset>

	<fieldset name="bannerdetails" label="COM_BANNERS_GROUP_LABEL_BANNER_DETAILS">

		<field
			name="sticky"
			type="radio"
			label="COM_BANNERS_FIELD_STICKY_LABEL"
			description="COM_BANNERS_FIELD_STICKY_DESC"
			default="0"
			class="btn-group btn-group-yesno"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
	</fieldset>

	<fieldset name="otherparams">
		<field
			name="imptotal"
			type="imptotal"
			label="COM_BANNERS_FIELD_IMPTOTAL_LABEL"
			description="COM_BANNERS_FIELD_IMPTOTAL_DESC"
			default="0"
		/>

		<field
			name="impmade"
			type="impmade"
			label="COM_BANNERS_FIELD_IMPMADE_LABEL"
			description="COM_BANNERS_FIELD_IMPMADE_DESC"
			default="0"
		/>

		<field
			name="clicks"
			type="clicks"
			label="COM_BANNERS_FIELD_CLICKS_LABEL"
			description="COM_BANNERS_FIELD_CLICKS_DESC"
			default="0"
		/>

		<field
			name="cid"
			type="bannerclient"
			label="COM_BANNERS_FIELD_CLIENT_LABEL"
			description="COM_BANNERS_FIELD_CLIENT_DESC"
		/>

		<field
			name="purchase_type"
			type="list"
			label="COM_BANNERS_FIELD_PURCHASETYPE_LABEL"
			description="COM_BANNERS_FIELD_PURCHASETYPE_DESC"
			default="0"
			>
			<option value="-1">COM_BANNERS_FIELD_VALUE_USECLIENTDEFAULT</option>
			<option value="1">COM_BANNERS_FIELD_VALUE_UNLIMITED</option>
			<option value="2">COM_BANNERS_FIELD_VALUE_YEARLY</option>
			<option value="3">COM_BANNERS_FIELD_VALUE_MONTHLY</option>
			<option value="4">COM_BANNERS_FIELD_VALUE_WEEKLY</option>
			<option value="5">COM_BANNERS_FIELD_VALUE_DAILY</option>
		</field>

		<field
			name="track_impressions"
			type="list"
			label="COM_BANNERS_FIELD_TRACKIMPRESSION_LABEL"
			description="COM_BANNERS_FIELD_TRACKIMPRESSION_DESC"
			default="0"
			>
			<option value="-1">COM_BANNERS_FIELD_VALUE_USECLIENTDEFAULT</option>
			<option value="0">JNO</option>
			<option value="1">JYES</option>
		</field>

		<field
			name="track_clicks"
			type="list"
			label="COM_BANNERS_FIELD_TRACKCLICK_LABEL"
			description="COM_BANNERS_FIELD_TRACKCLICK_DESC"
			default="0"
			>
			<option value="-1">COM_BANNERS_FIELD_VALUE_USECLIENTDEFAULT</option>
			<option value="0">JNO</option>
			<option value="1">JYES</option>
		</field>
	</fieldset>

	<fieldset name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">

		<field
			name="metakey"
			type="textarea"
			label="JFIELD_META_KEYWORDS_LABEL"
			description="COM_BANNERS_FIELD_METAKEYWORDS_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="own_prefix"
			type="radio"
			label="COM_BANNERS_FIELD_BANNEROWNPREFIX_LABEL"
			description="COM_BANNERS_FIELD_BANNEROWNPREFIX_DESC"
			class="btn-group btn-group-yesno"
			default="0"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>

		<field
			name="metakey_prefix"
			type="text"
			label="COM_BANNERS_FIELD_METAKEYWORDPREFIX_LABEL"
			description="COM_BANNERS_FIELD_METAKEYWORDPREFIX_DESC"
		/>
	</fieldset>

	<fields name="params" label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS">
		<fieldset name="image">
			<field
				name="imageurl"
				type="media"
				label="COM_BANNERS_FIELD_IMAGE_LABEL"
				description="COM_BANNERS_FIELD_IMAGE_DESC"
				directory="banners"
				hide_none="1"
				size="40"
			/>

			<field
				name="width"
				type="number"
				label="COM_BANNERS_FIELD_WIDTH_LABEL"
				description="COM_BANNERS_FIELD_WIDTH_DESC"
				class="input-mini validate-numeric"
			/>

			<field
				name="height"
				type="number"
				label="COM_BANNERS_FIELD_HEIGHT_LABEL"
				description="COM_BANNERS_FIELD_HEIGHT_DESC"
				class="input-mini validate-numeric"
			/>

			<field
				name="alt"
				type="text"
				label="COM_BANNERS_FIELD_ALT_LABEL"
				description="COM_BANNERS_FIELD_ALT_DESC"
			/>
		</fieldset>
	</fields>

	<fieldset name="custom">
		<field
			name="bannercode"
			type="textarea"
			label="COM_BANNERS_FIELD_CUSTOMCODE_LABEL"
			description="COM_BANNERS_FIELD_CUSTOMCODE_DESC"
			rows="3"
			cols="30"
			filter="raw"
		/>
	</fieldset>

</form>
forms/client.xml000060400000007033152455702440007701 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset name="details" addfieldpath="/administrator/components/com_banners/models/fields">
		<field
			name="id"
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			default="0"
			readonly="true"
			class="readonly"
		/>

		<field
			name="name"
			type="text"
			label="COM_BANNERS_FIELD_NAME_LABEL"
			description="COM_BANNERS_FIELD_CLIENT_NAME_DESC"
			class="input-xxlarge input-large-text"
			size="40"
			required="true"
		/>

		<field
			name="contact"
			type="text"
			label="COM_BANNERS_FIELD_CONTACT_LABEL"
			description="COM_BANNERS_FIELD_CONTACT_DESC"
			size="40"
			required="true"
		/>

		<field
			name="email"
			type="email"
			label="COM_BANNERS_FIELD_EMAIL_LABEL"
			description="COM_BANNERS_FIELD_EMAIL_DESC"
			size="40"
			validate="email"
		/>

		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="COM_BANNERS_FIELD_CLIENT_STATE_DESC"
			class="chzn-color-state"
			size="1"
			default="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="2">JARCHIVED</option>
			<option value="-2">JTRASHED</option>
		</field>

		<field
			name="version_note"
			type="text"
			label="JGLOBAL_FIELD_VERSION_NOTE_LABEL"
			description="JGLOBAL_FIELD_VERSION_NOTE_DESC"
			maxlength="255"
			size="45"
			labelclass="control-label"
		/>

		<field
			name="purchase_type"
			type="list"
			label="COM_BANNERS_FIELD_PURCHASETYPE_LABEL"
			description="COM_BANNERS_FIELD_PURCHASETYPE_DESC"
			default="0"
			>
			<option value="-1">JGLOBAL_USE_GLOBAL</option>
			<option value="1">COM_BANNERS_FIELD_VALUE_UNLIMITED</option>
			<option value="2">COM_BANNERS_FIELD_VALUE_YEARLY</option>
			<option value="3">COM_BANNERS_FIELD_VALUE_MONTHLY</option>
			<option value="4">COM_BANNERS_FIELD_VALUE_WEEKLY</option>
			<option value="5">COM_BANNERS_FIELD_VALUE_DAILY</option>
		</field>

		<field
			name="track_impressions"
			type="list"
			label="COM_BANNERS_FIELD_TRACKIMPRESSION_LABEL"
			description="COM_BANNERS_FIELD_TRACKIMPRESSION_DESC"
			default="0"
			class="chzn-color"
			>
			<option value="-1">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JNO</option>
			<option value="1">JYES</option>
		</field>

		<field
			name="track_clicks"
			type="list"
			label="COM_BANNERS_FIELD_TRACKCLICK_LABEL"
			description="COM_BANNERS_FIELD_TRACKCLICK_DESC"
			default="0"
			class="chzn-color"
			>
			<option value="-1">JGLOBAL_USE_GLOBAL</option>
			<option value="0">JNO</option>
			<option value="1">JYES</option>
		</field>

	</fieldset>

	<fieldset name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">
		<field
			name="metakey"
			type="textarea"
			label="JFIELD_META_KEYWORDS_LABEL"
			description="COM_BANNERS_FIELD_CLIENT_METAKEYWORDS_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="own_prefix"
			type="radio"
			label="COM_BANNERS_FIELD_CLIENTOWNPREFIX_LABEL"
			description="COM_BANNERS_FIELD_CLIENTOWNPREFIX_DESC"
			class="btn-group btn-group-yesno"
			default="0"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>

		<field
			name="metakey_prefix"
			type="text"
			label="COM_BANNERS_FIELD_CLIENT_METAKEYWORDPREFIX_LABEL"
			description="COM_BANNERS_FIELD_CLIENT_METAKEYWORDPREFIX_DESC"
		/>
	</fieldset>

	<fieldset name="extra" label="COM_BANNERS_EXTRA">
		<field
			name="extrainfo"
			type="textarea"
			label="COM_BANNERS_FIELD_EXTRAINFO_LABEL"
			description="COM_BANNERS_FIELD_EXTRAINFO_DESC"
			class="span12"
			rows="5"
			cols="80"
		/>
	</fieldset>
</form>
forms/filter_banners.xml000060400000006732152455702440011425 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter" addfieldpath="/administrator/components/com_banners/models/fields">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_BANNERS_BANNERS_FILTER_SEARCH_LABEL"
			description="COM_BANNERS_BANNERS_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="published"
			type="status"
			label="JOPTION_SELECT_PUBLISHED"
			description="JOPTION_SELECT_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="category_id"
			type="category"
			label="JOPTION_FILTER_CATEGORY"
			description="JOPTION_FILTER_CATEGORY_DESC"
			extension="com_banners"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_CATEGORY</option>
		</field>

		<field
			name="client_id"
			type="bannerclient"
			label="COM_BANNERS_FILTER_CLIENT"
			description="COM_BANNERS_FILTER_CLIENT_DESC"
			extension="com_content"
			onchange="this.form.submit();"
			>
			<option value="">COM_BANNERS_SELECT_CLIENT</option>
		</field>

		<field
			name="language"
			type="contentlanguage"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>

		<field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="10"
			step="1"
			languages="*"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			statuses="*,0,1,2,-2"
			onchange="this.form.submit();"
			default="a.name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.state ASC">JSTATUS_ASC</option>
			<option value="a.state DESC">JSTATUS_DESC</option>
			<option value="a.name ASC">COM_BANNERS_HEADING_NAME_ASC</option>
			<option value="a.name DESC">COM_BANNERS_HEADING_NAME_DESC</option>
			<option value="category_title ASC">JCATEGORY_ASC</option>
			<option value="category_title DESC">JCATEGORY_DESC</option>
			<option value="a.sticky ASC">COM_BANNERS_HEADING_STICKY_ASC</option>
			<option value="a.sticky DESC">COM_BANNERS_HEADING_STICKY_DESC</option>
			<option value="client_name ASC">COM_BANNERS_HEADING_CLIENT_ASC</option>
			<option value="client_name DESC">COM_BANNERS_HEADING_CLIENT_DESC</option>
			<option value="impmade ASC">COM_BANNERS_HEADING_IMPRESSIONS_ASC</option>
			<option value="impmade DESC">COM_BANNERS_HEADING_IMPRESSIONS_DESC</option>
			<option value="clicks ASC">COM_BANNERS_HEADING_CLICKS_ASC</option>
			<option value="clicks DESC">COM_BANNERS_HEADING_CLICKS_DESC</option>
			<option value="a.language ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="a.language DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="COM_BANNERS_LIST_LIMIT"
			description="COM_BANNERS_LIST_LIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_tracks.xml000060400000005631152455702440011261 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter" addfieldpath="/administrator/components/com_banners/models/fields">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_BANNERS_TRACKS_FILTER_SEARCH_LABEL"
			description="COM_BANNERS_TRACKS_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="category_id"
			type="category"
			label="JOPTION_FILTER_CATEGORY"
			description="JOPTION_FILTER_CATEGORY_DESC"
			extension="com_banners"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_CATEGORY</option>
		</field>

		<field
			name="client_id"
			type="bannerclient"
			label="COM_BANNERS_FILTER_CLIENT"
			description="COM_BANNERS_FILTER_CLIENT_DESC"
			extension="com_content"
			onchange="this.form.submit();"
			>
			<option value="">COM_BANNERS_SELECT_CLIENT</option>
		</field>

		<field
			name="type"
			type="list"
			onchange="this.form.submit();"
			>
			<option value="">COM_BANNERS_SELECT_TYPE</option>
			<option value="1">COM_BANNERS_TYPE1</option>
			<option value="2">COM_BANNERS_TYPE2</option>
		</field>

		<field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="10"
			step="1"
			languages="*"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
		</field>

		<field
			name="begin"
			type="calendar"
			label="COM_BANNERS_BEGIN_LABEL"
			description="COM_BANNERS_BEGIN_DESC"
			hint="COM_BANNERS_BEGIN_HINT"
			format="%Y-%m-%d"
			size="10"
			filter="user_utc"
		/>

		<field
			name="end"
			type="calendar"
			label="COM_BANNERS_END_LABEL"
			description="COM_BANNERS_END_DESC"
			hint="COM_BANNERS_END_HINT"
			format="%Y-%m-%d"
			size="10"
			filter="user_utc"
		/>
    </fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="b.name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="b.name ASC">COM_BANNERS_HEADING_NAME_ASC</option>
			<option value="b.name DESC">COM_BANNERS_HEADING_NAME_DESC</option>
			<option value="cl.name ASC">COM_BANNERS_HEADING_CLIENT_ASC</option>
			<option value="cl.name DESC">COM_BANNERS_HEADING_CLIENT_DESC</option>
			<option value="a.track_type ASC">COM_BANNERS_HEADING_TYPE_ASC</option>
			<option value="a.track_type DESC">COM_BANNERS_HEADING_TYPE_DESC</option>
			<option value="a.count ASC">COM_BANNERS_HEADING_COUNT_ASC</option>
			<option value="a.count DESC">COM_BANNERS_HEADING_COUNT_DESC</option>
			<option value="a.track_date ASC">JDATE_ASC</option>
			<option value="a.track_date DESC">JDATE_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="5"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_clients.xml000060400000004363152455702440011434 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_BANNERS_CLIENTS_FILTER_SEARCH_LABEL"
			description="COM_BANNERS_CLIENTS_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="state"
			type="status"
			label="JOPTION_SELECT_PUBLISHED"
			description="JOPTION_SELECT_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="purchase_type"
			type="list"
			label="COM_BANNERS_FILTER_PURCHASETYPE_LABEL"
			description="COM_BANNERS_FIELD_PURCHASETYPE_DESC"
			default="0"
			onchange="this.form.submit();"
			>
			<option value="">COM_BANNERS_SELECT_TYPE</option>
			<option value="1">COM_BANNERS_FIELD_VALUE_UNLIMITED</option>
			<option value="2">COM_BANNERS_FIELD_VALUE_YEARLY</option>
			<option value="3">COM_BANNERS_FIELD_VALUE_MONTHLY</option>
			<option value="4">COM_BANNERS_FIELD_VALUE_WEEKLY</option>
			<option value="5">COM_BANNERS_FIELD_VALUE_DAILY</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			statuses="*,0,1,2,-2"
			onchange="this.form.submit();"
			default="a.name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.state ASC">JSTATUS_ASC</option>
			<option value="a.state DESC">JSTATUS_DESC</option>
			<option value="a.name ASC">COM_BANNERS_HEADING_CLIENT_ASC</option>
			<option value="a.name DESC">COM_BANNERS_HEADING_CLIENT_DESC</option>
			<option value="a.contact ASC">COM_BANNERS_HEADING_CONTACT_ASC</option>
			<option value="a.contact DESC">COM_BANNERS_HEADING_CONTACT_DESC</option>
			<option value="a.purchase_type ASC">COM_BANNERS_HEADING_PURCHASETYPE_ASC</option>
			<option value="a.purchase_type DESC">COM_BANNERS_HEADING_PURCHASETYPE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="COM_BANNERS_LIST_LIMIT"
			description="COM_BANNERS_LIST_LIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/download.xml000060400000006150152455702440010231 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset name="details" addfieldpath="/administrator/components/com_icagenda/assets/elements">
		<field
			type="TitleImg"
			label="JOPTIONS"
			class="stylebox lead input-xxlarge"
			icicon="options"
			/>
		<field
			name="event_title"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_REGISTRATION_EVENTID"
			default="1"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="date"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_REGISTRATION_DATE"
			default="1"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="tickets"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_REGISTRATION_TICKETS"
			default="1"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="name"
			type="radio"
			class="btn-group btn-group-yesno"
			label="IC_NAME"
			default="1"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="email"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_REGISTRATION_EMAIL"
			default="1"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="phone"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_REGISTRATION_PHONE"
			default="1"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="customfields"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_CUSTOMFIELDS"
			default="1"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="notes"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_REGISTRATION_NOTES_DISPLAY_LABEL"
			default="0"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			name="status"
			type="radio"
			class="btn-group btn-group-yesno"
			label="JSTATUS"
			default="0"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field
			type="TitleImg"
			label="COM_ICAGENDA_REGISTRATIONS_EXPORT"
			class="stylebox lead input-xxlarge"
			icicon="logo"
			/>
		<field
			name="basename"
			type="text"
			size="40"
			label="COM_ICAGENDA_EXPORT_BASENAME_LABEL"
			description="COM_ICAGENDA_EXPORT_BASENAME_DESC"
			class="inputbox"
			/>
		<field
			name="separator"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_EXPORT_SEPARATOR_LABEL"
			description="COM_ICAGENDA_EXPORT_SEPARATOR_DESC"
			default="1"
		>
			<option value="1">IC_COMMA</option>
			<option value="2">IC_SEMICOLON</option>
		</field>
		<field
			name="compressed"
			type="radio"
			class="btn-group btn-group-yesno"
			label="COM_ICAGENDA_EXPORT_COMPRESSED_LABEL"
			description="COM_ICAGENDA_EXPORT_COMPRESSED_DESC"
			default="0"
		>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
		<field type="Title" label=" " class="stylenote"/>
	</fieldset>
</form>
download.php000060400000005556152455702440007103 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.0 2015-02-05
 * @since       3.5.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

// Joomla 2.5 import
jimport('joomla.application.component.modelform');

/**
 * Download model.
 *
 * @since	3.5.0
 */
class icagendaModelDownload extends JModelForm
{
	protected $_context = 'com_icagenda.registrations';

	/**
	 * Auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   3.5.0
	 */
	protected function populateState()
	{
		// Joomla 3
		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$input = JFactory::getApplication()->input;

			$basename = $input->cookie->getString(JApplicationHelper::getHash($this->_context . '.basename'), '__SITE__');
			$this->setState('basename', $basename);

			$compressed = $input->cookie->getInt(JApplicationHelper::getHash($this->_context . '.compressed'), 1);
			$this->setState('compressed', $compressed);
		}

		// Joomla 2.5
		else
		{
			$basename = JRequest::getString(JApplication::getHash($this->_context.'.basename'), '__SITE__', 'cookie');
			$this->setState('basename', $basename);

			$compressed = JRequest::getInt(JApplication::getHash($this->_context.'.compressed'), 1, 'cookie');
			$this->setState('compressed', $compressed);
		}
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed  A JForm object on success, false on failure
	 *
	 * @since   3.5.0
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_icagenda.download', 'download', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   3.5.0
	 */
	protected function loadFormData()
	{
		$data = array(
			'basename'		=> $this->getState('basename'),
			'compressed'	=> $this->getState('compressed')
		);

		// Joomla 3
		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$this->preprocessData('com_icagenda.download', $data);
		}

		return $data;
	}
}
fields/modal/newsfeed.php000060400000023453152455705560011440 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_newsfeeds
 *
 * @copyright   (C) 2013 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Language\LanguageHelper;

/**
 * Supports a modal newsfeeds picker.
 *
 * @since  1.6
 */
class JFormFieldModal_Newsfeed extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var     string
	 * @since   1.6
	 */
	protected $type = 'Modal_Newsfeed';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   1.6
	 */
	protected function getInput()
	{
		$allowNew       = ((string) $this->element['new'] == 'true');
		$allowEdit      = ((string) $this->element['edit'] == 'true');
		$allowClear     = ((string) $this->element['clear'] != 'false');
		$allowSelect    = ((string) $this->element['select'] != 'false');
		$allowPropagate = ((string) $this->element['propagate'] == 'true');

		$languages = LanguageHelper::getContentLanguages(array(0, 1));

		// Load language
		JFactory::getLanguage()->load('com_newsfeeds', JPATH_ADMINISTRATOR);

		// The active newsfeed id field.
		$value = (int) $this->value > 0 ? (int) $this->value : '';

		// Create the modal id.
		$modalId = 'Newsfeed_' . $this->id;

		// Add the modal field script to the document head.
		JHtml::_('jquery.framework');
		JHtml::_('script', 'system/modal-fields.js', array('version' => 'auto', 'relative' => true));

		// Script to proxy the select modal function to the modal-fields.js file.
		if ($allowSelect)
		{
			static $scriptSelect = null;

			if (is_null($scriptSelect))
			{
				$scriptSelect = array();
			}

			if (!isset($scriptSelect[$this->id]))
			{
				JFactory::getDocument()->addScriptDeclaration("
				function jSelectNewsfeed_" . $this->id . "(id, title, object) {
					window.processModalSelect('Newsfeed', '" . $this->id . "', id, title, '', object);
				}
				"
				);

				JText::script('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED');

				$scriptSelect[$this->id] = true;
			}
		}

		// Setup variables for display.
		$linkNewsfeeds = 'index.php?option=com_newsfeeds&amp;view=newsfeeds&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';
		$linkNewsfeed  = 'index.php?option=com_newsfeeds&amp;view=newsfeed&amp;layout=modal&amp;tmpl=component&amp;' . JSession::getFormToken() . '=1';
		$modalTitle    = JText::_('COM_NEWSFEEDS_CHANGE_FEED');

		if (isset($this->element['language']))
		{
			$linkNewsfeeds .= '&amp;forcedLanguage=' . $this->element['language'];
			$linkNewsfeed  .= '&amp;forcedLanguage=' . $this->element['language'];
			$modalTitle    .= ' &#8212; ' . $this->element['label'];
		}

		$urlSelect = $linkNewsfeeds . '&amp;function=jSelectNewsfeed_' . $this->id;
		$urlEdit   = $linkNewsfeed . '&amp;task=newsfeed.edit&amp;id=\' + document.getElementById("' . $this->id . '_id").value + \'';
		$urlNew    = $linkNewsfeed . '&amp;task=newsfeed.add';

		if ($value)
		{
			$db    = JFactory::getDbo();
			$query = $db->getQuery(true)
				->select($db->quoteName('name'))
				->from($db->quoteName('#__newsfeeds'))
				->where($db->quoteName('id') . ' = ' . (int) $value);
			$db->setQuery($query);

			try
			{
				$title = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				JError::raiseWarning(500, $e->getMessage());
			}
		}

		$title = empty($title) ? JText::_('COM_NEWSFEEDS_SELECT_A_FEED') : htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

		// The current newsfeed display field.
		$html  = '<span class="input-append">';
		$html .= '<input class="input-medium" id="' . $this->id . '_name" type="text" value="' . $title . '" disabled="disabled" size="35" />';

		// Select newsfeed button
		if ($allowSelect)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"'
				. ' id="' . $this->id . '_select"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalSelect' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_NEWSFEEDS_CHANGE_FEED') . '">'
				. '<span class="icon-file" aria-hidden="true"></span> ' . JText::_('JSELECT')
				. '</button>';
		}

		// New newsfeed button
		if ($allowNew)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? ' hidden' : '') . '"'
				. ' id="' . $this->id . '_new"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalNew' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_NEWSFEEDS_NEW_NEWSFEED') . '">'
				. '<span class="icon-new" aria-hidden="true"></span> ' . JText::_('JACTION_CREATE')
				. '</button>';
		}

		// Edit newsfeed button
		if ($allowEdit)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"'
				. ' id="' . $this->id . '_edit"'
				. ' data-toggle="modal"'
				. ' data-target="#ModalEdit' . $modalId . '"'
				. ' title="' . JHtml::tooltipText('COM_NEWSFEEDS_EDIT_NEWSFEED') . '">'
				. '<span class="icon-edit" aria-hidden="true"></span> ' . JText::_('JACTION_EDIT')
				. '</button>';
		}

		// Clear newsfeed button
		if ($allowClear)
		{
			$html .= '<button'
				. ' type="button"'
				. ' class="btn' . ($value ? '' : ' hidden') . '"'
				. ' id="' . $this->id . '_clear"'
				. ' onclick="window.processModalParent(\'' . $this->id . '\'); return false;">'
				. '<span class="icon-remove" aria-hidden="true"></span>' . JText::_('JCLEAR')
				. '</button>';
		}

		// Propagate newsfeed button
		if ($allowPropagate && count($languages) > 2)
		{
			// Strip off language tag at the end
			$tagLength = (int) strlen($this->element['language']);
			$callbackFunctionStem = substr("jSelectNewsfeed_" . $this->id, 0, -$tagLength);

			$html .= '<a'
			. ' class="btn hasTooltip' . ($value ? '' : ' hidden') . '"'
			. ' id="' . $this->id . '_propagate"'
			. ' href="#"'
			. ' title="' . JHtml::tooltipText('JGLOBAL_ASSOCIATIONS_PROPAGATE_TIP') . '"'
			. ' onclick="Joomla.propagateAssociation(\'' . $this->id . '\', \'' . $callbackFunctionStem . '\');">'
			. '<span class="icon-refresh" aria-hidden="true"></span>' . JText::_('JGLOBAL_ASSOCIATIONS_PROPAGATE_BUTTON')
			. '</a>';
		}

		$html .= '</span>';

		// Select newsfeed modal
		if ($allowSelect)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalSelect' . $modalId,
				array(
					'title'       => $modalTitle,
					'url'         => $urlSelect,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn" data-dismiss="modal">' . JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>',
				)
			);
		}

		// New newsfeed modal
		if ($allowNew)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalNew' . $modalId,
				array(
					'title'       => JText::_('COM_NEWSFEEDS_NEW_NEWSFEED'),
					'backdrop'    => 'static',
					'keyboard'    => false,
					'closeButton' => false,
					'url'         => $urlNew,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'add\', \'newsfeed\', \'cancel\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>'
							. '<button type="button" class="btn btn-primary"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'add\', \'newsfeed\', \'save\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JSAVE') . '</button>'
							. '<button type="button" class="btn btn-success"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'add\', \'newsfeed\', \'apply\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JAPPLY') . '</button>',
				)
			);
		}

		// Edit newsfeed modal.
		if ($allowEdit)
		{
			$html .= JHtml::_(
				'bootstrap.renderModal',
				'ModalEdit' . $modalId,
				array(
					'title'       => JText::_('COM_NEWSFEEDS_EDIT_NEWSFEED'),
					'backdrop'    => 'static',
					'keyboard'    => false,
					'closeButton' => false,
					'url'         => $urlEdit,
					'height'      => '400px',
					'width'       => '800px',
					'bodyHeight'  => '70',
					'modalWidth'  => '80',
					'footer'      => '<button type="button" class="btn"'
							. ' onclick="window.processModalEdit(this, \'' . $this->id
							. '\', \'edit\', \'newsfeed\', \'cancel\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JLIB_HTML_BEHAVIOR_CLOSE') . '</button>'
							. '<button type="button" class="btn btn-primary"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'edit\', \'newsfeed\', \'save\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JSAVE') . '</button>'
							. '<button type="button" class="btn btn-success"'
							. ' onclick="window.processModalEdit(this, \''
							. $this->id . '\', \'edit\', \'newsfeed\', \'apply\', \'newsfeed-form\', \'jform_id\', \'jform_name\'); return false;">'
							. JText::_('JAPPLY') . '</button>',
				)
			);
		}

		// Add class='required' for client side validation
		$class = $this->required ? ' class="required modal-value"' : '';

		$html .= '<input type="hidden" id="' . $this->id . '_id"' . $class . ' data-required="' . (int) $this->required . '" name="' . $this->name
			. '" data-text="' . htmlspecialchars(JText::_('COM_NEWSFEEDS_SELECT_A_FEED', true), ENT_COMPAT, 'UTF-8') . '" value="' . $value . '" />';

		return $html;
	}

	/**
	 * Method to get the field label markup.
	 *
	 * @return  string  The field label markup.
	 *
	 * @since   3.4
	 */
	protected function getLabel()
	{
		return str_replace($this->id, $this->id . '_id', parent::getLabel());
	}
}
fields/newsfeeds.php000060400000002226152455705560010522 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_newsfeeds
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JFormHelper::loadFieldClass('list');

/**
 * News Feed List field.
 *
 * @since  1.6
 */
class JFormFieldNewsfeeds extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var		string
	 * @since   1.6
	 */
	protected $type = 'Newsfeeds';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   1.6
	 */
	protected function getOptions()
	{
		$options = array();

		$db    = JFactory::getDbo();
		$query = $db->getQuery(true)
			->select('id As value, name As text')
			->from('#__newsfeeds AS a')
			->order('a.name');

		// Get the options.
		$db->setQuery($query);

		try
		{
			$options = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $db->getMessage());
		}

		// Merge any additional options in the XML definition.
		$options = array_merge(parent::getOptions(), $options);

		return $options;
	}
}
newsfeed.php000060400000012122152455705560007065 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_newsfeeds
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;

/**
 * Newsfeeds Component Newsfeed Model
 *
 * @since  1.5
 */
class NewsfeedsModelNewsfeed extends JModelItem
{
	/**
	 * Model context string.
	 *
	 * @var		string
	 * @since   1.6
	 */
	protected $_context = 'com_newsfeeds.newsfeed';

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication('site');

		// Load state from the request.
		$pk = $app->input->getInt('id');
		$this->setState('newsfeed.id', $pk);

		$offset = $app->input->get('limitstart', 0, 'uint');
		$this->setState('list.offset', $offset);

		// Load the parameters.
		$params = $app->getParams();
		$this->setState('params', $params);

		$user = JFactory::getUser();

		if ((!$user->authorise('core.edit.state', 'com_newsfeeds')) && (!$user->authorise('core.edit', 'com_newsfeeds')))
		{
			$this->setState('filter.published', 1);
			$this->setState('filter.archived', 2);
		}
	}

	/**
	 * Method to get newsfeed data.
	 *
	 * @param   integer  $pk  The id of the newsfeed.
	 *
	 * @return  mixed  Menu item data object on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function &getItem($pk = null)
	{
		$pk = (!empty($pk)) ? $pk : (int) $this->getState('newsfeed.id');

		if ($this->_item === null)
		{
			$this->_item = array();
		}

		if (!isset($this->_item[$pk]))
		{
			try
			{
				$db = $this->getDbo();
				$query = $db->getQuery(true)
					->select($this->getState('item.select', 'a.*'))
					->from('#__newsfeeds AS a');

				// Join on category table.
				$query->select('c.title AS category_title, c.alias AS category_alias, c.access AS category_access')
					->join('LEFT', '#__categories AS c on c.id = a.catid');

				// Join on user table.
				$query->select('u.name AS author')
					->join('LEFT', '#__users AS u on u.id = a.created_by');

				// Join over the categories to get parent category titles
				$query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias')
					->join('LEFT', '#__categories as parent ON parent.id = c.parent_id')

					->where('a.id = ' . (int) $pk);

				// Filter by start and end dates.
				$nullDate = $db->quote($db->getNullDate());
				$nowDate = $db->quote(JFactory::getDate()->toSql());

				// Filter by published state.
				$published = $this->getState('filter.published');
				$archived = $this->getState('filter.archived');

				if (is_numeric($published))
				{
					$query->where('(a.published = ' . (int) $published . ' OR a.published =' . (int) $archived . ')')
						->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')')
						->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')')
						->where('(c.published = ' . (int) $published . ' OR c.published =' . (int) $archived . ')');
				}

				$db->setQuery($query);

				$data = $db->loadObject();

				if (empty($data))
				{
					JError::raiseError(404, JText::_('COM_NEWSFEEDS_ERROR_FEED_NOT_FOUND'));
				}

				// Check for published state if filter set.

				if ((is_numeric($published) || is_numeric($archived)) && $data->published != $published && $data->published != $archived)
				{
					JError::raiseError(404, JText::_('COM_NEWSFEEDS_ERROR_FEED_NOT_FOUND'));
				}

				// Convert parameter fields to objects.
				$registry = new Registry($data->params);
				$data->params = clone $this->getState('params');
				$data->params->merge($registry);

				$data->metadata = new Registry($data->metadata);

				// Compute access permissions.

				if ($access = $this->getState('filter.access'))
				{
					// If the access filter has been set, we already know this user can view.
					$data->params->set('access-view', true);
				}
				else
				{
					// If no access filter is set, the layout takes some responsibility for display of limited information.
					$user   = JFactory::getUser();
					$groups = $user->getAuthorisedViewLevels();
					$data->params->set('access-view', in_array($data->access, $groups) && in_array($data->category_access, $groups));
				}

				$this->_item[$pk] = $data;
			}
			catch (Exception $e)
			{
				$this->setError($e);
				$this->_item[$pk] = false;
			}
		}

		return $this->_item[$pk];
	}

	/**
	 * Increment the hit counter for the newsfeed.
	 *
	 * @param   int  $pk  Optional primary key of the item to increment.
	 *
	 * @return  boolean  True if successful; false otherwise and internal error set.
	 *
	 * @since   3.0
	 */
	public function hit($pk = 0)
	{
		$input = JFactory::getApplication()->input;
		$hitcount = $input->getInt('hitcount', 1);

		if ($hitcount)
		{
			$pk = (!empty($pk)) ? $pk : (int) $this->getState('newsfeed.id');

			$table = JTable::getInstance('Newsfeed', 'NewsfeedsTable');
			$table->hit($pk);
		}

		return true;
	}
}
forms/newsfeed.xml000060400000024754152455705560010242 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>

	<fieldset addfieldpath="/administrator/components/com_categories/models/fields" >

		<field
			name="id"
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			default="0"
			class="readonly"
			readonly="true"
		/>

		<field
			name="name"
			type="text"
			label="JGLOBAL_TITLE"
			description="JFIELD_TITLE_DESC"
			class="input-xxlarge input-large-text"
			size="40"
			required="true"
		/>

		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			size="45"
			hint="JFIELD_ALIAS_PLACEHOLDER"
		/>

		<field
			name="published"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			default="1"
			class="chzn-color-state"
			size="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="2">JARCHIVED</option>
			<option value="-2">JTRASHED</option>
		</field>

		<field
			name="catid"
			type="categoryedit"
			label="JCATEGORY"
			description="COM_NEWSFEEDS_FIELD_CATEGORY_DESC"
			extension="com_newsfeeds"
			required="true"
			default=""
		/>

		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="COM_NEWSFEEDS_FIELD_LANGUAGE_DESC"
			>
			<option value="*">JALL</option>
		</field>

		<field
			name="tags"
			type="tag"
			label="JTAG"
			description="JTAG_DESC"
			class="span12"
			multiple="true"
		/>

		<field
			name="version_note"
			type="text"
			label="JGLOBAL_FIELD_VERSION_NOTE_LABEL"
			description="JGLOBAL_FIELD_VERSION_NOTE_DESC"
			labelclass="control-label"
			class="span12"
			size="45"
			maxlength="255"
		/>

		<field
			name="description"
			type="editor"
			label="JGLOBAL_DESCRIPTION"
			description="COM_NEWSFEEDS_FIELD_DESCRIPTION_DESC"
			buttons="true"
			hide="pagebreak,readmore"
			filter="JComponentHelper::filterText"
		/>

		<field
			name="link"
			type="url"
			label="COM_NEWSFEEDS_FIELD_LINK_LABEL"
			description="COM_NEWSFEEDS_FIELD_LINK_DESC"
			class="span12"
			size="60"
			required="true"
			filter="url"
			validate="url"
		/>

		<field
			name="numarticles"
			type="number"
			label="COM_NEWSFEEDS_FIELD_NUM_ARTICLES_LABEL"
			description="COM_NEWSFEEDS_FIELD_NUM_ARTICLES_DESC"
			default="5"
			size="2"
		/>

		<field
			name="cache_time"
			type="number"
			label="COM_NEWSFEEDS_FIELD_CACHETIME_LABEL"
			description="JGLOBAL_FIELD_FIELD_CACHETIME_DESC"
			default="3600"
			size="4"
		/>

		<field
			name="ordering"
			type="ordering"
			label="JFIELD_ORDERING_LABEL"
			description="JFIELD_ORDERING_DESC"
			content_type="com_newsfeeds.newsfeed"
		/>

		<field
			name="created"
			type="calendar"
			label="JGLOBAL_FIELD_CREATED_LABEL"
			description="JGLOBAL_FIELD_CREATED_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="created_by"
			type="user"
			label="JGLOBAL_FIELD_Created_by_Label"
			description="JGLOBAL_FIELD_CREATED_BY_DESC"
		/>

		<field
			name="created_by_alias"
			type="text"
			label="JGLOBAL_FIELD_Created_by_alias_Label"
			description="JGLOBAL_FIELD_CREATED_BY_ALIAS_DESC"
			size="20"
		/>

		<field
			name="modified"
			type="calendar"
			label="JGLOBAL_FIELD_Modified_Label"
			description="COM_NEWSFEEDS_FIELD_MODIFIED_DESC"
			class="readonly"
			translateformat="true"
			showtime="true"
			size="22"
			readonly="true"
			filter="user_utc"
		/>

		<field
			name="modified_by"
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			description="COM_NEWSFEEDS_FIELD_MODIFIED_BY_DESC"
			class="readonly"
			readonly="true"
			filter="unset"
		/>

		<field
			name="version"
			type="text"
			label="COM_NEWSFEEDS_FIELD_VERSION_LABEL"
			description="COM_NEWSFEEDS_FIELD_VERSION_DESC"
			class="readonly"
			size="6"
			readonly="true"
			filter="unset"
		/>

		<field
			name="checked_out"
			type="Text"
			label="JGLOBAL_FIELD_CHECKEDOUT_LABEL"
			description="JGLOBAL_FIELD_CHECKEDOUT_DESC"
			size="6"
			readonly="true"
			filter="unset"
		/>

		<field
			name="checked_out_time"
			type="Text"
			label="JGLOBAL_FIELD_CHECKEDOUT_TIME_LABEL"
			description="JGLOBAL_FIELD_CHECKEDOUT_TIME_DESC"
			size="6"
			readonly="true"
			filter="unset"
		/>

		<field
			name="publish_up"
			type="calendar"
			label="JGLOBAL_FIELD_PUBLISH_UP_LABEL"
			description="JGLOBAL_FIELD_PUBLISH_UP_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="publish_down"
			type="calendar"
			label="JGLOBAL_FIELD_PUBLISH_DOWN_LABEL"
			description="JGLOBAL_FIELD_PUBLISH_DOWN_DESC"
			translateformat="true"
			showtime="true"
			size="22"
			filter="user_utc"
		/>

		<field
			name="access"
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="JFIELD_ACCESS_DESC"
			size="1"
		/>

		<field
			name="metakey"
			type="textarea"
			label="JFIELD_META_KEYWORDS_LABEL"
			description="JFIELD_META_KEYWORDS_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="metadesc"
			type="textarea"
			label="JFIELD_META_DESCRIPTION_LABEL"
			description="JFIELD_META_DESCRIPTION_DESC"
			rows="3"
			cols="30"
		/>

		<field
			name="xreference"
			type="text"
			label="JFIELD_XREFERENCE_LABEL"
			description="JFIELD_XREFERENCE_DESC"
			size="20"
		/>

		<fields name="images">

			<fieldset name="images" label="JGLOBAL_FIELDSET_IMAGE_OPTIONS">

				<field
					name="image_first"
					type="media"
					label="COM_NEWSFEEDS_FIELD_FIRST_LABEL"
					description="COM_NEWSFEEDS_FIELD_FIRST_DESC"
				/>

				<field
					name="float_first"
					type="list"
					label="COM_NEWSFEEDS_FLOAT_LABEL"
					description="COM_NEWSFEEDS_FLOAT_DESC"
					useglobal="true"
					>
					<option value="right">COM_NEWSFEEDS_RIGHT</option>
					<option value="left">COM_NEWSFEEDS_LEFT</option>
					<option value="none">COM_NEWSFEEDS_NONE</option>
				</field>

				<field
					name="image_first_alt"
					type="text"
					label="COM_NEWSFEEDS_FIELD_IMAGE_ALT_LABEL"
					description="COM_NEWSFEEDS_FIELD_IMAGE_ALT_DESC"
					size="20"
				/>

				<field
					name="image_first_caption"
					type="text"
					label="COM_NEWSFEEDS_FIELD_IMAGE_CAPTION_LABEL"
					description="COM_NEWSFEEDS_FIELD_IMAGE_CAPTION_DESC"
					size="20"
				/>

				<field
					name="spacer1"
					type="spacer"
					hr="true"
				/>

				<field
					name="image_second"
					type="media"
					label="COM_NEWSFEEDS_FIELD_SECOND_LABEL"
					description="COM_NEWSFEEDS_FIELD_SECOND_DESC"
				/>

				<field
					name="float_second"
					type="list"
					label="COM_NEWSFEEDS_FLOAT_LABEL"
					description="COM_NEWSFEEDS_FLOAT_DESC"
					useglobal="true"
					>
					<option value="right">COM_NEWSFEEDS_RIGHT</option>
					<option value="left">COM_NEWSFEEDS_LEFT</option>
					<option value="none">COM_NEWSFEEDS_NONE</option>
				</field>

				<field
					name="image_second_alt"
					type="text"
					label="COM_NEWSFEEDS_FIELD_IMAGE_ALT_LABEL"
					description="COM_NEWSFEEDS_FIELD_IMAGE_ALT_DESC"
					size="20"
				/>

				<field
					name="image_second_caption"
					type="text"
					label="COM_NEWSFEEDS_FIELD_IMAGE_CAPTION_LABEL"
					description="COM_NEWSFEEDS_FIELD_IMAGE_CAPTION_DESC"
					size="20"
				/>
			</fieldset>
		</fields>
	</fieldset>

	<fieldset name="jbasic" label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS">

		<field
			name="numarticles"
			type="number"
			label="COM_NEWSFEEDS_FIELD_NUM_ARTICLES_LABEL"
			description="COM_NEWSFEEDS_FIELD_NUM_ARTICLES_DESC"
			default="5"
			size="2"
		/>

		<field
			name="cache_time"
			type="number"
			label="COM_NEWSFEEDS_FIELD_CACHETIME_LABEL"
			description="JGLOBAL_FIELD_FIELD_CACHETIME_DESC"
			default="3600"
			size="4"
		/>

		<field
			name="rtl"
			type="list"
			label="COM_NEWSFEEDS_FIELD_RTL_LABEL"
			description="COM_NEWSFEEDS_FIELD_RTL_DESC"
			default="0"
			>
			<option value="0">COM_NEWSFEEDS_FIELD_VALUE_SITE</option>
			<option value="1">COM_NEWSFEEDS_FIELD_VALUE_LTR</option>
			<option value="2">COM_NEWSFEEDS_FIELD_VALUE_RTL</option>
		</field>

		<fields name="params" label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS">

			<field
				name="show_feed_image"
				type="list"
				label="COM_NEWSFEEDS_FIELD_SHOW_FEED_IMAGE_LABEL"
				description="COM_NEWSFEEDS_FIELD_SHOW_FEED_IMAGE_DESC"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_feed_description"
				type="list"
				label="COM_NEWSFEEDS_FIELD_SHOW_FEED_DESCRIPTION_LABEL"
				description="COM_NEWSFEEDS_FIELD_SHOW_FEED_DESCRIPTION_DESC"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="show_item_description"
				type="list"
				label="COM_NEWSFEEDS_FIELD_SHOW_ITEM_DESCRIPTION_LABEL"
				description="COM_NEWSFEEDS_FIELD_SHOW_ITEM_DESCRIPTION_DESC"
				useglobal="true"
				>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>

			<field
				name="feed_character_count"
				type="number"
				label="COM_NEWSFEEDS_FIELD_CHARACTERS_COUNT_LABEL"
				description="COM_NEWSFEEDS_FIELD_CHARACTERS_COUNT_DESC"
				size="6"
				useglobal="true"
			/>

			<field
				name="newsfeed_layout"
				type="componentlayout"
				label="JFIELD_ALT_LAYOUT_LABEL"
				description="JFIELD_ALT_COMPONENT_LAYOUT_DESC"
				extension="com_newsfeeds"
				view="newsfeed"
				useglobal="true"
			/>

			<field
				name="feed_display_order"
				type="list"
				label="COM_NEWSFEEDS_FIELD_FEED_DISPLAY_ORDER_LABEL"
				description="COM_NEWSFEEDS_FIELD_FEED_DISPLAY_ORDER_DESC"
				useglobal="true"
				>
				<option value="des">JGLOBAL_MOST_RECENT_FIRST</option>
				<option value="asc">JGLOBAL_OLDEST_FIRST</option>
			</field>
		</fields>
	</fieldset>

	<fields name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">

		<fieldset name="jmetadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">

			<field
				name="robots"
				type="list"
				label="JFIELD_METADATA_ROBOTS_LABEL"
				description="JFIELD_METADATA_ROBOTS_DESC"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="index, follow"></option>
				<option value="noindex, follow"></option>
				<option value="index, nofollow"></option>
				<option value="noindex, nofollow"></option>
			</field>

			<field
				name="rights"
				type="text"
				label="JFIELD_META_RIGHTS_LABEL"
				description="JFIELD_META_RIGHTS_DESC"
				rows="2"
				cols="30"
				filter="string"
			/>

			<field
				name="hits"
				type="number"
				label="JGLOBAL_HITS"
				description="COM_NEWSFEEDS_HITS_DESC"
				class="readonly"
				size="6"
				readonly="true"
				filter="unset"
			/>
		</fieldset>
	</fields>
</form>
forms/filter_newsfeeds.xml000060400000007302152455705560011760 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>

	<fields name="filter">

		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_NEWSFEEDS_FILTER_SEARCH_LABEL"
			description="COM_NEWSFEEDS_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="published"
			type="status"
			label="COM_NEWSFEEDS_FILTER_PUBLISHED"
			description="COM_NEWSFEEDS_FILTER_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="category_id"
			type="category"
			label="JOPTION_FILTER_CATEGORY"
			description="JOPTION_FILTER_CATEGORY_DESC"
			extension="com_newsfeeds"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_CATEGORY</option>
		</field>

		<field
			name="access"
			type="accesslevel"
			label="JOPTION_FILTER_ACCESS"
			description="JOPTION_FILTER_ACCESS_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_ACCESS</option>
		</field>

		<field
			name="language"
			type="contentlanguage"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>

		<field
			name="tag"
			type="tag"
			label="JOPTION_FILTER_TAG"
			description="JOPTION_FILTER_TAG_DESC"
			mode="nested"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_TAG</option>
		</field>

		<field
			name="level"
			type="integer"
			label="JOPTION_FILTER_LEVEL"
			description="JOPTION_FILTER_LEVEL_DESC"
			first="1"
			last="10"
			step="1"
			languages="*"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_MAX_LEVELS</option>
		</field>
	</fields>

	<fields name="list">

		<field
			name="fullordering"
			type="list"
			label="COM_NEWSFEEDS_LIST_FULL_ORDERING"
			description="COM_NEWSFEEDS_LIST_FULL_ORDERING_DESC"
			onchange="this.form.submit();"
			default="a.name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.published ASC">JSTATUS_ASC</option>
			<option value="a.published DESC">JSTATUS_DESC</option>
			<option value="a.name ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.name DESC">JGLOBAL_TITLE_DESC</option>
			<option value="category_title ASC">JCATEGORY_ASC</option>
			<option value="category_title DESC">JCATEGORY_DESC</option>
			<option value="access_level ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="access_level DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option value="numarticles ASC">COM_NEWSFEEDS_NUM_ARTICLES_HEADING_ASC</option>
			<option value="numarticles DESC">COM_NEWSFEEDS_NUM_ARTICLES_HEADING_DESC</option>
			<option value="a.cache_time ASC">COM_NEWSFEEDS_CACHE_TIME_HEADING_ASC</option>
			<option value="a.cache_time DESC">COM_NEWSFEEDS_CACHE_TIME_HEADING_DESC</option>
			<option
				value="association ASC"
				requires="associations"
				>
				JASSOCIATIONS_ASC
			</option>
			<option
				value="association DESC"
				requires="associations"
				>
				JASSOCIATIONS_DESC
			</option>
			<option value="language_title ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="language_title DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="COM_NEWSFEEDS_LIST_LIMIT"
			description="COM_NEWSFEEDS_LIST_LIMIT_DESC"
			default="25"
			class="input-mini"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
newsfeeds.php000060400000023033152455705560007253 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_newsfeeds
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Methods supporting a list of newsfeed records.
 *
 * @since  1.6
 */
class NewsfeedsModelNewsfeeds extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'name', 'a.name',
				'alias', 'a.alias',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'catid', 'a.catid', 'category_id', 'category_title',
				'published', 'a.published',
				'access', 'a.access', 'access_level',
				'created', 'a.created',
				'created_by', 'a.created_by',
				'ordering', 'a.ordering',
				'language', 'a.language', 'language_title',
				'publish_up', 'a.publish_up',
				'publish_down', 'a.publish_down',
				'cache_time', 'a.cache_time',
				'numarticles',
				'tag',
				'level', 'c.level',
				'tag',
			);

			$assoc = JLanguageAssociations::isEnabled();

			if ($assoc)
			{
				$config['filter_fields'][] = 'association';
			}
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.name', $direction = 'asc')
	{
		$app = JFactory::getApplication();

		$forcedLanguage = $app->input->get('forcedLanguage', '', 'cmd');

		// Adjust the context to support modal layouts.
		if ($layout = $app->input->get('layout'))
		{
			$this->context .= '.' . $layout;
		}

		// Adjust the context to support forced languages.
		if ($forcedLanguage)
		{
			$this->context .= '.' . $forcedLanguage;
		}

		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.published', $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '', 'string'));
		$this->setState('filter.category_id', $this->getUserStateFromRequest($this->context . '.filter.category_id', 'filter_category_id', '', 'cmd'));
		$this->setState('filter.access', $this->getUserStateFromRequest($this->context . '.filter.access', 'filter_access', '', 'cmd'));
		$this->setState('filter.language', $this->getUserStateFromRequest($this->context . '.filter.language', 'filter_language', '', 'string'));
		$this->setState('filter.tag', $this->getUserStateFromRequest($this->context . '.filter.tag', 'filter_tag', '', 'string'));
		$this->setState('filter.level', $this->getUserStateFromRequest($this->context . '.filter.level', 'filter_level', null, 'int'));

		// Load the parameters.
		$params = JComponentHelper::getParams('com_newsfeeds');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);

		// Force a language.
		if (!empty($forcedLanguage))
		{
			$this->setState('filter.language', $forcedLanguage);
		}
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.published');
		$id .= ':' . $this->getState('filter.category_id');
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.language');
		$id .= ':' . $this->getState('filter.level');
		$id .= ':' . serialize($this->getState('filter.tag'));

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db    = $this->getDbo();
		$query = $db->getQuery(true);
		$user  = JFactory::getUser();
		$app   = JFactory::getApplication();

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.name, a.alias, a.checked_out, a.checked_out_time, a.catid,' .
				' a.numarticles, a.cache_time, a.created_by,' .
				' a.published, a.access, a.ordering, a.language, a.publish_up, a.publish_down'
			)
		);
		$query->from($db->quoteName('#__newsfeeds', 'a'));

		// Join over the language
		$query->select($db->quoteName('l.title', 'language_title'))
			->select($db->quoteName('l.image', 'language_image'))
			->join('LEFT', $db->quoteName('#__languages', 'l') . ' ON ' . $db->qn('l.lang_code') . ' = ' . $db->qn('a.language'));

		// Join over the users for the checked out user.
		$query->select($db->quoteName('uc.name', 'editor'))
			->join('LEFT', $db->quoteName('#__users', 'uc') . ' ON ' . $db->qn('uc.id') . ' = ' . $db->qn('a.checked_out'));

		// Join over the asset groups.
		$query->select($db->quoteName('ag.title', 'access_level'))
			->join('LEFT', $db->quoteName('#__viewlevels', 'ag') . ' ON ' . $db->qn('ag.id') . ' = ' . $db->qn('a.access'));

		// Join over the categories.
		$query->select($db->quoteName('c.title', 'category_title'))
			->join('LEFT', $db->quoteName('#__categories', 'c') . ' ON ' . $db->qn('c.id') . ' = ' . $db->qn('a.catid'));

		// Join over the associations.
		$assoc = JLanguageAssociations::isEnabled();

		if ($assoc)
		{
			$subQuery = $db->getQuery(true)
				->select('COUNT(' . $db->quoteName('asso1.id') . ') > 1')
				->from($db->quoteName('#__associations', 'asso1'))
				->join('INNER', $db->quoteName('#__associations', 'asso2') . ' ON ' . $db->quoteName('asso1.key') . ' = ' . $db->quoteName('asso2.key'))
				->where(
					array(
						$db->quoteName('asso1.id') . ' = ' . $db->quoteName('a.id'),
						$db->quoteName('asso1.context') . ' = ' . $db->quote('com_newsfeeds.item'),
					)
				);

			$query->select('(' . $subQuery . ') AS ' . $db->quoteName('association'));
		}

		// Filter by access level.
		if ($access = $this->getState('filter.access'))
		{
			$query->where($db->quoteName('a.access') . ' = ' . (int) $access);
		}

		// Implement View Level Access
		if (!$user->authorise('core.admin'))
		{
			$query->where($db->quoteName('a.access') . ' IN (' . implode(',', $user->getAuthorisedViewLevels()) . ')');
		}

		// Filter by published state.
		$published = $this->getState('filter.published');

		if (is_numeric($published))
		{
			$query->where($db->quoteName('a.published') . ' = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where($db->quoteName('a.published') . ' IN (0, 1)');
		}

		// Filter by category.
		$categoryId = $this->getState('filter.category_id');

		if (is_numeric($categoryId))
		{
			$query->where($db->quoteName('a.catid') . ' = ' . (int) $categoryId);
		}

		// Filter on the level.
		if ($level = $this->getState('filter.level'))
		{
			$query->where($db->quoteName('c.level') . ' <= ' . (int) $level);
		}

		// Filter by search in title
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->quoteName('a.id') . ' = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where('(a.name LIKE ' . $search . ' OR a.alias LIKE ' . $search . ')');
			}
		}

		// Filter on the language.
		if ($language = $this->getState('filter.language'))
		{
			$query->where($db->quoteName('a.language') . ' = ' . $db->quote($language));
		}

		// Filter by a single or group of tags.
		$tag = $this->getState('filter.tag');

		// Run simplified query when filtering by one tag.
		if (\is_array($tag) && \count($tag) === 1)
		{
			$tag = $tag[0];
		}

		if ($tag && \is_array($tag))
		{
			$tag = ArrayHelper::toInteger($tag);

			$subQuery = $db->getQuery(true)
				->select('DISTINCT ' . $db->quoteName('content_item_id'))
				->from($db->quoteName('#__contentitem_tag_map'))
				->where(
					array(
						$db->quoteName('tag_id') . ' IN (' . implode(',', $tag) . ')',
						$db->quoteName('type_alias') . ' = ' . $db->quote('com_newsfeeds.newsfeed'),
					)
				);

			$query->join(
				'INNER',
				'(' . $subQuery . ') AS ' . $db->quoteName('tagmap')
					. ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id')
			);
		}
		elseif ($tag = (int) $tag)
		{
			$query->join(
				'INNER',
				$db->quoteName('#__contentitem_tag_map', 'tagmap')
				. ' ON ' . $db->quoteName('tagmap.content_item_id') . ' = ' . $db->quoteName('a.id')
			)
				->where(
					array(
						$db->quoteName('tagmap.tag_id') . ' = ' . $tag,
						$db->quoteName('tagmap.type_alias') . ' = ' . $db->quote('com_newsfeeds.newsfeed'),
					)
				);
		}

		// Add the list ordering clause.
		$orderCol  = $this->state->get('list.ordering', 'a.name');
		$orderDirn = $this->state->get('list.direction', 'ASC');

		if ($orderCol == 'a.ordering' || $orderCol == 'category_title')
		{
			$orderCol = 'c.title ' . $orderDirn . ', a.ordering';
		}

		$query->order($db->escape($orderCol . ' ' . $orderDirn));

		return $query;
	}
}
fields/index.html000060400000000032152455705640010013 0ustar00<html><body></body></html>fields/iclist/index.html000060400000000032152455705640011302 0ustar00<html><body></body></html>fields/iclist/globalization.php000060400000021467152455705640012673 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.7 2015-07-12
 * @since       2.1.7
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldiClist_globalization extends JFormField
{
	protected $type='iclist_globalization';

	protected function getInput()
	{
		$lang		= JFactory::getLanguage();
		$langTag	= $lang->getTag();
		$langName	= $lang->getName();

		if ( ! file_exists(JPATH_LIBRARIES . '/ic_library/globalize/culture/' . $langTag . '.php'))
		{
			$langTag = 'en-GB';
			$currentText = JTEXT::_('COM_ICAGENDA_DATE_FORMAT_DEFAULT') . ' [' . $langTag . '] :';

		}
		else
		{
			$currentText = JTEXT::_('COM_ICAGENDA_DATE_FORMAT_CURRENT') . ' [' . $langTag . '] :';
		}

		$globalize		= JPATH_LIBRARIES . '/ic_library/globalize/culture/' . $langTag . '.php';
		$iso			= JPATH_LIBRARIES . '/ic_library/globalize/culture/iso.php';

		require_once $globalize;
		require_once $iso;

		$class		= isset($class) ? ' class="' . $class . '"' : '';
		$selected	= ' selected="selected" style="background:#D4D4D4;"';

		// Start Select List of Date Formats
		$html = '<select id="' . $this->id . '_id"' . $class . ' name="' . $this->name . '" style="width:250px;" >';

		if ($this->name != 'jform[format]' && $this->name != 'format')
		{
			$html.= '<option value="" style="text-align:center;">- ' . JTEXT::_('COM_ICAGENDA_SELECT_FORMAT') . ' -</option>';
		}

		// Date Formats in Current Language of User (admin)
		if (version_compare(JVERSION, '3.0', 'lt'))
		{
			$html.= '<optgroup label="&nbsp;"></optgroup>';
			$html.= '<optgroup label="' . $currentText . '" style="font-style:normal; color:#333333;"></optgroup>';
		}
		else
		{
			$html.= '<optgroup label="' . $currentText . '">';
		}

		$dateglobalize_array[] = array();
		$dateglobalize_array[] = $dateglobalize_1;
		$dateglobalize_array[] = $dateglobalize_2;
		$dateglobalize_array[] = $dateglobalize_3;
		$dateglobalize_array[] = $dateglobalize_4;
		$dateglobalize_array[] = isset($dateglobalize_5) ? $dateglobalize_5 : ''; // en-GB, en-US
		$dateglobalize_array[] = $dateglobalize_6;
		$dateglobalize_array[] = $dateglobalize_7;
		$dateglobalize_array[] = $dateglobalize_8;
		$dateglobalize_array[] = isset($dateglobalize_9) ? $dateglobalize_9 : ''; // en-GB
		$dateglobalize_array[] = isset($dateglobalize_10) ? $dateglobalize_10 : ''; // en-GB
		$dateglobalize_array[] = $dateglobalize_11;
		$dateglobalize_array[] = $dateglobalize_12;

		foreach ($dateglobalize_array as $format => $label)
		{
			if (isset($label) && $label)
			{
				$html.= '<option value="' . $format . '"';
				$html.= ($this->value == $format) ? $selected : '';
				$html.= '>' . $label . '</option>';
			}
		}

		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$html.= '</optgroup>';
		}


		// Other date format in English (if 'en-GB' is current language)
		if ($langTag == 'en-GB')
		{
			// Extra en-US
			if (version_compare(JVERSION, '3.0', 'lt'))
			{
				$html.= '<optgroup label="&nbsp;"></optgroup>';
				$html.= '<optgroup label="Other date format in English" style="font-style:normal; color:#333333;"></optgroup>';
				$html.= '<optgroup label="en-US (more formats if current language) :" style="font-weight:normal; color:#777777;"></optgroup>';
			}
			else
			{
				$html.= '<optgroup label="en-US (more formats if current language) :">';
			}

			$extra_array = array(
					$extravalue_1 => $extra_1,
					$extravalue_2 => $extra_2,
					$extravalue_3 => $extra_3,
					$extravalue_4 => $extra_4,
					$extravalue_5 => $extra_5,
				);

			foreach ($extra_array as $format => $label)
			{
				$html.= '<option value="' . $format . '"';
				$html.= ($this->value == $format) ? $selected : '';
				$html.= '>' . $label . '</option>';
			}

			if (version_compare(JVERSION, '3.0', 'ge'))
			{
				$html.= '</optgroup>';
			}

			// Extra en-CA
			if (version_compare(JVERSION, '3.0', 'lt'))
			{
				$html.= '<optgroup label="en-CA :" style="font-weight:normal; color:#777777;"></optgroup>';
			}
			else
			{
				$html.= '<optgroup label="en-CA :">';
			}

			$html.= '<option value="' . $extravalue_6 . '"';
			$html.= ($this->value == $extravalue_6) ? $selected : '';
			$html.= '>' . $extra_6 . '</option>';

			if (version_compare(JVERSION, '3.0', 'ge'))
			{
				$html.= '</optgroup>';
			}

			// Extra en-SG
			if (version_compare(JVERSION, '3.0', 'lt'))
			{
				$html.= '<optgroup label="en-SG :" style="font-weight:normal; color:#777777;"></optgroup>';
			}
			else
			{
				$html.= '<optgroup label="en-SG :">';
			}

			$html.= '<option value="' . $extravalue_7 . '"';
			$html.= ($this->value == $extravalue_7) ? $selected : '';
			$html.= '>' . $extra_7 . '</option>';

			if (version_compare(JVERSION, '3.0', 'ge'))
			{
				$html.= '</optgroup>';
			}
		}


		// International Date Format (ISO)
		if (version_compare(JVERSION, '3.0', 'lt'))
		{
			$html.= '<optgroup label="&nbsp;"></optgroup>';
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_ISO') . '" style="font-style:normal; color:#333333;"></optgroup>';
		}
		else
		{
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_ISO') . '">';
		}

		$html.= '<option value="' . $iso . '"';
		$html.= ($this->value == $iso) ? $selected : '';
		$html.= '>1993-04-30</option>';

		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$html.= '</optgroup>';
		}


		// Global date formats with separator
		if (version_compare(JVERSION, '3.0', 'lt'))
		{
			$html.= '<optgroup label="&nbsp;"></optgroup>';
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_SEPARATOR') . '" style="font-style:normal; color:#333333;"></optgroup>';
		}


		// DMY Little-endian (day, month, year), e.g. 22.04.96 or 22/04/96
		if (version_compare(JVERSION, '3.0', 'lt'))
		{
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_DMY') . ' :" style="font-weight:normal; color:#777777;"></optgroup>';
		}
		else
		{
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_DMY') . '">';
		}

		$dmy_array = array(
				$dmy_1 => '30␣04␣1993',
				$dmy_2 => '30␣04␣93',
				$dmy_3 => '30␣04',
				$dmy_4 => '04␣93',
				$dmy_5 => isset($dmy_text_5) ? $dmy_text_5 : '',
				$dmy_6 => isset($dmy_text_6) ? $dmy_text_6 : ''
			);

		foreach ($dmy_array as $format => $label)
		{
			if ($label)
			{
				$html.= '<option value="' . $format . '"';
				$html.= ($this->value == $format) ? $selected : '';
				$html.= '>' . $label . '</option>';
			}
		}

		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$html.= '</optgroup>';
		}


		// MDY Middle-endian (month, day, year), e.g. 04/22/96
		if (version_compare(JVERSION, '3.0', 'lt'))
		{
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_MDY') . ' :" style="font-weight:normal; color:#777777;"></optgroup>';
		}
		else
		{
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_MDY') . '">';
		}

		$mdy_array = array(
				$mdy_1 => '04␣30␣1993',
				$mdy_2 => '04␣30␣93',
				$mdy_3 => '04␣30',
				$mdy_4 => '04␣93',
				$mdy_5 => isset($mdy_text_5) ? $mdy_text_5 : '',
				$mdy_6 => isset($mdy_text_6) ? $mdy_text_6 : ''
			);

		foreach ($mdy_array as $format => $label)
		{
			if ($label)
			{
				$html.= '<option value="' . $format . '"';
				$html.= ($this->value == $format) ? $selected : '';
				$html.= '>' . $label . '</option>';
			}
		}

		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$html.= '</optgroup>';
		}


		// YMD Big-endian (year, month, day), e.g. 1996-04-22
		if (version_compare(JVERSION, '3.0', 'lt'))
		{
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_YMD') . ' :" style="font-weight:normal; color:#777777;"></optgroup>';
		}
		else
		{
			$html.= '<optgroup label="' . JTEXT::_('COM_ICAGENDA_DATE_FORMAT_YMD') . '">';
		}

		$ymd_array = array(
				$ymd_1 => '1993␣04␣30',
				$ymd_2 => '93␣04␣30',
				$ymd_3 => '04␣30',
				$ymd_4 => '93␣04',
				$ymd_5 => isset($ymd_text_5) ? $ymd_text_5 : '',
				$ymd_6 => isset($ymd_text_6) ? $ymd_text_6 : ''
			);

		foreach ($ymd_array as $format => $label)
		{
			if ($label)
			{
				$html.= '<option value="' . $format . '"';
				$html.= ($this->value == $format) ? $selected : '';
				$html.= '>' . $label . '</option>';
			}
		}

		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$html.= '</optgroup>';
		}

		$html.= '</select>';

		return $html;
	}
}
fields/icmap/lat.php000060400000004112152455705640010403 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rez�, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rez� (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.0 2015-02-15
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Returns Latitude from Google Maps address auto-complete field.
 */
class JFormFieldiCmap_lat extends JFormField
{
	protected $type='icmap_lat';

	protected function getInput()
	{
		// Check if coords set (deprecated)
		$id = JRequest::getVar('id');

		$class = isset($this->class) ? ' class="' . $this->class . '"' : '';

		if (isset($id))
		{
			$db	= JFactory::getDBO();
			$db->setQuery(
				'SELECT a.coordinate' .
				' FROM #__icagenda_events AS a' .
				' WHERE a.id = '.(int) $id
			);

			$coords = $db->loadResult();
		}
		else
		{
			$coords = NULL;
		}

		$session = JFactory::getSession();
		$ic_submit_lat = $session->get('ic_submit_lat', '');

		$lat_value = $ic_submit_lat ? $ic_submit_lat : $this->value;

		if ($coords != NULL
			&& $lat_value == '0.0000000000000000')
		{
			$ex			= explode(', ', $coords);
			$lat_value	= $ex[0];
		}
		elseif ($lat_value != '0.0000000000000000')
		{
			$lat_value	= $lat_value;
		}
		else
		{
			$lat_value	= NULL;
		}

		$html= '<div class="clr"></div>';
		$html.= '<label class="icmap-label">' . JText::_('COM_ICAGENDA_GOOGLE_MAPS_LATITUDE_LBL') . '</label> <input name="' . $this->name . '" id="lat" type="text"' . $class . ' value="' . $lat_value . '"/>';

		// clear the data so we don't process it again
		$session->clear('ic_submit_lat');

		return $html;
	}
}

fields/icmap/city.php000060400000003031152455705640010572 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rez�, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rez� (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.0 2015-02-25
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Returns City from Google Maps address auto-complete field.
 */
class JFormFieldiCmap_city extends JFormField
{
	protected $type='icmap_city';

	protected function getInput()
	{
		$session = JFactory::getSession();
		$ic_submit_city = $session->get('ic_submit_city', '');

		$city_value = $ic_submit_city ? $ic_submit_city : $this->value;

		$class = isset($this->class) ? ' class="' . $this->class . '"' : '';

		$html = '<div class="clr"></div>';
		$html.= '<label class="icmap-label">' . JText::_('COM_ICAGENDA_FORM_LBL_EVENT_CITY') . '</label> <input name="' . $this->name . '" id="locality" type="text"' . $class . ' value="' . $city_value . '"/>';

		// clear the data so we don't process it again
		$session->clear('ic_submit_city');

		return $html;
	}
}
fields/icmap/index.html000060400000000032152455705640011104 0ustar00<html><body></body></html>fields/icmap/lng.php000060400000004112152455705640010403 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rez�, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rez� (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.0 2015-02-15
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Returns Latitude from Google Maps address auto-complete field.
 */
class JFormFieldiCmap_lng extends JFormField
{
	protected $type='icmap_lng';

	protected function getInput()
	{
		// Check if coords set (deprecated)
		$id = JRequest::getVar('id');

		$class = isset($this->class) ? ' class="' . $this->class . '"' : '';

		if (isset($id))
		{
			$db	= JFactory::getDBO();
			$db->setQuery(
				'SELECT a.coordinate' .
				' FROM #__icagenda_events AS a' .
				' WHERE a.id = '.(int) $id
			);

			$coords = $db->loadResult();
		}
		else
		{
			$coords = NULL;
		}

		$session = JFactory::getSession();
		$ic_submit_lng = $session->get('ic_submit_lng', '');

		$lng_value = $ic_submit_lng ? $ic_submit_lng : $this->value;

		if ($coords != NULL
			&& $lng_value == '0.0000000000000000')
		{
			$ex			= explode(', ', $coords);
			$lng_value	= $ex[1];
		}
		elseif ($lng_value != '0.0000000000000000')
		{
			$lng_value	= $lng_value;
		}
		else
		{
			$lng_value	= NULL;
		}

		$html= '<div class="clr"></div>';
		$html.= '<label class="icmap-label">' . JText::_('COM_ICAGENDA_GOOGLE_MAPS_LONGITUDE_LBL') . '</label> <input name="' . $this->name . '" id="lng" type="text"' . $class . ' value="' . $lng_value . '"/>';

		// clear the data so we don't process it again
		$session->clear('ic_submit_lng');

		return $html;
	}
}
fields/icmap/country.php000060400000003072152455705640011332 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rez�, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rez� (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.0 2015-02-25
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Returns Country from Google Maps address auto-complete field.
 */
class JFormFieldiCmap_country extends JFormField
{
	protected $type='icmap_country';

	protected function getInput()
	{
		$session = JFactory::getSession();
		$ic_submit_country = $session->get('ic_submit_country', '');

		$country_value = $ic_submit_country ? $ic_submit_country : $this->value;

		$class = isset($this->class) ? ' class="' . $this->class . '"' : '';

		$html = '<div class="clr"></div>';
		$html.= '<label class="icmap-label">' . JText::_('COM_ICAGENDA_FORM_LBL_EVENT_COUNTRY') . '</label> <input name="' . $this->name . '" id="country" type="text"' . $class . ' value="' . $country_value . '" />';

		// clear the data so we don't process it again
		$session->clear('ic_submit_country');

		return $html;
	}
}
fields/modal/tos_article.php000060400000015034152455705640012143 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.0 2013-09-18
 * @since       3.2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

/**
 * Supports a modal article picker.
 */
class JFormFieldModal_tos_article extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type = 'modal_tos_article';

//	protected function getLabel()
//	{
//	   return ' ';
//	}

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		$icagendaParams = JComponentHelper::getParams('com_icagenda');
		$tos_Type = $icagendaParams->get('tos_Type', '1');

		$allowEdit		= ((string) $this->element['edit'] == 'true') ? true : false;
		$allowClear		= ((string) $this->element['clear'] != 'false') ? true : false;

		// Load language
		JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR);

		// Load the modal behavior script.
		JHtml::_('behavior.modal', 'a.modal');

		// Build the script.
		$script = array();

		// Select button script
		$script[] = '	function jSelectArticle_'.$this->id.'(id, title, catid, object) {';
		$script[] = '		document.getElementById("'.$this->id.'_id").value = id;';
		$script[] = '		document.getElementById("'.$this->id.'_name").value = title;';

		if ($allowEdit)
		{
			$script[] = '		jQuery("#'.$this->id.'_edit").removeClass("hidden");';
		}

		if ($allowClear)
		{
			$script[] = '		jQuery("#'.$this->id.'_clear").removeClass("hidden");';
		}

		$script[] = '		SqueezeBox.close();';
		$script[] = '	}';

		// Clear button script
		static $scriptClear;

		if ($allowClear && !$scriptClear)
		{
			$scriptClear = true;

			$script[] = '	function jClearArticle(id) {';
			$script[] = '		document.getElementById(id + "_id").value = "";';
			$script[] = '		document.getElementById(id + "_name").value = "'.htmlspecialchars(JText::_('COM_CONTENT_SELECT_AN_ARTICLE', true), ENT_COMPAT, 'UTF-8').'";';
			$script[] = '		jQuery("#"+id + "_clear").addClass("hidden");';
			$script[] = '		if (document.getElementById(id + "_edit")) {';
			$script[] = '			jQuery("#"+id + "_edit").addClass("hidden");';
			$script[] = '		}';
			$script[] = '		return false;';
			$script[] = '	}';
		}

		// Add the script to the document head.
		JFactory::getDocument()->addScriptDeclaration(implode("\n", $script));

		// Setup variables for display.
		$html	= array();
		$link	= 'index.php?option=com_content&amp;view=articles&amp;layout=modal&amp;tmpl=component&amp;function=jSelectArticle_'.$this->id;

		if (isset($this->element['language']))
		{
			$link .= '&amp;forcedLanguage='.$this->element['language'];
		}

		$db	= JFactory::getDbo();
		$db->setQuery(
			'SELECT title' .
			' FROM #__content' .
			' WHERE id = '.(int) $this->value
		);

		try
		{
			$title = $db->loadResult();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $e->getMessage());
		}

		if (empty($title))
		{
			$title = JText::_('COM_CONTENT_SELECT_AN_ARTICLE');
		}
		$title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

		// The active article id field.
		if (0 == (int) $this->value)
		{
			$value = '';
		}
		else
		{
			$value = (int) $this->value;
		}

		// The current article display field.
		$html[] = '<div id="ic_article"><fieldset class="span9 iCleft"><div>&nbsp;</div><span class="input-append">';
		$html[] = '<input type="text" class="input-medium" style="margin:0px" id="'.$this->id.'_name" value="'.$title.'" disabled="disabled" size="35" />';

		if(version_compare(JVERSION, '3.0', 'lt')) {
			$html[] = '<a class="modal btn hasTooltip" title="'.JText::_('COM_CONTENT_CHANGE_ARTICLE').'"  href="'.$link.'&amp;'.JSession::getFormToken().'=1" rel="{handler: \'iframe\', size: {x: 800, y: 450}}">'.JText::_('JSELECT').'</a>';
		} else {
			$html[] = '<a class="modal btn hasTooltip" title="'.JHtml::tooltipText('COM_CONTENT_CHANGE_ARTICLE').'"  href="'.$link.'&amp;'.JSession::getFormToken().'=1" rel="{handler: \'iframe\', size: {x: 800, y: 450}}"><i class="icon-file"></i> '.JText::_('JSELECT').'</a>';
		}

		// Edit article button
		if ($allowEdit)
		{
			if(version_compare(JVERSION, '3.0', 'lt')) {
				$html[] = '<a class="btn hasTooltip'.($value ? '' : ' hidden').'" href="index.php?option=com_content&view=article&layout=edit&id=' . $value. '" target="_blank" title="'.JText::_('COM_CONTENT_EDIT_ARTICLE').'" alt="'.JText::_('COM_CONTENT_EDIT_ARTICLE').'" >' . JText::_('JACTION_EDIT') . '</a>';
			} else {
				$html[] = '<a class="btn hasTooltip'.($value ? '' : ' hidden').'" href="index.php?option=com_content&layout=modal&tmpl=component&task=article.edit&id=' . $value. '" target="_blank" title="'.JHtml::tooltipText('COM_CONTENT_EDIT_ARTICLE').'" ><span class="icon-edit"></span> ' . JText::_('JACTION_EDIT') . '</a>';
			}
		}

		// Clear article button
		if ($allowClear)
		{
			if(version_compare(JVERSION, '3.0', 'lt')) {
				$html[] = '<a id="'.$this->id.'_clear" class="btn'.($value ? '' : ' hidden').'" onclick="return jClearArticle(\''.$this->id.'\')">' . JText::_('JCLEAR') . '</a>';
			} else {
				$html[] = '<button id="'.$this->id.'_clear" class="btn'.($value ? '' : ' hidden').'" onclick="return jClearArticle(\''.$this->id.'\')"><span class="icon-remove"></span> ' . JText::_('JCLEAR') . '</button>';
			}
		}

		$html[] = '</span>';

		// class='required' for client side validation
		$class = '';
		if ($this->required)
		{
			$class = ' class="required modal-value"';
		}


		$html[] = '<input type="hidden" id="'.$this->id.'_id"'.$class.' name="'.$this->name.'" value="'.$value.'" /></fieldset></div>';

//		if ($tos_Type == 'on') {
//			$tos_Type = '1';
//		}
		if ($tos_Type == '1') {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("ic_default").style.display = "none";';
			$html[] = 'document.getElementById("ic_article").style.display = "block";';
			$html[] = 'document.getElementById("tos_custom").style.display = "none";';
			$html[] = '</script>';
		} else {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("ic_article").style.display = "none";';
			$html[] = '</script>';
		}


		return implode("\n", $html);
	}
}
fields/modal/evt_date.php000060400000007245152455705640011433 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.9 2015-07-30
 * @since       3.3.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_evt_date extends JFormField
{
	protected $type = 'modal_evt_date';

	protected function getInput()
	{
		$jinput	= JFactory::getApplication()->input;
		$view	= $jinput->get('view');

		$id		= ($view == 'mail') ? $jinput->get('eventid', '0') : $jinput->get('id', '0');

		if ($id != 0)
		{
			$db		= JFactory::getDbo();
			$query	= $db->getQuery(true);
			$query->select('r.id as reg_id, r.date AS reg_date, r.period AS reg_period, r.eventid AS reg_eventid, sum(r.people) AS reg_count')
				->from('`#__icagenda_registration` AS r');

			if ($view == 'mail')
			{
				$query->where('r.state = 1');
				$query->group('r.date');
			}

			$query->where('r.eventid = ' . (int) $id);

			$db->setQuery($query);

			if ($view == 'mail')
			{
				$result = $db->loadObjectList();
			}
			else
			{
				$result = $db->loadObject();
				$event_id	= $result->reg_eventid;
				$saveddate	= $result->reg_date;
			}
		}
		elseif ($view == 'registration')
		{
			$event_id	= '';
			$saveddate	= '';
		}

		if ($view == 'registration')
		{
			// Test if date saved in in datetime data format
			$date_is_datetime_sql	= false;
			$array_ex_date			= array('-', ' ', ':');
			$d_ex					= str_replace($array_ex_date, '-', $saveddate);
			$d_ex					= explode('-', $d_ex);

			if (count($d_ex) > 4)
			{
				if (   strlen($d_ex[0]) == 4
					&& strlen($d_ex[1]) == 2
					&& strlen($d_ex[2]) == 2
					&& strlen($d_ex[3]) == 2
					&& strlen($d_ex[4]) == 2   )
				{
					$date_is_datetime_sql = true;
				}
			}

			// Test if registered date before 3.3.3 could be converted
			// Control if new date format (Y-m-d H:i:s)
			$input		= trim($saveddate);
			$is_valid	= date('Y-m-d H:i:s', strtotime($input)) == $input;

			if ($is_valid
				&& strtotime($saveddate))
			{
				$date_get		= explode (' ', $saveddate);
				$saved_date		= $date_get['0'];
				$saved_time		= date('H:i:s', strtotime($date_get['1']));
			}
			else
			{
				// Explode to test if stored in old format in database
				$ex_saveddate	= explode (' - ', $saveddate);
				$saved_date		= isset($ex_saveddate['0']) ? trim($ex_saveddate['0']) : '';
				$saved_time		= isset($ex_saveddate['1']) ? trim(date('H:i:s', strtotime($ex_saveddate['1']))) : '';
			}

			$data_eventid = $event_id;

			$eventid_url = JRequest::getVar('eventid', '');

			if ( ! $date_is_datetime_sql && $saveddate )
			{
				$saveddate_text = '"<b>' . $saveddate . '</b>"';
				echo '<div class="ic-alert ic-alert-note"><span class="iCicon-info"></span> <strong>' . JText::_('NOTICE') . '</strong><br />'
					. JText::sprintf('COM_ICAGENDA_REGISTRATION_ERROR_DATE_CONTROL', $saveddate_text) . '</div>';
			}

			$event_id = isset($event_id) ? $eventid_url : '';

			$html = '<select name="' . $this->name . '" id="' . $this->id . '_id" data-chosen="true"></select>';
		}
		else
		{
			$html = '<select name="' . $this->name . '" id="' . $this->id . '_id" data-chosen="true"></select>';
		}

		return $html;
	}
}
fields/modal/ph_regbt.php000060400000002610152455705640011421 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.1.3 2013-08-08
 * @since       3.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ph_regbt extends JFormField
{
	protected $type='modal_ph_regbt';

	protected function getInput()
	{
		$class = JRequest::getVar('class');

		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');
		$extRegButtonText = $icagendaParams->get('RegButtonText');

		if (!isset($extRegButtonText)) { $extRegButtonText = JText::_( 'COM_ICAGENDA_REGISTRATION_REGISTER'); }

		$html ='<input type="text" id="'.$this->id.'" class="'.$class.'" name="'.$this->name.'" value="'.$this->value.'" placeholder="'.$extRegButtonText.'"/>';

		return $html;
	}
}
fields/modal/icvalue_field.php000060400000003350152455705640012424 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.3 2013-10-17
 * @since       3.2.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_icvalue_field extends JFormField
{
	protected $type='modal_icvalue_field';

	protected function getInput()
	{

		$Explode = explode('_', $this->name);
		$TypeName = $Explode[0].']';

		$replace = array("jform", "[params]", "[", "]");
		$name = str_replace($replace, "", $TypeName);

		$Type_default = $name.'_default';
		$Type_content = $name.'_custom';

		$html	= array();

		$html[] = '<div id="'.$Type_content.'"><fieldset class="span9 iCleft">';
		$html[] = '<input type="text" value="'.$this->value.'" name="'.$this->name.'"/>';
		$html[] = '</fieldset></div>';

		$html[] = '<script type="text/javascript">';
		$html[] = 'if (typeset == 1) {';
		$html[] = 'document.getElementById("'.$Type_content.'").style.display = "block";';
		$html[] = '}';
		$html[] = 'if (typeset == 0) {';
		$html[] = 'document.getElementById("'.$Type_content.'").style.display = "none";';
		$html[] = '}';
		$html[] = '</script>';

		return implode("\n", $html);
	}
}
fields/modal/ictextarea_counter.php000060400000013220152455705640013516 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.0 2015-02-14
 * @since       3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Textarea with a counter. Short Description and Meta Description
 *
 * @package		iCagenda
 * @subpackage	com_icagenda
 * @since		3.4.0
 */
class JFormFieldModal_ictextarea_counter extends JFormField
{
	protected $type = 'modal_ictextarea_counter';

	protected function getInput()
	{
		$app		= JFactory::getApplication();
		$replace	= array("jform", "[", "]");
		$name		= str_replace($replace, "", $this->name);
		$nb_chars	= strlen(trim(utf8_decode($this->value)));
		$class		= !empty($this->class) ? ' class="' . $this->class . '"' : '';

		if ($app->isAdmin())
		{
			$params	= JComponentHelper::getParams('com_icagenda');
			$iCparams	= JComponentHelper::getParams('com_icagenda');
		}
		else
		{
			$params	= $app->getParams();
			$iCparams	= JComponentHelper::getParams('com_icagenda');
		}

		$session = JFactory::getSession();
		$ic_submit_shortdesc = $session->get('ic_submit_shortdesc', '');
		$ic_submit_metadesc = $session->get('ic_submit_metadesc', '');

		$event_shortdesc = $ic_submit_shortdesc ? $ic_submit_shortdesc : $this->value;
		$event_metadesc = $ic_submit_metadesc ? $ic_submit_metadesc : $this->value;

		if ($name == 'shortdesc')
		{
			$ic_max_component	= $iCparams->get('char_limit_short_description', '100');
			$ic_max				= $params->get('char_limit_short_description', '100');
			$ic_max				= ($ic_max_component >= $ic_max) ? $ic_max : $ic_max_component;
		}
		elseif ($name == 'metadesc')
		{
			$ic_max_component	= $iCparams->get('char_limit_meta_description', '160');
			$ic_max				= $params->get('char_limit_meta_description', '160');
			$ic_max				= ($ic_max_component >= $ic_max) ? $ic_max : $ic_max_component;
		}
		else
		{
			$ic_max = $params->get('ShortDescLimit', '100');
		}

		// Alert if text stored in the database exceeds the character limit currently set.
		$display_alert	= ($nb_chars > $ic_max) ? true : false;

		$count_value = $nb_chars ? ($ic_max-$nb_chars) : $ic_max;
		$ic_size = (strlen($ic_max))-1;
		$ic_size = $ic_size ? $ic_size : '1';

		$counter_input = '<input id="' . $name . '-counter"';
//		$counter_input.= ' onblur="iCtextCounter(this.form.' . $this->name . ', this, ' . $ic_max . ');"';
		$counter_input.= ' class="valid"';
//		$counter_input.= ' onfocus="this.blur();"';
//		$counter_input.= ' tabindex="999" maxlength="' . $ic_size . '" size="' . $ic_size . '"';
		$counter_input.= ' size="' . $ic_size . '"';
		$counter_input.= ' value="' . $count_value . '"';
		$counter_input.= ' name="counter_' . $name . '">';

		$html = '<div>';

		if ($display_alert)
		{
			$html.= '<div class="alert alert-danger"><h3>Warning</h3><strong>'
					. JText::sprintf('COM_ICAGENDA_ALERT_S_TEXT_S_EXCEEDS_CHARACTER_LIMIT', $this->title) . '</strong><br />'
					. JText::_('COM_ICAGENDA_ALERT_EDIT_TEXT_TO_FIT_CHAR_LIMIT') . '<br /><br /><u>'
					. JText::sprintf('COM_ICAGENDA_ALERT_S_TEXT_S_CURRENTLY_STORED_IN_DATABASE', $this->title) . '</u> :<br/><i>'
					. $this->value . '</i></div>';
		}
		$html.= '<textarea';
		$html.= ' onKeyPress="iCtextCounter(this, this.form.counter_' . $name.', ' . $ic_max . ');"';
		$html.= ' onKeyUp="iCtextCounter(' . $name . ', counter_' . $name . ', ' . $ic_max . ');"';
		$html.= ' onkeydown="iCtextCounter(' . $name . ', counter_' . $name . ', ' . $ic_max . ');"';
		$html.= ' onmouseout="iCtextCounter(' . $name . ', counter_' . $name . ', ' . $ic_max . ');"';
//		$html.= ' onpaste="' . $name . 'useractions();"';
		$html.= $class . ' name="' . $this->name . '" id="' . $name . '">';

		if ($name == 'shortdesc')
		{
			$html.= $event_shortdesc;

			// clear the data so we don't process it again
			$session->clear('ic_submit_shortdesc');
		}
		elseif ($name == 'metadesc')
		{
			$html.= $event_metadesc;

			// clear the data so we don't process it again
			$session->clear('ic_submit_metadesc');
		}
		else
		{
			$html.= $this->value;
		}

		$html.= '</textarea>';

		$html.= '</div>';
		$html.= '<div id="'.$name.'-counter-container" class="ic-counter-container">';
		$html.= '<div class="ic-counter">';
		$html.= JText::sprintf('COM_ICAGENDA_MAXIMUM_N_CHARACTERS', $ic_max);
		$html.= '</div> ';
		$html.= '<div class="ic-counter">';
		$html.= JText::sprintf('COM_ICAGENDA_N_REMAINING', $counter_input);
		$html.= '</div>';
		$html.= '</div>';
		$html.= '<div>&nbsp;</div>';

//		$html.= '<textarea';
//		$html.= ' onMouseOut="CheckFieldLength(this.' . $name . ', \'' . $name . '_charcount\', \'' . $name . '_remaining\', 140);"';
//		$html.= ' onKeyDown="CheckFieldLength(this.' . $name . ', \'' . $name . '_charcount\', \'' . $name . '_remaining\', 140);"';
//		$html.= ' onkeyup="CheckFieldLength(this.' . $name . ', \'' . $name . '_charcount\', \'' . $name . '_remaining\', 140);"';
//		$html.= $class . ' name="' . $this->name . '" id ="' . $name . '">';
//		$html.= '</textarea>';
//		$html.= '<h2><span id="' . $name . '_charcount">0</span> characters entered   | <span id="' . $name . '_remaining">140</span> characters remaining</h2>';

		return $html;
	}
}
fields/modal/thumbs.php000060400000011033152455705640011130 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.2 2015-03-13
 * @since       3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_thumbs extends JFormField
{
	protected $type='modal_thumbs';

	protected function getInput()
	{
		$replace = array("jform", "params", "[", "]");
		$name_input = str_replace($replace, "", $this->name);

		jimport('joomla.application.component.helper');
		$iCparams = JComponentHelper::getParams('com_icagenda');

		if ($name_input == 'thumb_large')
		{
			$thumbOptions = $iCparams->get('thumb_large');
			$width = is_numeric($thumbOptions[0]) ? $thumbOptions[0] : '900';
			$height = is_numeric($thumbOptions[1]) ? $thumbOptions[1] : '600';
			$quality = is_numeric($thumbOptions[2]) ? $thumbOptions[2] : '100';
			$crop = $thumbOptions[3] ? $thumbOptions[3] : false;
			$default_width = '900';
			$default_height = '600';
			$default_quality = '100';
			$default_crop = '0';
		}
		elseif ($name_input == 'thumb_medium')
		{
			$thumbOptions = $iCparams->get('thumb_medium');
			$width = is_numeric($thumbOptions[0]) ? $thumbOptions[0] : '300';
			$height = is_numeric($thumbOptions[1]) ? $thumbOptions[1] : '300';
			$quality = is_numeric($thumbOptions[2]) ? $thumbOptions[2] : '100';
			$crop = $thumbOptions[3] ? $thumbOptions[3] : false;
			$default_width = '300';
			$default_height = '300';
			$default_quality = '100';
			$default_crop = '0';
		}
		elseif ($name_input == 'thumb_small')
		{
			$thumbOptions = $iCparams->get('thumb_small');
			$width = is_numeric($thumbOptions[0]) ? $thumbOptions[0] : '100';
			$height = is_numeric($thumbOptions[1]) ? $thumbOptions[1] : '100';
			$quality = is_numeric($thumbOptions[2]) ? $thumbOptions[2] : '100';
			$crop = $thumbOptions[3] ? $thumbOptions[3] : false;
			$default_width = '100';
			$default_height = '100';
			$default_quality = '100';
			$default_crop = '0';
		}
		elseif ($name_input == 'thumb_xsmall')
		{
			$thumbOptions = $iCparams->get('thumb_xsmall');
			$width = is_numeric($thumbOptions[0]) ? $thumbOptions[0] : '48';
			$height = is_numeric($thumbOptions[1]) ? $thumbOptions[1] : '48';
			$quality = is_numeric($thumbOptions[2]) ? $thumbOptions[2] : '80';
			$crop = $thumbOptions[3] ? $thumbOptions[3] : true;
			$default_width = '48';
			$default_height = '48';
			$default_quality = '80';
			$default_crop = '1';
		}

		$crop_false = $crop_true = '';

		if (!empty($crop))
		{
			$crop_true = ' selected="selected"';
		}
		else
		{
			$crop_false = ' selected="selected"';
		}

		$quality_80 = '';

		if ($quality == '80')
		{
			$quality_80 =  ' selected="selected"';
		}

		$quality_values = array('100', '95', '90', '85', '80', '75', '70', '60', '50');

		$html = array();

		$html[] = '<div class="span2">' . JText::_('IC_WIDTH') . '<br />';
		$html[] = '<input type="text" class="input-mini" name="'.$this->name.'[]" value="'.$width.'" default="'.$default_width.'"/></div>';

		$html[] = '<div class="span2">' . JText::_('IC_HEIGHT') . '<br />';
		$html[] = '<input type="text" class="input-mini" name="'.$this->name.'[]" value="'.$height.'" default="'.$default_height.'"/></div>';

		$html[] = '<div class="span2">' . JText::_('IC_QUALITY') . '<br />';
		$html[] = '<select id="ThumbMedium_quality" class="input-small" name="'.$this->name.'[]" value="'.$quality.'">';

		foreach ($quality_values AS $qv)
		{
			$html[] = '<option value="'.$qv.'"';

			if ($qv == $quality)
			{
				$html[] = ' selected="selected"';
			}

			$html[] = '>' . JText::_('IC'.$qv.'') . '</option>';
		}

		$html[] = '</select></div>';

		$html[] = '<div class="span2">' . JText::_('IC_CROPPED') . '<br />';
		$html[] = '<select id="ThumbMedium_crop" class="input-small" name="' . $this->name . '[]" value="' . $crop . '">';
		$html[] = '<option value="0" ' . $crop_false . '>'.JText::_('JNO').'</option>';
		$html[] = '<option value="1" ' . $crop_true . '>'.JText::_('JYES').'</option>';
		$html[] = '</select></div>';

		return implode("\n", $html);
	}
}
fields/modal/startdate.php000060400000003111152455705640011617 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.10 2015-08-13
 * @since       2.0.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.filesystem.path');
jimport('joomla.form.formfield');

/**
 * Form Field to load a startdate datetime picker input
 *
 * @since	2.0.0
 */
class JFormFieldModal_startdate extends JFormField
{
	protected $type = 'modal_startdate';

	protected function getInput()
	{
		$class = ! empty($this->class) ? ' class="' . $this->class . '"' : '';

		$lang = JFactory::getLanguage();

		if ($lang->getTag() == 'fa-IR')
		{
			// Including fallback code for HTML5 non supported browsers.
			JHtml::_('jquery.framework');
			JHtml::_('script', 'system/html5fallback.js', false, true);

			$attributes = '';

			$html = JHtml::_('calendar', $this->value, $this->name, 'startdate_jalali', '%Y-%m-%d %H:%M:%S', $attributes);
		}
		else
		{
			$html ='<input type="text" id="startdate"' . $class . ' name="' . $this->name . '" value="' . $this->value . '"/>';
		}

		return $html;
	}
}
fields/modal/ictxt_content.php000060400000003772152455705640012526 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.5 2013-11-10
 * @since       3.2.5
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ictxt_content extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type = 'modal_ictxt_content';

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');

		$replace = array("jform", "[", "]", "Content");
		$name = str_replace($replace, "", $this->name);

		$tosContent = $icagendaParams->get($name.'Content', '');
		$tos_Type = $icagendaParams->get($name.'_Type', '');

		$editor = JFactory::getEditor();

		$html	= array();

		$html[] = '<div id="'.$name.'_custom"><fieldset class="span9 iCleft">';
		$html[] = $editor->display($this->name, $tosContent, "100%", "300", "300", "20", 1, null, null, null, array('mode' => 'advanced'));
		$html[] = '</fieldset></div>';

		if ($tos_Type == '2') {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("'.$name.'_custom").style.display = "block";';
			$html[] = '</script>';
		} else {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("'.$name.'_custom").style.display = "none";';
			$html[] = '</script>';
		}

		return implode("\n", $html);
	}
}
fields/modal/coordinate.php000060400000002731152455705640011762 0ustar00<?php
/** 
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 * 
 * @update		2013-04-18
 * @version		2.1.7
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');


class JFormFieldModal_coordinate extends JFormField
{
	protected $type='modal_coordinate';
	
	protected function getInput()
	{	
		$def=JRequest::getVar('def');
		if ($def=='')$def=$this->value;
	
	
	
		$html= '
			<!--div class="clr"></div>
			<div id="map_canvas" style="width:100%; height:300px"></div><br/>
			<label>'.JText::_('COM_ICAGENDA_FORM_LBL_EVENT_GPS').'</label>&nbsp;<input name="'.$this->name.'" id="jform_coordinate" type="text" size="41" value="'.$def.'"/-->
			<div class="clr"></div>
			<!--input name="latitude" id="lat" type="text"/>
			<input name="longitude" id="lng" type="text"/-->';

		
			$html.= '<input name="'.$this->name.'" id="lat" type="text" size="41" value="'.$this->value.'"/>
		<!--script>
			document.getElementById("coords").value=document.getElementById("lat").value+", "+document.getElementById("lng").value;
		</script-->';

		return $html;
	}
}fields/modal/checkdnsrr.php000060400000003055152455705640011761 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.1.7 2013-08-28
 * @since       3.1.7
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_checkdnsrr extends JFormField
{
	protected $type='modal_checkdnsrr';

	protected function getInput()
	{
		$test='0';
		if (function_exists('checkdnsrr')) {
			$test='1';
		}
		if ($test!=1) {
			if(version_compare(JVERSION, '3.0', 'lt')) {
				$html='<label style="color:red"><b> '.JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_CHECKDNSRR_NOT_PRESENT_1').'</b><br/>'.JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_CHECKDNSRR_NOT_PRESENT_2').'</label><br/>';
			} else {
				$html='<div class="alert alert-error"><span class="icon-warning"></span><b> '.JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_CHECKDNSRR_NOT_PRESENT_1').'</b><br/>'.JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_CHECKDNSRR_NOT_PRESENT_2').'</div>';
			}
			return $html;
		} else {
			return false;
		}

	}
}
fields/modal/period.php000060400000002542152455705640011115 0ustar00<?php
/** 
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 * 
 * @since		1.3
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');


JText::script('COM_ICAGENDA_TP_CURRENT');
JText::script('COM_ICAGENDA_TP_CLOSE');
JText::script('COM_ICAGENDA_TP_TITLE');
JText::script('COM_ICAGENDA_TP_TIME');
JText::script('COM_ICAGENDA_TP_HOUR');
JText::script('COM_ICAGENDA_TP_MINUTE');


class JFormFieldModal_period extends JFormField
{
	protected $type='modal_period';
	
	protected function getInput()
	{
		$html ='<script>
		$(function(){
			$(\'#jform_period\').datetimepicker({
				dateFormat: \'yy-mm-dd\',
				hourGrid: 4,
				minuteGrid: 10
			});
		})

		</script>
		<input type="text" id="'.$this->id.'" class="'.$this->class.'" name="'.$this->name.'" value="'.$this->value.'"/>';
		$html ='<input type="text" id="'.$this->id.'" class="'.$this->class.'" name="'.$this->name.'" value="'.$this->value.'"/>';
			
		return $html;
	}
}fields/modal/ictxt_article.php000060400000014612152455705640012472 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.5 2013-11-10
 * @since       3.2.5
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

/**
 * Supports a modal article picker.
 */
class JFormFieldModal_ictxt_article extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type = 'modal_ictxt_article';

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		$icagendaParams = JComponentHelper::getParams('com_icagenda');

		$replace = array("jform", "[", "]", "Article");
		$name = str_replace($replace, "", $this->name);

		$tos_Type = $icagendaParams->get($name.'_Type', '');

		$allowEdit		= ((string) $this->element['edit'] == 'true') ? true : false;
		$allowClear		= ((string) $this->element['clear'] != 'false') ? true : false;

		// Load language
		JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR);

		// Load the modal behavior script.
		JHtml::_('behavior.modal', 'a.modal');

		// Build the script.
		$script = array();

		// Select button script
		$script[] = '	function jSelectArticle_'.$this->id.'(id, title, catid, object) {';
		$script[] = '		document.getElementById("'.$this->id.'_id").value = id;';
		$script[] = '		document.getElementById("'.$this->id.'_name").value = title;';

		if ($allowEdit)
		{
			$script[] = '		jQuery("#'.$this->id.'_edit").removeClass("hidden");';
		}

		if ($allowClear)
		{
			$script[] = '		jQuery("#'.$this->id.'_clear").removeClass("hidden");';
		}

		$script[] = '		SqueezeBox.close();';
		$script[] = '	}';

		// Clear button script
		static $scriptClear;

		if ($allowClear && !$scriptClear)
		{
			$scriptClear = true;

			$script[] = '	function jClearArticle(id) {';
			$script[] = '		document.getElementById(id + "_id").value = "";';
			$script[] = '		document.getElementById(id + "_name").value = "'.htmlspecialchars(JText::_('COM_CONTENT_SELECT_AN_ARTICLE', true), ENT_COMPAT, 'UTF-8').'";';
			$script[] = '		jQuery("#"+id + "_clear").addClass("hidden");';
			$script[] = '		if (document.getElementById(id + "_edit")) {';
			$script[] = '			jQuery("#"+id + "_edit").addClass("hidden");';
			$script[] = '		}';
			$script[] = '		return false;';
			$script[] = '	}';
		}

		// Add the script to the document head.
		JFactory::getDocument()->addScriptDeclaration(implode("\n", $script));

		// Setup variables for display.
		$html	= array();
		$link	= 'index.php?option=com_content&amp;view=articles&amp;layout=modal&amp;tmpl=component&amp;function=jSelectArticle_'.$this->id;

		if (isset($this->element['language']))
		{
			$link .= '&amp;forcedLanguage='.$this->element['language'];
		}

		$db	= JFactory::getDbo();
		$db->setQuery(
			'SELECT title' .
			' FROM #__content' .
			' WHERE id = '.(int) $this->value
		);

		try
		{
			$title = $db->loadResult();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $e->getMessage());
		}

		if (empty($title))
		{
			$title = JText::_('COM_CONTENT_SELECT_AN_ARTICLE');
		}
		$title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

		// The active article id field.
		if (0 == (int) $this->value)
		{
			$value = '';
		}
		else
		{
			$value = (int) $this->value;
		}

		// The current article display field.
		$html[] = '<div id="'.$name.'_article"><fieldset class="span9 iCleft"><div>&nbsp;</div><span class="input-append">';
		$html[] = '<input type="text" class="input-medium" style="margin:0px" id="'.$this->id.'_name" value="'.$title.'" disabled="disabled" size="35" />';

		if(version_compare(JVERSION, '3.0', 'lt')) {
			$html[] = '<a class="modal btn hasTooltip" title="'.JText::_('COM_CONTENT_CHANGE_ARTICLE').'"  href="'.$link.'&amp;'.JSession::getFormToken().'=1" rel="{handler: \'iframe\', size: {x: 800, y: 450}}">'.JText::_('JSELECT').'</a>';
		} else {
			$html[] = '<a class="modal btn hasTooltip" title="'.JHtml::tooltipText('COM_CONTENT_CHANGE_ARTICLE').'"  href="'.$link.'&amp;'.JSession::getFormToken().'=1" rel="{handler: \'iframe\', size: {x: 800, y: 450}}"><i class="icon-file"></i> '.JText::_('JSELECT').'</a>';
		}

		// Edit article button
		if ($allowEdit)
		{
			if(version_compare(JVERSION, '3.0', 'lt')) {
				$html[] = '<a class="btn hasTooltip'.($value ? '' : ' hidden').'" href="index.php?option=com_content&view=article&layout=edit&id=' . $value. '" target="_blank" title="'.JText::_('COM_CONTENT_EDIT_ARTICLE').'" alt="'.JText::_('COM_CONTENT_EDIT_ARTICLE').'" >' . JText::_('JACTION_EDIT') . '</a>';
			} else {
				$html[] = '<a class="btn hasTooltip'.($value ? '' : ' hidden').'" href="index.php?option=com_content&layout=modal&tmpl=component&task=article.edit&id=' . $value. '" target="_blank" title="'.JHtml::tooltipText('COM_CONTENT_EDIT_ARTICLE').'" ><span class="icon-edit"></span> ' . JText::_('JACTION_EDIT') . '</a>';
			}
		}

		// Clear article button
		if ($allowClear)
		{
			if(version_compare(JVERSION, '3.0', 'lt')) {
				$html[] = '<a id="'.$this->id.'_clear" class="btn'.($value ? '' : ' hidden').'" onclick="return jClearArticle(\''.$this->id.'\')">' . JText::_('JCLEAR') . '</a>';
			} else {
				$html[] = '<button id="'.$this->id.'_clear" class="btn'.($value ? '' : ' hidden').'" onclick="return jClearArticle(\''.$this->id.'\')"><span class="icon-remove"></span> ' . JText::_('JCLEAR') . '</button>';
			}
		}

		$html[] = '</span>';

		// class='required' for client side validation
		$class = '';
		if ($this->required)
		{
			$class = ' class="required modal-value"';
		}


		$html[] = '<input type="hidden" id="'.$this->id.'_id"'.$class.' name="'.$this->name.'" value="'.$value.'" /></fieldset></div>';

		if ($tos_Type == '1') {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("'.$name.'_article").style.display = "block";';
			$html[] = '</script>';
		} else {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("'.$name.'_article").style.display = "none";';
			$html[] = '</script>';
		}


		return implode("\n", $html);
	}
}
fields/modal/icmulti_checkbox.php000060400000005042152455705640013145 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.6 2013-11-21
 * @since       3.2.6
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_icmulti_checkbox extends JFormField
{
	protected $type='modal_icmulti_checkbox';

	protected function getLabel()
	{
	   return ' ';
	}

	protected function getInput()
	{

		$Explode = explode('_', $this->name);
		$TypeName = $Explode[0].']';

		$replace = array("jform", "[params]", "[", "]");
		$name = str_replace($replace, "", $TypeName);

		$selected = $this->value;
		if (!is_array($selected)) $selected = array();

		$check_1 = ' checked="checked"';
		$check_2 = ' checked="checked"';

		if (in_array('1', $selected)) {
			$check_1 = ' checked="checked"';
		} else {
			$check_1 = '';
		}
		if (in_array('2', $selected)) {
			$check_2 = ' checked="checked"';
		} else {
			$check_2 = '';
		}

		$Type_none = $name.'_none';
		$Type_checkbox = $name.'_checkbox';

		$html	= array();

		$html[] = '<div id="'.$Type_checkbox.'"><fieldset class="span9 iCleft">';
//		$html[] = '<input type="text" value="'.$this->value.'" name="'.$this->name.'"/>';
		$html[] = '<div style="display: inline-block"><input type="checkbox" value="1" name="'.$this->name.'[]"'.$check_1.'/>&nbsp;'.JText::_( 'ICTITLE' ).'</div>';
		$html[] = '<div style="display: inline-block"><input type="checkbox" value="2" name="'.$this->name.'[]"'.$check_2.'/>&nbsp;'.JText::_( 'ICDESC' ).'</div>';
		$html[] = '</fieldset></div>';

		$html[] = '<script type="text/javascript">';
		$html[] = 'document.getElementById("'.$Type_checkbox.'").style.display = "none";';
		$html[] = 'if (typeset == 1) {';
		$html[] = 'document.getElementById("'.$Type_checkbox.'").style.display = "block";';
		$html[] = '}';
//		$html[] = 'if (typeset == 0) {';
//		$html[] = 'document.getElementById("'.$Type_checkbox.'").style.display = "none";';
//		$html[] = '}';
		$html[] = '</script>';

		return implode("\n", $html);
	}
}
fields/modal/icvalue_opt.php000060400000005524152455705640012150 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.9 2013-12-22
 * @since       3.2.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_icvalue_opt extends JFormField
{
	protected $type='modal_icvalue_opt';

	protected function getInput()
	{

		$replace = array("jform", "params", "[", "]");
		$name = str_replace($replace, "", $this->name);

		$Type = $this->value;

		if ($name == 'calendarclosebtn') {
			$default_text = JText::_( 'JTOOLBAR_DEFAULT' );
		} else {
			$default_text = JText::_( 'JGLOBAL_USE_GLOBAL' );
		}

		$Type_default = $name.'_default';
		$Type_content = $name.'_custom';

		$class_default = '';
		$class_custom = '';
		$checked_default = ' checked="checked"';
		$checked_custom = '';
		if ($Type == '0') {
			$class_default = 'btn-primary';
			$checked_default = ' checked="checked"';
			$checked_custom = '';
		}
		elseif ($Type == '1') {
			$class_custom = 'btn-success';
			$checked_default = '';
			$checked_custom = ' checked="checked"';
		} else {
			$class_default = 'btn-primary';
			$checked_default = ' checked="checked"';
			$checked_custom = '';
		}

		$html	= array();


		$html[]	= '<fieldset class="radio btn-group">';
		$html[]	= '<label class="'.$class_default.'">'.$default_text.'<input type="radio"  id="'.$name.'_0" name="'.$this->name.'" value="0"  onClick="icdefault_'.$name.'();"'.$checked_default.' /></label>';
		$html[]	= '<label class="'.$class_custom.'">'.JText::_( 'COM_ICAGENDA_LBL_CUSTOM_VALUE' ).'<input type="radio"  id="'.$name.'_1" name="'.$this->name.'" value="1"  onClick="iccustom_'.$name.'();"'.$checked_custom.' /></label>';
		$html[]	= '</fieldset>';


		$html[]	= '<script type="text/javascript">';
		$html[]	= 'var typeset = '.$Type.';';
		$html[]	= 'function icdefault_'.$name.'()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("'.$Type_content.'").style.display = "none";';
		$html[]	= '$("#'.$name.'_0").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function iccustom_'.$name.'()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("'.$Type_content.'").style.display = "block";';
		$html[]	= '$("#'.$name.'_1").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= '</script>';

		return implode("\n", $html);
	}
}
fields/modal/tos_type.php000060400000010641152455705640011500 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.0 2013-09-18
 * @since       3.2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_tos_type extends JFormField
{
	protected $type='modal_tos_type';

	protected function getInput()
	{
		jimport('joomla.application.component.helper');

		$icagendaParams = JComponentHelper::getParams('com_icagenda');
		$tos_Type = $icagendaParams->get('tos_Type', '');
		$class_default = '';
		$class_article = '';
		$class_custom = '';
		$checked_default = '';
		$checked_article = '';
		$checked_custom = '';
		if ($tos_Type == '') {
			$class_default = 'btn-success';
			$checked_default = ' checked="checked"';
			$checked_article = '';
			$checked_custom = '';
		}
		elseif ($tos_Type == '1') {
			$class_article = 'btn-success';
			$checked_default = '';
			$checked_article = ' checked="checked"';
			$checked_custom = '';
		}
		elseif ($tos_Type == '2') {
			$class_custom = 'btn-success';
			$checked_default = '';
			$checked_article = '';
			$checked_custom = ' checked="checked"';
		} else {
			$class_default = 'btn-success';
			$checked_default = ' checked="checked"';
			$checked_article = '';
			$checked_custom = '';
		}

		$html	= array();
		$html[]	= '<fieldset class="radio btn-group">';
		$html[]	= '<label class="'.$class_default.'">'.JText::_( 'IC_DEFAULT' ).'<input type="radio"  id="tos_Type0" name="'.$this->name.'" value=""  onClick="tosdefault();"'.$checked_default.' /></label>';
		$html[]	= '<label class="'.$class_article.'">'.JText::_( 'IC_ARTICLE' ).'<input type="radio"  id="tos_Type1" name="'.$this->name.'" value="1"  onClick="tosarticle();"'.$checked_article.' /></label>';
		$html[]	= '<label class="'.$class_custom.'">'.JText::_( 'IC_CUSTOM_TEXT' ).'<input type="radio"  id="tos_Type2" name="'.$this->name.'" value="2"  onClick="toscustom();"'.$checked_custom.' /></label>';
		$html[]	= '</fieldset>';



		$html[]	= '<script type="text/javascript">';
//		$html[]	= 'var tos_Type0 = document.getElementById("tos_Type0").checked;';
//		$html[]	= 'var tos_Type1 = document.getElementById("tos_Type1").checked;';
//		$html[]	= 'var tos_Type2 = document.getElementById("tos_Type2").checked;';
//		$html[]	= 'if(tos_Type0==true)';
//		$html[]	= '{';
//		$html[]	= 'document.getElementByName("tos_Type").value = "";';
//		$html[]	= '$("#tos_Type1").attr("checked", "checked");';
//		$html[]	= '}';
//		$html[]	= 'if(tos_Type1==true)';
//		$html[]	= '{';
//		$html[]	= 'document.getElementByName("tos_Type").value = 1;';
//		$html[]	= '}';
//		$html[]	= 'if(tos_Type2==true)';
//		$html[]	= '{';
//		$html[]	= 'document.getElementByName("tos_Type").value = 2;';
//		$html[]	= '}';
//		$html[]	= '';
//		$html[]	= '';
		$html[]	= 'function tosdefault()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("ic_default").style.display = "block";';
		$html[]	= 'document.getElementById("ic_article").style.display = "none";';
		$html[]	= 'document.getElementById("tos_custom").style.display = "none";';
		$html[]	= '$("#tos_Type0").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function tosarticle()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("ic_default").style.display = "none";';
		$html[]	= 'document.getElementById("ic_article").style.display = "block";';
		$html[]	= 'document.getElementById("tos_custom").style.display = "none";';
		$html[]	= '$("#tos_Type1").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function toscustom()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("ic_default").style.display = "none";';
		$html[]	= 'document.getElementById("ic_article").style.display = "none";';
		$html[]	= 'document.getElementById("tos_custom").style.display = "block";';
		$html[]	= '$("#tos_Type2").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= '</script>';

		return implode("\n", $html);
	}
}
fields/modal/cat.php000060400000007206152455705640010404 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.4.1 2015-01-03
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_cat extends JFormField
{
	protected $type='modal_cat';

	protected function getInput()
	{
		$app		= JFactory::getApplication();
		$session	= JFactory::getSession();

		// Initialize some field attributes.
		$class		= !empty($this->class) ? ' class="' . $this->class . '"' : '';

		if ($app->isAdmin())
		{
			$iCparams = JComponentHelper::getParams('com_icagenda');
		}
		else
		{
			$iCparams	= $app->getParams();
		}

		$orderby_catlist		= $iCparams->get('orderby_catlist', 'alpha');
		$default_catlist		= $iCparams->get('default_catlist', '');

		$admin_status_catlist	= $iCparams->get('admin_status_catlist', '1');
		$site_status_catlist	= $iCparams->get('site_status_catlist', '1');

		$admin_status_array		= is_array($admin_status_catlist) ? $admin_status_catlist : array($admin_status_catlist);
		$site_status_array		= is_array($site_status_catlist) ? $site_status_catlist : array($site_status_catlist);

		$admin_status			= implode(',', $admin_status_array);
		$site_status			= implode(',', $site_status_array);

		$catid = $session->get('ic_submit_catid', '');

		// Query List of Categories
		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);
		$query->select('c.ordering, c.title, c.state, c.id')
			->from('`#__icagenda_category` AS c');

		// Not display Trashed Categories
		$query->where('c.state <> -2');

		if ($app->isAdmin())
		{
			$query->where($db->qn('c.state') . ' IN (' . $admin_status . ') ');
		}
		else
		{
			$query->where($db->qn('c.state') . ' IN (' . $site_status . ') ');
		}

		if ($orderby_catlist == 'alpha')
		{
			$query->order('c.title ASC');
		}
		elseif ($orderby_catlist == 'ralpha')
		{
			$query->order('c.title DESC');
		}
		elseif ($orderby_catlist == 'order')
		{
			$query->order('c.ordering ASC');
		}

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

		$html = '<select id="' . $this->id . '" name="' . $this->name . '"' . $class . '>';

		$html.= ' <option value="">' . JTEXT::_('JOPTION_SELECT_CATEGORY') . '</option>';

		foreach ($categories as $c)
		{
			$html.= '<option value="' . $c->id . '"';

			if ($c->state == '0')
			{
				$html.= ' style="color:red"';
//				$c->title = '[' . $c->title . '] (' . JTEXT::_('JUNPUBLISHED') . ')';
				$c->title = '[' . $c->title . ']';
			}
			elseif ($c->state == '2')
			{
				$html.= ' style="color:orange"';
//				$c->title = $c->title . ' (' . JTEXT::_('JARCHIVED') . ')';
				$c->title = '[' . $c->title . ']';
			}

			if ($this->value == $c->id)
			{
				$html.= ' selected="selected"';
			}

			if ($catid == $c->id)
			{
				$html.= ' selected="selected"';
			}

			if (empty($this->value) && empty($catid)
				&& ($c->id == $default_catlist))
			{
				$html.= ' selected="selected"';
			}

			$html.= '>' . $c->title . '</option>';
		}

		$html.= '</select>';

		// clear the data so we don't process it again
		$session->clear('ic_submit_catid');

		return $html;
	}
}
fields/modal/enddate.php000060400000003130152455705640011231 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.10 2015-08-13
 * @since       2.0.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Form Field to load a enddate datetime picker input
 *
 * @since	2.0.0
 */
class JFormFieldModal_enddate extends JFormField
{
	protected $type = 'modal_enddate';

	protected function getInput()
	{
		$class = ! empty($this->class) ? ' class="' . $this->class . '"' : '';

		$lang = JFactory::getLanguage();

		if ($lang->getTag() == 'fa-IR')
		{
			// Including fallback code for HTML5 non supported browsers.
			JHtml::_('jquery.framework');
			JHtml::_('script', 'system/html5fallback.js', false, true);

			$attributes = '';

			$html = JHtml::_('calendar', $this->value, $this->name, 'enddate_jalali', '%Y-%m-%d %H:%M:%S', $attributes);
		}
		else
		{
			$html ='<input type="text" id="enddate"' . $class . ' name="' . $this->name . '" value="' . $this->value . '"/>';
		}

		return $html;
	}
}
fields/modal/icalert_msg.php000060400000012410152455705640012117 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.3.3 2014-04-12
 * @since       3.2.8
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_icalert_msg extends JFormField
{
	protected $type='modal_icalert_msg';

	protected function getLabel()
	{
		return ' ';
	}

	protected function getInput()
	{
		$replace = array("jform", "params", "[", "]");
		$name_input = str_replace($replace, "", $this->name);
		$get_error = explode('_', $name_input);
		$error = $get_error['1'];
		$name = $get_error['0'];

		$url=JPATH_SITE.'/components/com_icagenda/themes/packs';

		// Set Function to condition to be checked
		$events_php=$this->getList($url);
		$cal_date=$this->getCalDate($url);

		if ($name == 'eventsfile')
		{
			$list = $events_php;
			$doc_url = 'http://www.icagenda.com/theme-pack-upgrade/3-2-8-new-option-all-dates';
			$parent_field = 'datesDisplay';
			$action_value = '1';
		}
		elseif ($name == 'caldate')
		{
			$list = $cal_date;
			$doc_url = 'http://www.icagenda.com/theme-pack-upgrade/3-3-3-change-cal-date-to-data-cal-date';
			$parent_field = 'setTodayTimezone';
			$action_value = '';
		}

		$span_style	= 'input-xlarge';

		if (version_compare(JVERSION, '3.0', 'lt')) {
			$listP		= implode('<br /> - ', $list);
			$setlist	= ' - '.$listP.' ';
		} else {
			$listP		= implode('</li><li>', $list);
			$setlist	= '<ul><li>'.$listP.'</li></ul>';
//			$span_style	= 'span8';
		}

		$html	= array();

		if (count($list) >= 1)
		{
			$html[]	= '<div id="icalert_'.$this->id.'" class="'.$span_style.' alert alert-error" style="clear:both">';
			$html[]	=  '<b>'.JText::_( $this->title ).'</b>';
			$html[]	= '<p>';
			$html[]	=  JText::_( $this->description ) . ' <a class="modal" rel="{size: {x: 700, y: 500}, handler:\'iframe\'}" href="'.$doc_url.'">' .JText::_( 'IC_MORE_INFORMATION' ). '</a>';
			$html[]	= '</p>';

			if ($this->id == 'jform_params_'.$name.'_error')
			{
				$html[]	= '<p>';
				$html[]	= '<b><i>'.JText::_( 'COM_ICAGENDA_EVENTS_PHPFILE_MISSING_PACKS_LIST' ).'</i></b><br />';
				$html[]	= $setlist;
				$html[]	= '</p>';
			}
			$html[]	= '</div>';

			$html[] = '<script type="text/javascript">';
			$html[]	= '		var icdisplay = document.getElementById("jform_params_'.$parent_field.'").value;';
			$html[] = '		document.getElementById("icalert_'.$this->id.'").style.display = "none";';
			$html[] = '		if (icdisplay == "'.$action_value.'") {';
			$html[] = '			document.getElementById("icalert_'.$this->id.'").style.display = "block";';
			$html[] = '		}';
			$html[]	= '	function icalert()';
			$html[]	= '	{';
			$html[]	= '		var icdisplay = document.getElementById("jform_params_'.$parent_field.'").value;';
			$html[] = '		document.getElementById("icalert_'.$this->id.'").style.display = "none";';
			$html[] = '		if (icdisplay == "'.$action_value.'") {';
			$html[] = '			document.getElementById("icalert_'.$this->id.'").style.display = "block";';
			$html[] = '		}';
			$html[]	= '	}';
			$html[] = '</script>';
		}

		return implode("\n", $html);
	}

	/**
	 * Function to check if the file 'THEME_events.php' exists in each Theme Pack
	 */
	function getList($dirname)
	{
		$arrayfiles = Array();

		if(file_exists($dirname))
		{
			$handle = opendir($dirname);

			while (false !== ($file = readdir($handle)))
			{
				if ( !is_file($dirname.$file)
					&& $file!= '.'
					&& $file!='..'
					&& $file!='index.php'
					&& $file!='index.html'
					&& $file!='.DS_Store'
					&& $file!='.thumbs' )
				{
					if (!file_exists($dirname.'/'.$file.'/'.$file.'_events.php'))
					{
						array_push($arrayfiles,$file);
					}
				}
			}
			$handle = closedir($handle);
		}
		sort($arrayfiles);

		return $arrayfiles;
	}

	/**
	 * Function to check if 'data-cal-date' is defined inside the file 'THEME_day.php' for each Theme Pack.
	 * Returns an alert if deprecated 'cal_date' found.
	 */
	function getCalDate($dirname)
	{
		$arrayfiles = Array();

		if (ini_get('allow_url_fopen'))
		{
			if (file_exists($dirname))
			{
				$handle = opendir($dirname);

				while (false !== ($file = readdir($handle)))
				{
					if ( !is_file($dirname.$file)
						&& $file!= '.'
						&& $file!='..'
						&& $file!='index.php'
						&& $file!='index.html'
						&& $file!='.DS_Store'
						&& $file!='.thumbs' )
					{
						$t_day = $dirname.'/'.$file.'/'.$file.'_day.php';
						$file_t_day = file_get_contents($t_day);

						if (!strpos($file_t_day, "cal_date")
							&& !strpos($file_t_day, "data-cal-date"))
						{
							array_push($arrayfiles,$file);
						}
						elseif (strpos($file_t_day, "cal_date"))
						{
							array_push($arrayfiles,$file);
						}
					}
				}
			}
			$handle = closedir($handle);
		}
		sort($arrayfiles);

		return $arrayfiles;
	}

}
fields/modal/ictext_content.php000060400000004165152455705640012670 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.0.1 2013-09-22
 * @since       3.2.0.1
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ictext_content extends JFormField
{
	protected $type='modal_ictext_content';

	protected function getInput()
	{

		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');

		$Explode = explode('_', $this->name);
		$TypeName = $Explode[0].']';

		$replace = array("jform", "[", "]");
		$name = str_replace($replace, "", $TypeName);
		$icContent = $icagendaParams->get($name.'_Content', '');

		$Type = $icagendaParams->get($name, '');

		$Type_default = $name.'_default';
		$Type_content = $name.'_custom';


		$editor = JFactory::getEditor();

		$html	= array();

		$html[] = '<div id="'.$Type_content.'"><fieldset class="span9 iCleft">';
		$html[] = $editor->display($this->name, $icContent, "100%", "300", "300", "20", 1, null, null, null, array('mode' => 'advanced'));
		$html[] = '</fieldset></div>';

		if ($Type == '2') {
			$html[] = '<script type="text/javascript">';
//			$html[] = 'document.getElementById("'.$Type_default.'").style.display = "none";';
			$html[] = 'document.getElementById("'.$Type_content.'").style.display = "block";';
			$html[] = '</script>';
		} else {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("'.$Type_content.'").style.display = "none";';
			$html[] = '</script>';
		}

		return implode("\n", $html);
	}
}
fields/modal/iclink_type.php000060400000010042152455705640012137 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.1 2015-02-27
 * @since       3.3.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_iclink_type extends JFormField
{
	protected $type='modal_iclink_type';

	protected function getInput()
	{
		jimport('joomla.application.component.helper');

		$location = JRequest::getVar('option', 'com_config');

		if ($location != 'com_config')
		{
			$default_text	= JText::_('JGLOBAL_USE_GLOBAL');
		}
		else
		{
			$default_text = JText::_("IC_DEFAULT");
		}

		// Get Type value
		$Type			= isset($this->value) ? $this->value : '';

		// Clean jform name
		$replace		= array("jform", "params", "[", "]");
		$name			= str_replace($replace, "", $this->name);

		$Type_default	= $name . '_default';
		$Type_article	= $name . '_article';
		$Type_url		= $name . '_url';

		// Set Var type, to get selected option
		JRequest::setVar('type', $Type);

		// Article
		if ($Type == '1')
		{
			$class_default		= '';
			$class_article		= 'btn-success';
			$class_url			= '';
			$checked_default	= '';
			$checked_article	= ' checked="checked"';
			$checked_url		= '';
		}

		// URL
		elseif ($Type == '2')
		{
			$class_default		= '';
			$class_article		= '';
			$class_url			= 'btn-success';
			$checked_default	= '';
			$checked_article	= '';
			$checked_url		= ' checked="checked"';
		}

		// iCagenda default
		else
		{
			$class_default		= 'btn-primary';
			$class_article		= '';
			$class_url			= '';
			$checked_default	= ' checked="checked"';
			$checked_article	= '';
			$checked_url		= '';
		}

		$html	= array();
		$html[]	= '<fieldset class="radio btn-group">';
		$html[]	= '<label class="' . $class_default . '">' . $default_text . '<input type="radio"  id="' . $name . '_0" name="' . $this->name . '" value=""  onClick="icdefault_' . $name . '();"' . $checked_default . ' /></label>';
		$html[]	= '<label class="' . $class_article . '">' . JText::_( 'COM_ICAGENDA_REGISTRATION_LINK_ARTICLE' ) . '<input type="radio"  id="' . $name . '_1" name="' . $this->name . '" value="1"  onClick="icarticle_' . $name . '();"' . $checked_article . ' /></label>';
		$html[]	= '<label class="' . $class_url . '">' . JText::_( 'COM_ICAGENDA_REGISTRATION_LINK_URL' ) . '<input type="radio"  id="' . $name . '_2" name="' . $this->name . '" value="2"  onClick="icurl_' . $name . '();"' . $checked_url . ' /></label>';
		$html[]	= '</fieldset>';

		// Script
		$html[]	= '<script type="text/javascript">';
		$html[]	= 'function icdefault_' . $name . '()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("' . $Type_article . '").style.display = "none";';
		$html[]	= 'document.getElementById("' . $Type_url . '").style.display = "none";';
//		$html[]	= '$("#'.$name.'_0").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function icarticle_' . $name . '()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("' . $Type_article . '").style.display = "block";';
		$html[]	= 'document.getElementById("' . $Type_url . '").style.display = "none";';
//		$html[]	= '$("#'.$name.'_1").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function icurl_' . $name . '()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("' . $Type_article . '").style.display = "none";';
		$html[]	= 'document.getElementById("' . $Type_url . '").style.display = "block";';
//		$html[]	= '$("#'.$name.'_2").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= '</script>';

		return implode("\n", $html);
	}
}
fields/modal/index.html000060400000000032152455705640011107 0ustar00<html><body></body></html>fields/modal/iclink_article.php000060400000016067152455705640012616 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.1 2015-02-27
 * @since       3.3.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Supports a modal article picker.
 */
class JFormFieldModal_iclink_article extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type = 'modal_iclink_article';

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		jimport('joomla.application.component.helper');
		$icagendaParams	= JComponentHelper::getParams('com_icagenda');

		$Explode		= explode('_', $this->name);
		$TypeName		= $Explode[0] . ']';

		$replace		= array("jform", "params", "[", "]");
		$name			= str_replace($replace, "", $TypeName);

//		$Type = JRequest::getVar('type');

		$allowEdit		= ((string) $this->element['edit'] == 'true') ? true : false;
		$allowClear		= ((string) $this->element['clear'] != 'false') ? true : false;

		// Load language
		JFactory::getLanguage()->load('com_content', JPATH_ADMINISTRATOR);

		// Load the modal behavior script.
		JHtml::_('behavior.modal', 'a.modal');

		// Build the script.
		$script = array();

		// Select button script
		$script[] = '	function jSelectArticle_'.$this->id.'(id, title, catid, object) {';
		$script[] = '		document.getElementById("'.$this->id.'_id").value = id;';
		$script[] = '		document.getElementById("'.$this->id.'_name").value = title;';

		if ($allowEdit)
		{
			$script[] = '		jQuery("#'.$this->id.'_edit").removeClass("hidden");';
		}

		if ($allowClear)
		{
			$script[] = '		jQuery("#'.$this->id.'_clear").removeClass("hidden");';
		}

		$script[] = '		SqueezeBox.close();';
		$script[] = '	}';

		// Clear button script
		static $scriptClear;

		if ($allowClear && !$scriptClear)
		{
			$scriptClear = true;

			$script[] = '	function jClearArticle(id) {';
			$script[] = '		document.getElementById(id + "_id").value = "";';
			$script[] = '		document.getElementById(id + "_name").value = "'.htmlspecialchars(JText::_('COM_CONTENT_SELECT_AN_ARTICLE', true), ENT_COMPAT, 'UTF-8').'";';
			$script[] = '		jQuery("#"+id + "_clear").addClass("hidden");';
			$script[] = '		if (document.getElementById(id + "_edit")) {';
			$script[] = '			jQuery("#"+id + "_edit").addClass("hidden");';
			$script[] = '		}';
			$script[] = '		return false;';
			$script[] = '	}';
		}

		// Add the script to the document head.
		JFactory::getDocument()->addScriptDeclaration(implode("\n", $script));

		// Setup variables for display.
		$html	= array();
		$link	= 'index.php?option=com_content&amp;view=articles&amp;layout=modal&amp;tmpl=component&amp;function=jSelectArticle_'.$this->id;

		if (isset($this->element['language']))
		{
			$link .= '&amp;forcedLanguage='.$this->element['language'];
		}

		$db	= JFactory::getDbo();
		$db->setQuery(
			'SELECT title' .
			' FROM #__content' .
			' WHERE id = '.(int) $this->value
		);

		try
		{
			$title = $db->loadResult();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $e->getMessage());
		}

		if (empty($title))
		{
			$title = JText::_('COM_CONTENT_SELECT_AN_ARTICLE');
		}
		$title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');

		// The active article id field.
		if (0 == (int) $this->value)
		{
			$value = '';
		}
		else
		{
			$value = (int) $this->value;
		}

		// The current article display field.
		$html[] = '<div id="'.$name.'_article"><fieldset class="span9 iCleft"><div>&nbsp;</div><span class="input-append">';
		$html[] = '<input type="text" class="input-medium" style="margin:0px" id="'.$this->id.'_name" value="'.$title.'" disabled="disabled" size="35" />';

		if(version_compare(JVERSION, '3.0', 'lt'))
		{
			$html[] = '<a class="modal btn hasTooltip" title="'.JText::_('COM_CONTENT_CHANGE_ARTICLE').'"  href="'.$link.'&amp;'.JSession::getFormToken().'=1" rel="{handler: \'iframe\', size: {x: 800, y: 450}}">'.JText::_('JSELECT').'</a>';
		}
		else
		{
			$html[] = '<a class="modal btn hasTooltip" title="'.JHtml::tooltipText('COM_CONTENT_CHANGE_ARTICLE').'"  href="'.$link.'&amp;'.JSession::getFormToken().'=1" rel="{handler: \'iframe\', size: {x: 800, y: 450}}"><i class="icon-file"></i> '.JText::_('JSELECT').'</a>';
		}

		// Edit article button
		if ($allowEdit)
		{
			if(version_compare(JVERSION, '3.0', 'lt'))
			{
				$html[] = '<a class="btn hasTooltip'.($value ? '' : ' hidden').'" href="index.php?option=com_content&view=article&layout=edit&id=' . $value. '" target="_blank" title="'.JText::_('COM_CONTENT_EDIT_ARTICLE').'" alt="'.JText::_('COM_CONTENT_EDIT_ARTICLE').'" >' . JText::_('JACTION_EDIT') . '</a>';
			}
			else
			{
				$html[] = '<a class="btn hasTooltip'.($value ? '' : ' hidden').'" href="index.php?option=com_content&layout=modal&tmpl=component&task=article.edit&id=' . $value. '" target="_blank" title="'.JHtml::tooltipText('COM_CONTENT_EDIT_ARTICLE').'" ><span class="icon-edit"></span> ' . JText::_('JACTION_EDIT') . '</a>';
			}
		}

		// Clear article button
		if ($allowClear)
		{
			if(version_compare(JVERSION, '3.0', 'lt'))
			{
				$html[] = '<a id="'.$this->id.'_clear" class="btn'.($value ? '' : ' hidden').'" onclick="return jClearArticle(\''.$this->id.'\')">' . JText::_('JCLEAR') . '</a>';
			}
			else
			{
				$html[] = '<button id="'.$this->id.'_clear" class="btn'.($value ? '' : ' hidden').'" onclick="return jClearArticle(\''.$this->id.'\')"><span class="icon-remove"></span> ' . JText::_('JCLEAR') . '</button>';
			}
		}

		$html[] = '</span>';

		// class='required' for client side validation
		$class = '';
		if ($this->required)
		{
			$class = ' class="required modal-value"';
		}


		$html[] = '<input type="hidden" id="'.$this->id.'_id"'.$class.' name="'.$this->name.'" value="'.$value.'" /></fieldset></div>';

//		if ($Type == '1')
//		{
//			$html[] = '<script type="text/javascript">';
//			$html[] = 'document.getElementById("'.$name.'_article").style.display = "block";';
//			$html[] = 'document.getElementById("'.$name.'_url").style.display = "none";';
//			$html[] = '</script>';
//		}
//		elseif ($Type == '2')
//		{
//			$html[] = '<script type="text/javascript">';
//			$html[] = 'document.getElementById("'.$name.'_article").style.display = "none";';
//			$html[] = 'document.getElementById("'.$name.'_url").style.display = "block";';
//			$html[] = '</script>';
//		}
//		else
//		{
//			$html[] = '<script type="text/javascript">';
//			$html[] = 'document.getElementById("'.$name.'_article").style.display = "none";';
//			$html[] = 'document.getElementById("'.$name.'_url").style.display = "none";';
//			$html[] = '</script>';
//		}

		return implode("\n", $html);
	}
}
fields/modal/tos_content.php000060400000004037152455705640012173 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.0 2013-09-18
 * @since       3.2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_tos_content extends JFormField
{
	protected $type='modal_tos_content';

//	protected function getLabel()
//	{
//	   return ' ';
//	}

	protected function getInput()
	{

		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');
		$tosContent = $icagendaParams->get('tosContent', '');
		$tos_Type = $icagendaParams->get('tos_Type', '');


		$editor = JFactory::getEditor();
//		$editor = JEditor::getEditor();

		$html	= array();

		$html[] = '<div id="tos_custom"><fieldset class="span9 iCleft">';
		$html[] = $editor->display($this->name, $tosContent, "100%", "300", "300", "20", 1, null, null, null, array('mode' => 'advanced'));
		$html[] = '</fieldset></div>';

		if ($tos_Type == '2') {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("ic_default").style.display = "none";';
			$html[] = 'document.getElementById("ic_article").style.display = "none";';
			$html[] = 'document.getElementById("tos_custom").style.display = "block";';
			$html[] = '</script>';
		} else {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("tos_custom").style.display = "none";';
			$html[] = '</script>';
		}

		return implode("\n", $html);
	}
}
fields/modal/evt.php000060400000030331152455705640010426 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.9 2015-08-01
 * @since       3.3.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_evt extends JFormField
{
	protected $type = 'modal_evt';

	protected function getInput()
	{
		$jinput		= JFactory::getApplication()->input;
		$view		= $jinput->get('view');
		$id			= $jinput->get('id', null);
		$eventid	= $jinput->get('eventid', $this->value);

		$class		= isset($this->class) ? ' class="' . $this->class . '"' : '';

		$typeReg = $db_date = $db_period = $db_date_is_valid = '';

		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);
		$query->select('e.title, e.state, e.id, e.weekdays, e.params')
			->from('`#__icagenda_events` AS e');

		if ($view == 'mail')
		{
			// Join Total of registrations
			$query->select('r.count AS registered');
			$sub_query = $db->getQuery(true);
			$sub_query->select('r.state, r.date AS reg_date, r.period AS reg_period, r.eventid, sum(r.people) AS count');
			$sub_query->from('`#__icagenda_registration` AS r');
			$sub_query->where('r.state = 1');
			$sub_query->where('r.email <> ""');
			$sub_query->group('r.eventid');
			$query->leftJoin('(' . (string) $sub_query . ') AS r ON (e.id = r.eventid)');
			$query->where('r.count > 0');
		}

		$query->order('e.title ASC');

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

		if ($eventid != 0 && $view == 'registration')
		{
			$query	= $db->getQuery(true);
			$query->select('r.date AS reg_date, r.period AS reg_period')
				->from('`#__icagenda_registration` AS r');
			$query->where('r.eventid = ' . (int) $eventid);
			$query->where('r.id = ' . (int) $id);
			$db->setQuery($query);
			$reg	= $db->loadObject();
			$db_date			= $reg->reg_date;
			$db_date_is_valid	= iCDate::isDate($db_date);
			$db_period			= $reg->reg_period;
		}

		// User state used in Newsletter
		$data				= JFactory::getApplication()->getUserState('com_icagenda.mail.data', array());
		$session_eventid	= isset($data['eventid']) ? $data['eventid'] : $eventid;
		$session_date		= isset($data['date']) ? $data['date'] : '';

		$html = '<div style="margin-bottom: 10px">';
		$html.= '<select id="' . $this->id . '_id"' . $class . ' name="' .
			$this->name . '">';

		$value = isset($this->value) ? $this->value : '';

		$html.= '<option value=""';

		if ( ! $id || ! $this->value)
		{
			$html.= ' selected="selected"';
		}

		$html.= '>' . JText::_('COM_ICAGENDA_SELECT_EVENT') . '</option>';

		foreach ($events as $e)
		{
			if ($e->state == '1')
			{
				$html.= '<option value="' . $e->id . '"';

				if ($eventid == $e->id)
				{
					$eventparam			= new JRegistry($e->params);
					$typeReg			= $eventparam->get('typeReg', 1);
					$weekdays			= $e->weekdays;

					$html.= ' selected="selected"';
				}

				if ($view == 'registration')
				{
					$html.= '>' . $e->title . ' (id:' . $e->id . ')</option>';
				}
				else
				{
					$html.= '>' . $e->title . ' (&#10003;' . $e->registered . ' - id:' . $e->id . ')</option>';
				}
			}
			elseif ($eventid == $e->id)
			{
				$html.= '<option value="' . $value . '"';
				$html.= ' selected="selected"';
				$html.= '>' . JText::_('COM_ICAGENDA_REGISTRATION_EVENT_NOT_PUBLISHED') . '</option>';
			}
		}

		$html.= '</select>';
		$html.= '</div>';

		$id_display = $id ? '&id=' . (int) $id : '';

		if ($view == 'registration')
		{
			// Info message with 'Registration Type' option setting, if the saved date is not in the list of dates for selected event.
			if ($typeReg == 1)
			{
				$reg_type = JText::_('COM_ICAGENDA_REG_BY_INDIVIDUAL_DATE');
			}
			elseif ($typeReg == 2)
			{
				$reg_type = JText::_('COM_ICAGENDA_REG_FOR_ALL_DATES');
			}
			else
			{
				$reg_type = JText::_('COM_ICAGENDA_REG_BY_DATE_OR_PERIOD');
			}

			$registration_type = '<strong>' . $reg_type . '</strong>';

			$alert_reg_type = '<div class="alert alert-info">';
			$alert_reg_type.= '<small>' . JText::sprintf('COM_ICAGENDA_REGISTRATION_TYPE_FOR_THIS_EVENT', $registration_type) . '</small>';
			$alert_reg_type.= '</div>';
			$alert_reg_type = addslashes($alert_reg_type);

			// Alert message for a date saved with a version before 3.3.3 (date not formatted as expected in sql format)
			$date_no_longer_exists = '<strong>"' . $db_date . '"</strong>';
			$alert_date_format = '<div class="ic-alert ic-alert-note"><span class="iCicon-info"></span> <strong>' . JText::_('NOTICE') . '</strong><br />' . JText::sprintf('COM_ICAGENDA_REGISTRATION_ERROR_DATE_CONTROL', $date_no_longer_exists) . '</div>';
			$alert_date_format = addslashes($alert_date_format);

			// Alert message if a date does not exist anymore for the selected event
			$alert_date_no_longer_exists = '<div class="alert alert-error"><strong>' . JText::_('COM_ICAGENDA_FORM_WARNING') . '</strong><br /><small>' . JText::sprintf('COM_ICAGENDA_REGISTRATION_DATE_NO_LONGER_EXISTS', $date_no_longer_exists) . '</small></div>';
			$alert_date_no_longer_exists = addslashes($alert_date_no_longer_exists);

			// Alert message if a date does not exist anymore for the selected event
			$alert_full_period_no_longer_exists = '<div class="alert alert-error"><strong>' . JText::_('COM_ICAGENDA_FORM_WARNING') . '</strong><br /><small>' . JText::sprintf('COM_ICAGENDA_REGISTRATION_PERIOD_NO_LONGER_EXISTS', $date_no_longer_exists) . '</small></div>';
			$alert_full_period_no_longer_exists = addslashes($alert_full_period_no_longer_exists);

			// Alert message if a date or period is set for the registration, but event registration type is now 'for all dates of the event'
			$for_all_dates = '<strong>' . JText::_('COM_ICAGENDA_ADMIN_REGISTRATION_FOR_ALL_DATES') . '</strong>';
			$alert_by_date_no_longer_possible = '<div class="alert alert-error"><strong>' . JText::_('COM_ICAGENDA_FORM_WARNING') . '</strong><br /><small>' . JText::sprintf('COM_ICAGENDA_REGISTRATION_BY_DATE_NO_LONGER_POSSIBLE', $for_all_dates, $for_all_dates) . '</small></div>';
			$alert_by_date_no_longer_possible = addslashes($alert_by_date_no_longer_possible);

			// Alert message if registration for all dates of the event, but event registration type is now 'select list of dates'
			$by_date = '<strong>' . JText::_('COM_ICAGENDA_ADMIN_REGISTRATION_BY_INDIVIDUAL_DATE') . '</strong>';
			$alert_for_all_dates_no_longer_possible = '<div class="alert alert-error"><strong>' . JText::_('COM_ICAGENDA_FORM_WARNING') . '</strong><br /><small>' . JText::sprintf('COM_ICAGENDA_REGISTRATION_FOR_ALL_DATES_NO_LONGER_POSSIBLE', $by_date) . '</small></div>';
			$alert_for_all_dates_no_longer_possible = addslashes($alert_for_all_dates_no_longer_possible);

			$html.= '<div id="date-alert">';
			$html.= '</div>';

			if ($typeReg == '1')
			{
				?>
				<script type="text/javascript">
					jQuery(document).ready(function($) {
						var value = $('#jform_date_id').val(),
							db_date = '<?php echo $db_date; ?>',
							db_period = '<?php echo $db_period; ?>',
							db_weekdays = '<?php echo $weekdays; ?>',
							db_date_is_valid = '<?php echo $db_date_is_valid; ?>',
							alert_reg_type = '<?php echo $alert_reg_type; ?>',
							alert_date_format = '<?php echo $alert_date_format; ?>',
							alert_date_no_longer_exists = '<?php echo $alert_date_no_longer_exists; ?>',
							alert_full_period_no_longer_exists = '<?php echo $alert_full_period_no_longer_exists; ?>',
							alert_for_all_dates_no_longer_possible = '<?php echo $alert_for_all_dates_no_longer_possible; ?>';

						if ( db_date == '' && db_period == '1' ) {
							// Registration for all dates, not possible if registration type is per date
							$('#date-alert').html(alert_reg_type+alert_for_all_dates_no_longer_possible);
						}
						else if ( !db_date_is_valid && db_date !== '' ) {
							// Date is not empty, but not a valid sql format (registration before release 3.3.3)
							$('#date-alert').html(alert_reg_type+alert_date_format);
						}
						else if ( db_date !== value && db_period !== '0') {
							// Date is not empty, but date is not anymore set for this event
							$('#date-alert').html(alert_date_no_longer_exists);
						}
						else if ( db_date == '' && db_period == '0' &&
							db_weekdays !== '' && db_weekdays !== '0') {
							// Date is not empty, but date is not anymore set for this event
							$('#date-alert').html(alert_full_period_no_longer_exists);
						}

						$('#jform_date_id').change(function(e) {
							$('#jform_period').val('0');
							$('#date-alert').html('');
						});
					});
				</script>
				<?php
			}
			elseif ($typeReg == '2')
			{
				?>
				<script type="text/javascript">
					jQuery(document).ready(function($) {
						var value = $('#jform_date_id').val(),
							db_date = '<?php echo $db_date; ?>',
							db_period = '<?php echo $db_period; ?>',
							alert_reg_type = '<?php echo $alert_reg_type; ?>',
							alert_by_date_no_longer_possible = '<?php echo $alert_by_date_no_longer_possible; ?>';

						$('#date-alert').html(alert_reg_type);

						if ( db_period !== '1' ) {
							// Date is empty, not possible if registration type is per date
							$('#date-alert').html(alert_reg_type+alert_by_date_no_longer_possible);
						}

						$('#jform_date_id').change(function(e) {
//							if ( value == 'update' ) {
								$('#jform_period').val('1');
								$('#date-alert').html('');
//							}
						});
					});
				</script>
			<?php
			}
		}
		?>
		<script type="text/javascript">
		jQuery(document).ready(function($) {
			var view = '<?php echo $view; ?>',
				regid = '<?php echo $id; ?>',
				eventid = '<?php echo $session_eventid; ?>',
				date = '<?php echo $session_date; ?>',
				list_target_id = 'jform_date_id',
				list_select_id = '<?php echo $this->id; ?>_id',
				initial_target_html = '<option value=""><?php echo JText::_("COM_ICAGENDA_SELECT_NO_EVENT_SELECTED"); ?>...</option>',
				loading = '<?php echo JText::_("IC_LOADING"); ?>';

			if (eventid) {
				$('#'+list_target_id).removeAttr('readonly');
				$('#'+list_target_id).val(date);

				$.ajax({url: 'index.php?option=com_icagenda&task='+view+'.dates&eventid='+eventid+'&regid='+regid,
					success: function(output) {
							$('#'+list_target_id).html(output);
					},
					error: function (xhr, ajaxOptions, thrownError) {
							alert(xhr.status + " "+ thrownError);
					}
				});

				$('#'+list_select_id).change(function(e) {
					$('#'+list_target_id).removeAttr('readonly');

					var selectvalue = $(this).val();

					$('#'+list_target_id).html('<option value="">'+loading+'</option>');

					if (selectvalue == "") {
						$('#'+list_target_id).attr('readonly', 'true');
						$('#'+list_target_id).html(initial_target_html);
					} else {
						$.ajax({url: 'index.php?option=com_icagenda&task='+view+'.dates&eventid='+selectvalue+'&regid='+regid,
							success: function(output) {
									$('#'+list_target_id).html(output);
							},
							error: function (xhr, ajaxOptions, thrownError) {
									alert(xhr.status + " "+ thrownError);
							}
						});
					}
				});
			} else {
				$('#'+list_target_id).attr('readonly', 'true');
				$('#'+list_target_id).html(initial_target_html);

				$('#'+list_select_id).change(function(e) {
					$('#'+list_target_id).removeAttr('readonly');

					var selectvalue = $(this).val();

					$('#'+list_target_id).html('<option value="">'+loading+'</option>');

					if (selectvalue == "") {
						$('#'+list_target_id).attr('readonly', 'true');
						$('#'+list_target_id).html(initial_target_html);
					} else {
						$.ajax({url: 'index.php?option=com_icagenda&task='+view+'.dates&eventid='+selectvalue+'&regid='+regid,
							success: function(output) {
									$('#'+list_target_id).html(output);
							},
							error: function (xhr, ajaxOptions, thrownError) {
									alert(xhr.status + " "+ thrownError);
							}
						});
					}
				});
			}
		});
		</script>
		<?php

		return $html;
	}
}
fields/modal/param_place.php000060400000002643152455705640012101 0ustar00<?php
/** 
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 * 
 * @since		1.0
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

JHTML::_('stylesheet', 'style.css', 'administrator/components/com_icagenda/add/css/');

class JFormFieldModal_param_place extends JFormField
{
	protected $type='modal_param_place';
	
	protected function getInput()
	{
		
		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);
		$query->select('a.place, a.id, a.coordinate')
			->from('`#__icagenda_events` AS a');
		$db->setQuery($query);
		$loc = $db->loadObjectList();
	
		$html= '
			<select id="'.$this->id.'_id"'.$class.' place="'.$this->place.'">
			<option value="NULL">-</option>';
		foreach ($loc as $l){
			$html.='<option value="'.$l->id.'"';
			if ($this->value == $l->id){
				$html.='selected="selected"';
			}
			$html.='>'.$l->place.'</option>';
			$span.='<span id="coord'.$l->id.'" style="display:none;">'.$l->coordinate.'</span>';
		}
		$html.='</select>'.$span;
			
		return $html;
	}
}fields/modal/ictext_placeholder.php000060400000003074152455705640013476 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.3 2014-03-24
 * @since       3.2.10
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ictext_Placeholder extends JFormField
{
	protected $type='modal_ictext_Placeholder';

	protected function getInput()
	{
		$class = JRequest::getVar('class');

		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');

		$replace = array("jform", "[", "]", "_Placeholder");
		$name = str_replace($replace, "", $this->name);

		$Type = $name . '_Placeholder';
		$tos_Type = $icagendaParams->get($Type);

		$placeholder = ( ! isset($tos_Type)) ? JText::_( 'COM_ICAGENDA_' . strtoupper($name) . '_PLACEHOLDER') : '';

		$html ='<input type="text" id="' . $this->id . '" class="' . $class . ' input-xxlarge" name="' . $this->name . '" value="' . $this->value . '" placeholder="' . $placeholder . '"/>';

		return $html;
	}
}
fields/modal/template.php000060400000003665152455705640011455 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.4.1 2015-01-30
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_Template extends JFormField
{
	protected $type = 'modal_template';

	protected function getInput()
	{
		$url	= JPATH_SITE.'/components/com_icagenda/themes/packs';
		$list	= $this->getList($url);
		$class 	= !empty($this->class) ? ' class="' . $this->class . '"' : '';
		$html	= '<select id="' . $this->id . '_id"' . $class . ' name="' . $this->name . '">';

		foreach ($list as $l)
		{
			$html.= '<option value="' . $l . '"';

			if ($this->value == $l)
			{
				$html.= ' selected="selected"';
			}

			$html.= '>' . $l . '</option>';
		}

		$html.= '</select>';

		return $html;
	}

	function getList($dirname)
	{
		$arrayfiles = Array();

		if (file_exists($dirname))
		{
			$handle = opendir($dirname);

			while (false !== ($file = readdir($handle)))
			{
				if (!is_file($dirname.$file)
					&& $file != '.'
					&& $file != '..'
					&& $file != '.DS_Store'
					&& $file != '.htaccess'
					&& $file != '.thumbs'
					&& $file != 'index.php'
					&& $file != 'index.html'
					&& $file != 'php.ini'
					)
				{
					array_push($arrayfiles, $file);
				}
			}

			$handle = closedir($handle);
		}

		sort($arrayfiles);

		return $arrayfiles;
	}
}
fields/modal/ictxt_type.php000060400000010034152455705640012022 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.5 2013-11-10
 * @since       3.2.5
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ictxt_type extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type = 'modal_ictxt_type';

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');

		$replace = array("jform", "[", "]", "_Type");
		$name = str_replace($replace, "", $this->name);

		$Type = $name.'_Type';
		$tos_Type = $icagendaParams->get($Type, '');

		$class_default = '';
		$class_article = '';
		$class_custom = '';
		$checked_default = '';
		$checked_article = '';
		$checked_custom = '';
		if ($tos_Type == '') {
			$class_default = 'btn-success';
			$checked_default = ' checked="checked"';
			$checked_article = '';
			$checked_custom = '';
		}
		elseif ($tos_Type == '1') {
			$class_article = 'btn-success';
			$checked_default = '';
			$checked_article = ' checked="checked"';
			$checked_custom = '';
		}
		elseif ($tos_Type == '2') {
			$class_custom = 'btn-success';
			$checked_default = '';
			$checked_article = '';
			$checked_custom = ' checked="checked"';
		} else {
			$class_default = 'btn-success';
			$checked_default = ' checked="checked"';
			$checked_article = '';
			$checked_custom = '';
		}

		$html	= array();
		$html[]	= '<fieldset class="radio btn-group">';
		$html[]	= '<label class="'.$class_default.'">'.JText::_( 'IC_DEFAULT' ).'<input type="radio"  id="'.$name.'_Type0" name="'.$this->name.'" value=""  onClick="tosdefault_'.$name.'();"'.$checked_default.' /></label>';
		$html[]	= '<label class="'.$class_article.'">'.JText::_( 'IC_ARTICLE' ).'<input type="radio"  id="'.$name.'_Type1" name="'.$this->name.'" value="1"  onClick="tosarticle_'.$name.'();"'.$checked_article.' /></label>';
		$html[]	= '<label class="'.$class_custom.'">'.JText::_( 'IC_CUSTOM_TEXT' ).'<input type="radio"  id="'.$name.'_Type2" name="'.$this->name.'" value="2"  onClick="toscustom_'.$name.'();"'.$checked_custom.' /></label>';
		$html[]	= '</fieldset>';



		$html[]	= '<script type="text/javascript">';
		$html[]	= 'function tosdefault_'.$name.'()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("'.$name.'_default").style.display = "block";';
		$html[]	= 'document.getElementById("'.$name.'_article").style.display = "none";';
		$html[]	= 'document.getElementById("'.$name.'_custom").style.display = "none";';
		$html[]	= '$("#'.$name.'_Type0").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function tosarticle_'.$name.'()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("'.$name.'_default").style.display = "none";';
		$html[]	= 'document.getElementById("'.$name.'_article").style.display = "block";';
		$html[]	= 'document.getElementById("'.$name.'_custom").style.display = "none";';
		$html[]	= '$("#'.$name.'_Type1").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function toscustom_'.$name.'()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("'.$name.'_default").style.display = "none";';
		$html[]	= 'document.getElementById("'.$name.'_article").style.display = "none";';
		$html[]	= 'document.getElementById("'.$name.'_custom").style.display = "block";';
		$html[]	= '$("#'.$name.'_Type2").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= '</script>';

		return implode("\n", $html);
	}
}
fields/modal/menulink.php000060400000003272152455705640011456 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rez�, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rez� (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.3.6 2014-04-29
 * @since       2.1.4
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_Menulink extends JFormField
{
	protected $type='modal_menulink';

	protected function getInput()
	{

		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);
		$query->select('a.title, a.published, a.id, a.path')
			->from('`#__menu` AS a')
			->where( "(link = 'index.php?option=com_icagenda&view=list') AND (published > 0)" );
		$db->setQuery($query);
		$link = $db->loadObjectList();
		$class = JRequest::getVar('class');

		$html= '
			<select id="'.$this->id.'_id"'.$class.' name="'.$this->name.'">';
		if ($this->name!='jform[catid]' && $this->name!='catid') $html.='<option value="">- '.JTEXT::_('JGLOBAL_AUTO').' -</option>';
		foreach ($link as $l){
		if ($l->published == '1') {
			$html.='<option value="'.$l->id.'"';
			if ($this->value == $l->id){
				$html.='selected="selected"';
			}
			$html.='>['.$l->id.'] '.$l->title.'</option>';
		}
		}
		$html.='</select>';
		return $html;

	}
}
fields/modal/tos_default.php000060400000003740152455705640012145 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.0 2013-09-18
 * @since       3.2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_tos_default extends JFormField
{
	protected $type='modal_tos_default';

//	protected function getLabel()
//	{
//	   return ' ';
//	}

	protected function getInput()
	{
		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');
		$tosContent = $icagendaParams->get('tosContent');
		$tos_Type = $icagendaParams->get('tos_Type', '');

		$html	= array();

		$html[] = '<div id="ic_default"><fieldset class="span9 iCleft">';
		$html[] = ''.JText::_( 'COM_ICAGENDA_SUBMIT_TOS_TYPE_DEFAULT_LBL' ).'<br /><div class="alert alert-info">'.JText::_( 'COM_ICAGENDA_TOS' ).'</div>';
		$html[] = '</fieldset></div>';

		if ($tos_Type == '') {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("ic_default").style.display = "block";';
			$html[] = 'document.getElementById("ic_article").style.display = "none";';
			$html[] = 'document.getElementById("tos_custom").style.display = "none";';
			$html[] = '</script>';
		} else {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("ic_default").style.display = "none";';
			$html[] = '</script>';
		}

		return implode("\n", $html);
	}
}
fields/modal/media.php000060400000010700152455705640010705 0ustar00<?php
/**
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.

 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 *
 * @update		2013-04-04
 * @version		2.1.4
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_media extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  11.1
	 */
	protected $type = 'modal_media';

	/**
	 * The initialised state of the document object.
	 *
	 * @var    boolean
	 * @since  11.1
	 */
	protected static $initialised = false;

	/**
	 * Method to get the field input markup for a media selector.
	 * Use attributes to identify specific created_by and asset_id fields
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   11.1
	 */
	protected function getInput()
	{
		$assetField = $this->element['asset_field'] ? (string) $this->element['asset_field'] : 'asset_id';
		$authorField = $this->element['created_by_field'] ? (string) $this->element['created_by_field'] : 'created_by';
		$asset = $this->form->getValue($assetField) ? $this->form->getValue($assetField) : (string) $this->element['asset_id'];
		if ($asset == '')
		{
			$asset = JRequest::getCmd('option');
		}

		$link = (string) $this->element['link'];
		if (!self::$initialised)
		{

			// Load the modal behavior script.
			JHtml::_('behavior.modal');

			// Build the script.
			$script = array();
			$script[] = '	function jInsertFieldValue(value, id) {';
			$script[] = '		var old_id = document.id(id).value;';
			$script[] = '		if (old_id != id) {';
			$script[] = '			var elem = document.id(id)';
			$script[] = '			elem.value = value;';
			$script[] = '			elem.fireEvent("change");';
			$script[] = '		}';
			$script[] = '	}';

			// Add the script to the document head.
			JFactory::getDocument()->addScriptDeclaration(implode("\n", $script));

			self::$initialised = true;
		}

		// Initialize variables.
		$html = array();
		$attr = '';

		// Initialize some field attributes.
		$attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : '';
		$attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : '';

		// Initialize JavaScript field attributes.
		$attr .= $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : '';

		// The text field.
		$html[] = '<span class="media_field">';
		$html[] = '	<input type="text" name="' . $this->name . '" id="' . $this->id . '"' . ' value="'
			. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '"' . ' readonly="readonly"' . $attr . ' />';
		$html[] = '</span>';

		$directory = (string) $this->element['directory'];
		if ($this->value && file_exists(JPATH_ROOT . '/' . $this->value))
		{
			$folder = explode('/', $this->value);
			array_shift($folder);
			array_pop($folder);
			$folder = implode('/', $folder);
		}
		elseif (file_exists(JPATH_ROOT . '/' . JComponentHelper::getParams('com_media')->get('image_path', 'images') . '/' . $directory))
		{
			$folder = $directory;
		}
		else
		{
			$folder = '';
		}
		// The button.
		$html[] = '<span class="ic_button">';
		$html[] = '	<span class="blank">';
		$html[] = '		<a class="modal" title="' . JText::_('JLIB_FORM_BUTTON_SELECT') . '"' . ' href="'
			. ($this->element['readonly'] ? ''
			: ($link ? $link
				: 'index.php?option=com_media&amp;view=images&amp;tmpl=component&amp;asset=' . $asset . '&amp;author='
				. $this->form->getValue($authorField)) . '&amp;fieldid=' . $this->id . '&amp;folder=' . $folder) . '"'
			. ' rel="{handler: \'iframe\', size: {x: 800, y: 500}}">';
		$html[] = JText::_('JLIB_FORM_BUTTON_SELECT') . '</a>';
		$html[] = '	</span>';
		$html[] = '</span>';

		$html[] = '<span class="ic_button">';
		$html[] = '	<span class="blank">';
		$html[] = '		<a title="' . JText::_('JLIB_FORM_BUTTON_CLEAR') . '"' . ' href="#" onclick="';
		$html[] = 'document.id(\'' . $this->id . '\').value=\'\';';
		$html[] = 'document.id(\'' . $this->id . '\').fireEvent(\'change\');';
		$html[] = 'return false;';
		$html[] = '">';
		$html[] = JText::_('JLIB_FORM_BUTTON_CLEAR') . '</a>';
		$html[] = '	</span>';
		$html[] = '</span>';

		return implode("\n", $html);
	}
}
fields/modal/icfile.php000060400000011750152455705640011067 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.13 2014-01-23
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.form.formfield');

class JFormFieldModal_icfile extends JFormField
{
	public $type = 'modal_icfile';


	protected static $initialised = false;

	/**
	 * Method to get the field input markup for a media selector.
	 * Use attributes to identify specific created_by and asset_id fields
	 *
	 * @return  string  The field input markup.
	 *
	 * @since   11.1
	 */
	protected function getInput()
	{
		$assetField = $this->element['asset_field'] ? (string) $this->element['asset_field'] : 'asset_id';
		$authorField = $this->element['created_by_field'] ? (string) $this->element['created_by_field'] : 'created_by';
		$asset = $this->form->getValue($assetField) ? $this->form->getValue($assetField) : (string) $this->element['asset_id'];
		if ($asset == '')
		{
			$asset = JRequest::getCmd('option');
		}

		$link = (string) $this->element['link'];
		if (!self::$initialised)
		{

			// Load the modal behavior script.
			JHtml::_('behavior.modal');

			// Build the script.
			$script = array();
			$script[] = '	function jInsertFieldValue(value, id) {';
			$script[] = '		var old_id = document.id(id).value;';
			$script[] = '		if (old_id != id) {';
			$script[] = '			var elem = document.id(id)';
			$script[] = '			elem.value = value;';
			$script[] = '			elem.fireEvent("change");';
			$script[] = '		}';
			$script[] = '	}';

			// Add the script to the document head.
			JFactory::getDocument()->addScriptDeclaration(implode("\n", $script));

			self::$initialised = true;
		}

		// Initialize variables.
		$html = array();
		$attr = '';

		// Initialize some field attributes.
		$attr .= $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : '';
		$attr .= $this->element['size'] ? ' size="' . (int) $this->element['size'] . '"' : '';
		$attr .= $this->element['accept'] ? ' accept="' . (string) $this->element['accept'] . '"' : '';
		$attr .= ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : '';

		// Initialize JavaScript field attributes.
		$attr .= $this->element['onchange'] ? ' onchange="' . (string) $this->element['onchange'] . '"' : '';

		// The text field.
		if ($this->value == NULL) {
			$html[] = '<span>';
			$html[] = '	<input type="file" style="cursor: pointer" name="' . $this->name . '" id="' . $this->id . '"' . ' value="'
				. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '"' . ' ' . $attr . ' />';
			$html[] = '</span>';
		} else {
			$html[] = '<span>';
			$html[] = '	<input type="text" name="' . $this->name . '" id="' . $this->id . '"' . ' value="'
				. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '"' . ' readonly="readonly"' . $attr . ' />';
			$html[] = '</span>';
		}


		$folder = 'icagenda_doc';
		// The button.
//		$html[] = '<div class="button2-left">';
//		$html[] = '	<div class="blank">';
//		$html[] = '		<a class="modal" title="' . JText::_('JLIB_FORM_BUTTON_SELECT') . '"' . ' href="'
//			. ($this->element['readonly'] ? ''
//			: ($link ? $link
//				: 'index.php?option=com_media&amp;view=images&amp;tmpl=component&amp;asset=' . $asset . '&amp;author='
//				. $this->form->getValue($authorField)) . '&amp;fieldid=' . $this->id . '&amp;folder=' . $folder) . '"'
//			. ' rel="{handler: \'iframe\', size: {x: 800, y: 500}}">';
//		$html[] = JText::_('JLIB_FORM_BUTTON_SELECT') . '</a>';
//		$html[] = '	</div>';
//		$html[] = '</div>';

		if ($this->value == NULL) {
		$html[] = '<div class="button2-left">';
		$html[] = '	<div class="blank">';
		$html[] = '		<a title="' . JText::_('JLIB_FORM_BUTTON_CLEAR') . '"' . ' href="#" onclick="';
		$html[] = 'document.id(\'' . $this->id . '\').value=\'\';';
		$html[] = 'document.id(\'' . $this->id . '\').fireEvent(\'change\');';
		$html[] = 'return false;';
		$html[] = '">';
		$html[] = JText::_('JLIB_FORM_BUTTON_CLEAR') . '</a>';
		$html[] = '</div>';
		$html[] = '</div>';
		} else {
		$html[] = '<div class="button2-left">';
		$html[] = '	<div class="blank">';
		$html[] = '		<a title="' . JText::_('JLIB_FORM_BUTTON_CLEAR') . '"' . ' href="#" onclick="';
		$html[] = 'document.id(\'' . $this->id . '\').value=\'\';';
		$html[] = 'document.id(\'' . $this->id . '\').fireEvent(\'change\');';
		$html[] = 'return false;';
		$html[] = '">';
		$html[] = JText::_('JLIB_FORM_BUTTON_CLEAR') . '</a>';
		$html[] = '</div>';
		$html[] = '</div>';
		}

		return implode("\n", $html);







	}
}
fields/modal/ic_editor.php000060400000003774152455705640011604 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.3.7 2014-05-18
 * @since       3.3.7
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_iC_editor extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type = 'modal_iC_editor';

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		$icName = $this->name;
		$icDefault = $this->default;
		$icValue = $this->value;

		if (strpos($icValue,'\n') !== false)
		{
			$array_newline = array('\\n', '\n');
			$icValue = str_replace($array_newline, '<br />', $icValue);
		}

		$get_period_string = JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_USER_PERIOD_DEFAULT_BODY');
		$get_date_string = JText::_('COM_ICAGENDA_REGISTRATION_EMAIL_USER_DATE_DEFAULT_BODY');

		if  ($icValue == 'COM_ICAGENDA_REGISTRATION_EMAIL_USER_PERIOD_DEFAULT_BODY')
		{
			$icBody = $get_period_string;
		}
		elseif ($icValue == 'COM_ICAGENDA_REGISTRATION_EMAIL_USER_DATE_DEFAULT_BODY')
		{
			$icBody = $get_date_string;
		}
		else
		{
			$icBody = $icValue;
		}

		$editor = JFactory::getEditor();

		$html	= array();

		$html[] = '<div id="'.$this->name.'_ic_editor"><fieldset class="span9 iCleft">';
		$html[] = $editor->display($this->name, $icBody, "100%", "300", "300", "20", 1, null, null, null, array('mode' => 'advanced'));
		$html[] = '</fieldset></div>';

		return implode("\n", $html);
	}
}
fields/modal/date.php000060400000010726152455705640010553 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.10 2015-08-13
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Supports unlimited modal datetime picker (add / delete).
 *
 * @package		iCagenda
 * @subpackage	com_icagenda
 * @since		1.0
 */
class JFormFieldModal_date extends JFormField
{
	protected $type = 'modal_date';

	protected function getInput()
	{
		$lang = JFactory::getLanguage();

		$id_suffix = ($lang->getTag() == 'fa-IR') ? '_jalali' : '';

		if ($lang->getTag() == 'fa-IR')
		{
			// Including fallback code for HTML5 non supported browsers.
			JHtml::_('jquery.framework');
			JHtml::_('script', 'system/html5fallback.js', false, true);
		}

		$id = JRequest::getInt('id');
		$class = !empty($this->class) ? ' ' . $this->class : '';

		$session = JFactory::getSession();
		$datesDB = $session->get('ic_submit_dates', '');

		if ($id && empty($datesDB))
		{
			$db	= JFactory::getDBO();
			$db->setQuery(
				'SELECT a.dates' .
				' FROM #__icagenda_events AS a' .
				' WHERE a.id = '.(int) $id
			);
			$datesDB = $db->loadResult();
		}

		$dates = iCString::isSerialized($datesDB) ? unserialize($datesDB) : false;

//		if ($lang->getTag() == 'fa-IR'
//			&& $dates
//			&& $dates != array('0000-00-00 00:00'))
//		{
//			$dates_to_sql = array();

//			foreach ($dates AS $date)
//			{
//				if (iCDate::isDate($date))
//				{
//					$year		= date('Y', strtotime($date));
//					$month		= date('m', strtotime($date));
//					$day		= date('d', strtotime($date));
//					$time		= date('H:i', strtotime($date));

//					$dates_to_sql[] = iCGlobalizeConvert::gregorianToJalali($year, $month, $day, true) . ' ' . $time;
//				}
//			}

//			$dates = $dates_to_sql;
//		}

		$html = '<table id="dTable' . $id_suffix . '" style="border:0px">';

		$html.= '<thead>';
		$html.= '<tr>';
		$html.= '<th width="70%">';
		$html.= JText::_('COM_ICAGENDA_TB_DATE');
		$html.= '</th>';
		$html.= '<th width="30%">';
//		$html.= JText::_('COM_ICAGENDA_TB_ACT');
		$html.= '</th>';
		$html.= '</tr>';
		$html.= '</thead>';

		$add_counter = 0;

		if ($dates
			&& $dates != array('0000-00-00 00:00'))
		{
			foreach ($dates as $date)
			{
				$html.= '<tr>';
				$html.= '<td>';

				if ($lang->getTag() == 'fa-IR')
				{
					$add_counter = $add_counter+1;
//					$this_number = $add_counter ? $add_counter : '';
					$html.= JHtml::_('calendar', $date, 'd', 'date_jalali' . $add_counter, '%Y-%m-%d %H:%M', ' class="ic-date-input' . $id_suffix . '"');
				}
				else
				{
					$html.= '<input class="ic-date-input' . $id_suffix . '" type="text" name="d" value="' . $date . '" />';
				}

				$html.= '</td>';
				$html.= '<td>';
				$html.= '<a class="del btn btn-danger btn-mini" href="#">' . JText::_('COM_ICAGENDA_DELETE_DATE') . '</a>';
				$html.= '</td>';
				$html.= '</tr>';
			}

			// clear the data so we don't process it again
			$session->clear('ic_submit_dates');
		}
		else
		{
			$html.= '<tr>';
			$html.= '<td>';

			if ($lang->getTag() == 'fa-IR')
			{
				$html.= JHtml::_('calendar', '0000-00-00 00:00', 'd', 'date_jalali', '%Y-%m-%d %H:%M', ' class="ic-date-input' . $id_suffix . '"');
			}
			else
			{
				$html.= '<input class="ic-date-input' . $id_suffix . '" type="text" name="d" value="0000-00-00 00:00" />';
			}
			$html.= '</td>';
			$html.= '<td>';
			$html.= '<a class="del btn btn-danger btn-mini" href="#">' . JText::_('COM_ICAGENDA_DELETE_DATE') . '</a>';
			$html.= '</td>';
			$html.= '</tr>';
		}

		$html.= '</table>';

		$html.= '<a id="add" href="#"><span class="btn btn-success btn-small input-medium" style="float:left"><strong>' . JText::_('COM_ICAGENDA_ADD_DATE') . '</strong></span></a><br/>';

		$html.= '<input type="hidden"';
		$html.= ' class="date' . $class . '"';
		$html.= ' id="' . $this->id . '_id"';
		$html.= ' name="' . $this->name . '"';
		$html.= ' value=\''.$datesDB.'\'';
		$html.= '/>';

		return $html;
	}
}
fields/modal/ictext_type.php000060400000005643152455705640012201 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.0.1 2013-09-22
 * @since       3.2.0.1
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ictext_type extends JFormField
{
	protected $type='modal_ictext_type';

	protected function getInput()
	{
		jimport('joomla.application.component.helper');

		$icagendaParams = JComponentHelper::getParams('com_icagenda');

		$replace = array("jform", "[", "]");
		$name = str_replace($replace, "", $this->name);
		$Type = $icagendaParams->get($name, '');

		$Type_default = $name.'_default';
		$Type_content = $name.'_custom';

		$class_default = '';
		$class_custom = '';
		$checked_default = '';
		$checked_custom = '';
		if ($Type == '') {
			$class_default = 'btn-success';
			$checked_default = ' checked="checked"';
			$checked_custom = '';
		}
		elseif ($Type == '2') {
			$class_custom = 'btn-success';
			$checked_default = '';
			$checked_custom = ' checked="checked"';
		} else {
			$class_default = 'btn-success';
			$checked_default = ' checked="checked"';
			$checked_custom = '';
		}

		$html	= array();
		$html[]	= '<fieldset class="radio btn-group">';
		$html[]	= '<label class="'.$class_default.'">'.JText::_( 'IC_DEFAULT' ).'<input type="radio"  id="'.$name.'_0" name="'.$this->name.'" value=""  onClick="icdefault_'.$name.'();"'.$checked_default.' /></label>';
		$html[]	= '<label class="'.$class_custom.'">'.JText::_( 'IC_CUSTOM_TEXT' ).'<input type="radio"  id="'.$name.'_2" name="'.$this->name.'" value="2"  onClick="iccustom_'.$name.'();"'.$checked_custom.' /></label>';
		$html[]	= '</fieldset>';



		$html[]	= '<script type="text/javascript">';
		$html[]	= 'function icdefault_'.$name.'()';
		$html[]	= '{';
//		$html[]	= 'document.getElementById("'.$Type_default.'").style.display = "block";';
		$html[]	= 'document.getElementById("'.$Type_content.'").style.display = "none";';
		$html[]	= '$("#'.$name.'_0").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function iccustom_'.$name.'()';
		$html[]	= '{';
//		$html[]	= 'document.getElementById("'.$Type_default.'").style.display = "none";';
		$html[]	= 'document.getElementById("'.$Type_content.'").style.display = "block";';
		$html[]	= '$("#'.$name.'_2").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= '</script>';

		return implode("\n", $html);
	}
}
fields/modal/color.php000060400000001725152455705640010753 0ustar00<?php
/** 
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 * 
 * @update		2.0.4
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');


class JFormFieldModal_color extends JFormField
{
	protected $type='modal_color';
	
	protected function getInput()
	{
		$html= '
		<div class="color">
			<div class="form-item">
				<input type="text" id="'.$this->id.'" name="'.$this->name.'" value="'.$this->value.'" />
			</div>
			<div id="picker"></div>
			<div class="clr"></div>
		</div>
		<div class="clr"></div>
		';

		return $html;
	}
}fields/modal/icmulti_opt.php000060400000007047152455705640012170 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.6 2013-11-20
 * @since       3.2.6
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_icmulti_opt extends JFormField
{
	protected $type='modal_icmulti_opt';

	protected function getInput()
	{

		$replace = array("jform", "params", "[", "]");
		$name_input = str_replace($replace, "", $this->name);
		$get_location = explode('_', $name_input);
		$location = $get_location['1'];
		$name = $get_location['0'];

		$Type = $this->value;

		$Type_none = $name.'_none';
		$Type_checkbox = $name.'_checkbox';

		$class_global = 'btn-primary';
		$class_none = 'btn-danger';
		$class_checkbox = 'btn-success';
		$checked_none = ' checked="checked"';
		$checked_checkbox = '';
		if ($Type == '0') {
			$class_global = '';
			$class_none = 'btn-danger';
			$class_checkbox = '';
			$checked_global = '';
			$checked_none = ' checked="checked"';
			$checked_checkbox = '';
		}
		elseif ($Type == '1') {
			$class_global = '';
			$class_none = '';
			$class_checkbox = 'btn-success';
			$checked_global = '';
			$checked_none = '';
			$checked_checkbox = ' checked="checked"';
		}
		else {
			$class_global = 'btn-primary';
			$class_none = '';
			$class_checkbox = '';
			$checked_global = ' checked="checked"';
			$checked_none = '';
			$checked_checkbox = '';
		}

		$html	= array();


		$html[]	= '<fieldset class="radio btn-group">';
		if ($location == 'menu') {
			$html[]	= '<label class="'.$class_global.'">'.JText::_( 'JGLOBAL_USE_GLOBAL' ).'<input type="radio"  id="'.$name.'_global" name="'.$this->name.'" value="global"  onClick="icglobal_'.$name.'();"'.$checked_global.' /></label>';
		}
		$html[]	= '<label class="'.$class_none.'">'.JText::_( 'JNO' ).'<input type="radio"  id="'.$name.'_0" name="'.$this->name.'" value="0"  onClick="icnone_'.$name.'();"'.$checked_none.' /></label>';
		$html[]	= '<label class="'.$class_checkbox.'">'.JText::_( 'JYES' ).'<input type="radio"  id="'.$name.'_1" name="'.$this->name.'" value="1"  onClick="iccheckbox_'.$name.'();"'.$checked_checkbox.' /></label>';
		$html[]	= '</fieldset>';


		$html[]	= '<script type="text/javascript">';
		$html[]	= 'var typeset = '.$Type.';';
		if ($location == 'menu') {
			$html[]	= 'function icglobal_'.$name.'()';
			$html[]	= '{';
			$html[]	= 'document.getElementById("'.$Type_checkbox.'").style.display = "none";';
			$html[]	= '$("#'.$name.'_global").attr("checked", "checked");';
			$html[]	= '}';
		}
		$html[]	= 'function icnone_'.$name.'()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("'.$Type_checkbox.'").style.display = "none";';
		$html[]	= '$("#'.$name.'_0").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= 'function iccheckbox_'.$name.'()';
		$html[]	= '{';
		$html[]	= 'document.getElementById("'.$Type_checkbox.'").style.display = "block";';
		$html[]	= '$("#'.$name.'_1").attr("checked", "checked");';
		$html[]	= '}';
		$html[]	= '</script>';

		return implode("\n", $html);
	}
}
fields/modal/iclink_url.php000060400000005123152455705640011764 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.1 2015-02-27
 * @since       3.3.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

/**
 * Supports a url type field.
 */
class JFormFieldModal_iclink_url extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type='modal_iclink_url';

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		jimport('joomla.application.component.helper');
		$icagendaParams	= JComponentHelper::getParams('com_icagenda');

		$Explode		= explode('_', $this->name);
		$TypeName		= $Explode[0] . ']';

		$replace		= array("jform", "params", "[", "]");
		$name			= str_replace($replace, "", $TypeName);

		$Type			= JRequest::getVar('type');

		$Type_default	= $name.'_default';
		$Type_article	= $name.'_article';
		$Type_url		= $name.'_url';


		$editor = JFactory::getEditor();

		$html	= array();

		$html[] = '<div id="' . $Type_url . '"><fieldset class="span9 iCleft">';
		$html[] = '<input type="url" name="' . $this->name . '" value="' . $this->value . '" />';
		$html[] = '</fieldset></div>';

		// Article
		if ($Type == '1')
		{
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("' . $Type_article . '").style.display = "block";';
			$html[] = 'document.getElementById("' . $Type_url . '").style.display = "none";';
			$html[] = '</script>';
		}

		// URL
		elseif ($Type == '2')
		{
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("' . $Type_article . '").style.display = "none";';
			$html[] = 'document.getElementById("' . $Type_url . '").style.display = "block";';
			$html[] = '</script>';
		}

		// iCagenda default
		else
		{
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("' . $Type_article . '").style.display = "none";';
			$html[] = 'document.getElementById("' . $Type_url . '").style.display = "none";';
			$html[] = '</script>';
		}

		return implode("\n", $html);
	}
}
fields/modal/ictxt_default.php000060400000005000152455705640012462 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.2.5 2013-11-10
 * @since       3.2.5
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ictxt_default extends JFormField
{
	/**
	 * The form field type.
	 */
	protected $type = 'modal_ictxt_default';

	/**
	 * Method to create a blank label.
	 */
	protected function getLabel()
	{
	   return ' ';
	}

	/**
	 * Method to get the field input markup.
	 */
	protected function getInput()
	{
		jimport('joomla.application.component.helper');
		$icagendaParams = JComponentHelper::getParams('com_icagenda');

		$replace = array("jform", "[", "]", "Default");
		$name = str_replace($replace, "", $this->name);

		$tos_Type = $icagendaParams->get($name.'_Type', '');

		$Type_default = $name.'_default';
		$Type_article = $name.'_article';
		$Type_content = $name.'_custom';

		$html	= array();

		$html[] = '<div id="'.$name.'_default"><fieldset class="span9 iCleft">';
		$html[] = '<div class="alert alert-error">';
		if(version_compare(JVERSION, '3.0', 'ge')) {
			$html[] = '<i class="icon-warning-2"></i>';
		}
		$html[] = ' '.JText::sprintf( 'COM_ICAGENDA_TERMS_IMPORTANT_INFOS', $this->description ).'</div><div>'.JText::_( 'COM_ICAGENDA_SUBMIT_TOS_TYPE_DEFAULT_LBL' ).'<br /><small>'.$this->description.'</small></div><div class="alert alert-info">'.JText::_( $this->description ).'</div>';
		$html[] = '<input type="hidden" id="'.$this->id.'_id" name="'.$this->name.'" value="'.$this->value.'" />';
		$html[] = '</fieldset></div>';

		if ($tos_Type == '') {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("'.$name.'_default").style.display = "block";';
			$html[] = '</script>';
		} else {
			$html[] = '<script type="text/javascript">';
			$html[] = 'document.getElementById("'.$name.'_default").style.display = "none";';
			$html[] = '</script>';
		}

		return implode("\n", $html);
	}
}
fields/modal/ic_password.php000060400000002352152455705640012147 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.4.0 2014-12-21
 * @since       3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_ic_password extends JFormField
{
	protected $type='modal_ic_password';

	protected function getInput()
	{
		$_pass = str_replace('/', '.', $this->value);
		$pass_ex = explode('.', $_pass);

		if (isset($pass_ex[1]))
		{
			$value = base64_decode($pass_ex[1]);
		}
		else
		{
			$value = $this->value;
		}

		$html = '<input type="password" id="' . $this->id . '" name="' . $this->name . '" value="' . $value . '" />';

		return $html;
	}
}
fields/modal/multicat.php000060400000004063152455705640011455 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.4.0 2014-12-06
 * @since       3.2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );
jimport('joomla.form.formfield');

class JFormFieldModal_multicat extends JFormField
{
	protected $type='modal_multicat';

	protected function getInput()
	{
		// Initialize some field attributes.
		$class	= !empty($this->class) ? ' class="' . $this->class . '"' : '';

		// Query List of Categories
		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);
		$query->select('a.title, a.state, a.id')
			->from('`#__icagenda_category` AS a');
		$db->setQuery($query);
		$cat	= $db->loadObjectList();

		if (!is_array($this->value))
		{
			$this->value = array($this->value);
		}

		$html = ' <select multiple id="' . $this->id . '_id" name="' . $this->name . '"' . $class . '>';

		if (version_compare(JVERSION, '3.0', 'lt'))
		 {
			if ($this->name != 'jform[catid]' && $this->name != 'catid')
			{
				$html.= '<option value="0"';

				if (in_array('0', $this->value))
				{
					$html.= ' selected="selected"';
				}

				$html.= '>-- '.JTEXT::_('COM_ICAGENDA_ALL_CATEGORIES').' --</option>';
			}
		}

		foreach ($cat as $c)
		{
			if ($c->state == '1')
			{
				$html.= '<option value="' . $c->id . '"';

				if ( (in_array($c->id, $this->value)) && (!in_array('0', $this->value)) )
				{
					$html.= ' selected="selected"';
				}

				$html.= '>' . $c->title . '</option>';
			}
		}

		$html.= '</select>';

		return $html;
	}
}
themes.php000060400000034351152455705640006561 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.0 2013-06-04
 * @since       2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modellist');
jimport( 'joomla.html.parameter' );

if(version_compare(JVERSION, '3.0', 'ge')) {
	jimport( 'joomla.installer.installer' );
	jimport( 'joomla.installer.helper' );
	jimport( 'joomla.filesystem.folder' );
}

/**
 * Model Admin - Theme Manager - iCagenda
 */
class iCagendaModelthemes extends JModelList
{

	protected 	$_paths 	= array();
	protected 	$_manifest 	= null;
	protected	$option 		= 'com_icagenda';
	protected 	$text_prefix	= 'com_icagenda';

	function __construct(){
		parent::__construct();
	}

	public function getForm($data = array(), $loadData = true) {

		$app	= JFactory::getApplication();
		$form 	= $this->loadForm('com_icagenda.template', 'themes', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}
		return $form;
	}

	function install($theme) {
		$app		= JFactory::getApplication();
		$db 		= JFactory::getDBO();
		$package 	= $this->_getPackageFromUpload();

		if (!$package) {
			JError::raiseWarning(1, JText::_('COM_ICAGENDA_ERROR_FIND_INSTALL_PACKAGE'));
			$this->deleteTempFiles();
			return false;
		}

		if ($package['dir'] && JFolder::exists($package['dir'])) {
			$this->setPath('source', $package['dir']);
		} else {
			JError::raiseWarning(1, JText::_('COM_ICAGENDA_ERROR_INSTALL_PATH_NOT_EXISTS'));
			$this->deleteTempFiles();
			return false;
		}

		// We need to find the installation manifest file
		if (!$this->_findManifest()) {
			JError::raiseWarning(1, JText::_('COM_ICAGENDA_ERROR_FIND_INFO_INSTALL_PACKAGE'));
			$this->deleteTempFiles();
			return false;
		}

		// Files - copy files in manifest
		foreach ($this->_manifest->children() as $child)
		{
			if (is_a($child, 'JXMLElement') && $child->name() == 'files') {
				if ($this->parseFiles($child) === false) {
					JError::raiseWarning(1, JText::_('COM_ICAGENDA_ERROR_FIND_INFO_INSTALL_PACKAGE'));
					$this->deleteTempFiles();
					return false;
				}
			}
		}

		// File - copy the xml file
		$copyFile 		= array();
		$path['src']	= $this->getPath( 'manifest' ); // XML file will be copied too
		$path['dest']	= JPATH_SITE.DS.'components'.DS.'com_icagenda'.DS.'themes'.DS. basename($this->getPath('manifest'));
		$copyFile[] 	= $path;
		$this->copyFiles($copyFile, array());
		$this->deleteTempFiles();

		// -------------------
		// Themes
		// -------------------
		// Params -  Get new themes params
		$paramsThemes = $this->getParamsThemes();


		// -------------------
		// Component
		// -------------------
		if (isset($theme['component']) && $theme['component'] == 1 ) {

			$component			= 'com_icagenda';
			$paramsC			= JComponentHelper::getParams($component) ;

			foreach($paramsThemes as $keyT => $valueT) {
if(version_compare(JVERSION, '3.0', 'lt')) {
				$paramsC->setValue($valueT['name'], $valueT['value']);
} else {
				$paramsC->set($valueT['name'], $valueT['value']);
}
			}

			$data['params'] 	= $paramsC->toArray();
			$table 				= JTable::getInstance('extension');

			$idCom				= $table->find( array('element' => $component ));
			$table->load($idCom);

			if (!$table->bind($data)) {
				JError::raiseWarning( 500, 'Not a valid component' );
				return false;
			}

			// pre-save checks
			if (!$table->check()) {
				JError::raiseWarning( 500, $table->getError('Check Problem') );
				return false;
			}

			// save the changes
			if (!$table->store()) {
				JError::raiseWarning( 500, $table->getError('Store Problem') );
				return false;
			}
		}

		return true;
	}

	function _getPackageFromUpload()
	{
		// Get the uploaded file information
		$userfile = JRequest::getVar('Filedata', null, 'files', 'array' );
// 2.5		$userfile = JRequest::getVar('install_package', null, 'files', 'array' );

		// Make sure that file uploads are enabled in php
		if (!(bool) ini_get('file_uploads')) {
			JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_ICAGENDA_ERROR_INSTALL_FILE_UPLOAD'));
			return false;
		}

		// Make sure that zlib is loaded so that the package can be unpacked
		if (!extension_loaded('zlib')) {
			JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_ICAGENDA_ERROR_INSTALL_ZLIB'));
			return false;
		}

		// If there is no uploaded file, we have a problem...
		if (!is_array($userfile) ) {
			JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_ICAGENDA_ERROR_NO_FILE_SELECTED'));
			return false;
		}

		// Check if there was a problem uploading the file.
		if ( $userfile['error'] || $userfile['size'] < 1 ) {
			JError::raiseWarning('SOME_ERROR_CODE', JText::_('COM_ICAGENDA_ERROR_UPLOAD_FILE'));
			return false;
		}

		// Build the appropriate paths
if(version_compare(JVERSION, '3.0', 'lt')) {
		$config 	=& JFactory::getConfig();
		$tmp_dest 	= $config->getValue('config.tmp_path').DS.$userfile['name'];
} else {
		$config 	=& JFactory::getConfig();
		$tmp_dest 	= $config->get('tmp_path') . '/' . $userfile['name'];
}

		$tmp_src	= $userfile['tmp_name'];

		// Move uploaded file
		jimport('joomla.filesystem.file');
		$uploaded = JFile::upload($tmp_src, $tmp_dest);

		// Unpack the downloaded package file
if(version_compare(JVERSION, '3.0', 'lt')) {
		$package = JInstallerHelper::unpack($tmp_dest);
} else {
		$package = self::unpack($tmp_dest);
}

		$this->_manifest =& $manifest;

		$this->setPath('packagefile', $package['packagefile']);
		$this->setPath('extractdir', $package['extractdir']);

		return $package;
	}

	function getPath($name, $Default=null) {
		return (!empty($this->_paths[$name])) ? $this->_paths[$name] : $Default;
	}

	function setPath($name, $value) {
		$this->_paths[$name] = $value;
	}

	function _findManifest() {
		// Get an array of all the xml files from teh installation directory
		$xmlfiles = JFolder::files($this->getPath('source'), '.xml$', 1, true);

		// If at least one xml file exists
		if (count($xmlfiles) > 0) {
			foreach ($xmlfiles as $file)
			{
				// Is it a valid joomla installation manifest file?
				$manifest = $this->_isManifest($file);
				if (!is_null($manifest)) {

					$attr = $manifest->attributes();
					if ((string)$attr['method'] != 'icthemes') {
						JError::raiseWarning(1, JText::_('COM_ICAGENDA_ERROR_NO_THEME_FILE'));
						return false;
					}

					// Set the manifest object and path
					$this->_manifest =& $manifest;
					$this->setPath('manifest', $file);

					// Set the installation source path to that of the manifest file
					$this->setPath('source', dirname($file));

					return true;
				}
			}

			// None of the xml files found were valid install files
			JError::raiseWarning(1, JText::_('COM_ICAGENDA_ERROR_XML_INSTALL_ICAGENDA'));
			return false;
		} else {
			// No xml files were found in the install folder
			JError::raiseWarning(1, JText::_('COM_ICAGENDA_ERROR_XML_INSTALL'));
			return false;
		}
	}

	function _isManifest($file) {
		$xml	= JFactory::getXML($file, true);
		if (!$xml) {
			unset ($xml);
			return null;
		}
		if (!is_object($xml) || ($xml->name() != 'install' )) {
			unset ($xml);
			return null;
		}
		return $xml;
	}


	function parseFiles($element, $cid=0) {
		$copyfiles 		= array();
		$copyfolders 	= array();

		if (!is_a($element, 'JXMLElement') || !count($element->children())) {
			return 0;// Either the tag does not exist or has no children therefore we return zero files processed.
		}

		$files = $element->children();// Get the array of file nodes to process

		if (count($files) == 0) {
			return 0;// No files to process
		}

		$source 	 	= $this->getPath('source');
		$destination 	= JPATH_SITE.DS.'components'.DS.'com_icagenda'.DS.'themes';
		$destination2 	= JPATH_SITE.DS.'components'.DS.'com_icagenda'.DS.'themes'.DS.'packs';

if(version_compare(JVERSION, '3.0', 'lt')) {
		foreach ($files as $file) {
			if ($file->name() == 'folder') {
				$path['src']	= $source.DS.$file->data();
				$path['dest']	= $destination2.DS.$file->data();
				$copyfolders[] = $path;
			} else {
				$path['src']	= $source.DS.$file->data();
				$path['dest']	= $destination.DS.$file->data();
				$copyfiles[] = $path;
			}
		}
} else {
		if(!empty($files->folder)){
			foreach ($files->folder as $fk => $fv) {
				$path['src']	= $source . '/' . $fv;
				$path['dest']	= $destination2 . '/' . $fv;
				$copyfolders[] = $path;
			}
		}
		if (!empty($files->filename)) {
			foreach($files->filename as $fik => $fiv) {
				$path['src']	= $source . '/' . $fiv;
				$path['dest']	= $destination . '/' . $fiv;
				$copyfiles[] = $path;
			}
		}
}

		return $this->copyFiles($copyfiles, $copyfolders);
	}

	function copyFiles($files, $folders) {

		$i = 0;
		$fileIncluded = $folderIncluded = 0;
		if (is_array($folders) && count($folders) > 0)
		{
			foreach ($folders as $folder)
			{
				// Get the source and destination paths
				$foldersource	= JPath::clean($folder['src']);
				$folderdest		= JPath::clean($folder['dest']);

				if (!JFolder::exists($foldersource)) {
					JError::raiseWarning(1, JText::sprintf('COM_ICAGENDA_FOLDER_NOT_EXISTS', $foldersource));
					return false;
				} else {
					if (!(JFolder::copy($foldersource, $folderdest, '', true))) {
						JError::raiseWarning(1, JText::sprintf('COM_ICAGENDA_ERROR_COPY_FOLDER_TO', $foldersource, $folderdest));
						return false;
					} else {
						$i++;
					}
				}
			}
			$folderIncluded = 1;
		}

		if (is_array($files) && count($files) > 0)
		{
			foreach ($files as $file)
			{
				// Get the source and destination paths
				$filesource	= JPath::clean($file['src']);
				$filedest	= JPath::clean($file['dest']);

				if (!file_exists($filesource)) {
					JError::raiseWarning(1, JText::sprintf('COM_ICAGENDA_FILE_NOT_EXISTS', $filesource));
					return false;
				} else {
					if (!(JFile::copy($filesource, $filedest))) {
						JError::raiseWarning(1, JText::sprintf('COM_ICAGENDA_ERROR_COPY_FILE_TO', $filesource, $filedest));
						return false;
					} else {
						$i++;
					}
				}
			}
			$fileIncluded = 1;
		}

		if ($fileIncluded == 0 && $folderIncluded ==0) {
			JError::raiseWarning(1, JText::sprintf('COM_ICAGENDA_ERROR_INSTALL_FILE'));
			return false;
		}

		return $i;// Possible TO DO, now it returns count folders and files togeter, //return count($files);
	}

	protected function getParamsThemes() {

		$element = $this->_manifest->children()->params;

		if (!is_a($element, 'JXMLElement') || !count($element->children())) {
			return null;// Either the tag does not exist or has no children therefore we return zero files processed.
		}

		$params = $element->children();
		if (count($params) == 0) {
			return null;// No params to process
		}

		// Process each parameter in the $params array.
		$paramsArray = array();
		$i=0;
		foreach ($params as $param) {
			if (!$name = $param['name']) {
				continue;
			}
			if (!$value = $param['default']) {
				continue;
			}

			$paramsArray[$i]['name'] = (string)$name;
			$paramsArray[$i]['value'] = (string)$value;
			$i++;
		}
		return $paramsArray;
	}

	function deleteTempFiles() {
		$path = $this->getPath('source');
		if (is_dir($path)) {
			$val = JFolder::delete($path);
		} else if (is_file($path)) {
			$val = JFile::delete($path);
		}
		$packageFile = $this->getPath('packagefile');
		if (is_file($packageFile)) {
			$val = JFile::delete($packageFile);
		}
		$extractDir = $this->getPath('extractdir');
		if (is_dir($extractDir)) {
			$val = JFolder::delete($extractDir);
		}
	}


	/*
	 * Added @since 3.0.
	 */
	public static function unpack($p_filename)
	{
		// Path to the archive
		$archivename = $p_filename;

		// Temporary folder to extract the archive into
		$tmpdir = uniqid('install_');

		// Clean the paths to use for archive extraction
		$extractdir = JPath::clean(dirname($p_filename) . '/' . $tmpdir);
		$archivename = JPath::clean($archivename);

		// Do the unpacking of the archive
		try
		{
			JArchive::extract($archivename, $extractdir);
		}
		catch (Exception $e)
		{
			return false;
		}

		/*
		 * Let's set the extraction directory and package file in the result array so we can
		 * cleanup everything properly later on.
		 */
		$retval['extractdir'] = $extractdir;
		$retval['packagefile'] = $archivename;

		/*
		 * Try to find the correct install directory.  In case the package is inside a
		 * subdirectory detect this and set the install directory to the correct path.
		 *
		 * List all the items in the installation directory.  If there is only one, and
		 * it is a folder, then we will set that folder to be the installation folder.
		 */
		$dirList = array_merge(JFolder::files($extractdir, ''), JFolder::folders($extractdir, ''));

		if (count($dirList) == 1)
		{
			if (JFolder::exists($extractdir . '/' . $dirList[0]))
			{
				$extractdir = JPath::clean($extractdir . '/' . $dirList[0]);
			}
		}

		/*
		 * We have found the install directory so lets set it and then move on
		 * to detecting the extension type.
		 */
		$retval['dir'] = $extractdir;

		/*
		 * Get the extension type and return the directory/type array on success or
		 * false on fail.
		 */
		$retval['type'] = self::detectType($extractdir);
		if ($retval['type'])
		{
			return $retval;
		}
		else
		{
			return false;
		}
	}

	/*
	 * Added @since 3.0.
	 */
	public static function detectType($p_dir)
	{
		// Search the install dir for an XML file
		$files = JFolder::files($p_dir, '\.xml$', 1, true);

		if (!count($files))
		{
			JLog::add(JText::_('JLIB_INSTALLER_ERROR_NOTFINDXMLSETUPFILE'), JLog::WARNING, 'jerror');
			return false;
		}

		foreach ($files as $file)
		{
			$xml = simplexml_load_file($file);

			if (!$xml)
			{
				continue;
			}

			if ($xml->getName() != 'install')
			{
				unset($xml);
				continue;
			}

			$type = (string) $xml->attributes()->type;

			// Free up memory
			unset($xml);
			return $type;
		}

		JLog::add(JText::_('JLIB_INSTALLER_ERROR_NOTFINDJOOMLAXMLSETUPFILE'), JLog::WARNING, 'jerror');

		// Free up memory.
		unset($xml);
		return false;
	}

}
?>
registration.php000060400000013331152455705640010001 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.7 2015-07-16
 * @since       3.3.3
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modeladmin');


/**
 * iCagenda model.
 */
class iCagendaModelregistration extends JModelAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	3.3.3
	 */
	protected $text_prefix = 'COM_ICAGENDA';

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 *
	 * @since   3.5.6
	 */
	protected function canDelete($record)
	{
		if ( ! empty($record->id))
		{
			if ($record->state != -2)
			{
				return false;
			}

			$user = JFactory::getUser();

			if ($user->authorise('core.delete'))
			{
				icagendaCustomfields::deleteData($record->id, 1);
				icagendaCustomfields::cleanData(1);

				return true;
			}
		}

		return false;
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	3.3.3
	 */
	public function getTable($type = 'Registration', $prefix = 'iCagendaTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		An optional array of data for the form to interogate.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	JForm	A JForm object on success, false on failure
	 * @since	3.3.3
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_icagenda.registration', 'registration',
								array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	3.3.3
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data_array = JFactory::getApplication()->getUserState('com_icagenda.edit.registration.data', array());

		if (empty($data_array))
		{
			$data = $this->getItem();
		}
		else
		{
			$data = new JObject;
			$data->setProperties($data_array);
		}

		return $data;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since	3.5.6
	 */
	public function save($data)
	{
		$app	= JFactory::getApplication();
		$input	= $app->input;
		$date	= JFactory::getDate();
		$user	= JFactory::getUser();

//		if (empty($data['created'])) // not to be used, to leave created empty if before update to 3.5.7
//		{
//			$data['created'] = ( ! empty($data['modified'])) ? $data['modified'] : $date->toSql();
//		}

		// Set registration creator
		if (empty($data['created_by']))
		{
			$data['created_by'] = (int) $data['userid'];
		}

		// Set Params
		if (isset($data['params']) && is_array($data['params']))
		{
			// Convert the params field to a string.
			$parameter = new JRegistry;
			$parameter->loadArray($data['params']);
			$data['params'] = (string)$parameter;
		}

		if ($input->get('task') == 'delete')
		{
			icagendaCustomfields::deleteData($data['custom_fields'], $data['id'], 1);
			$app->enqueueMessage('Test', 'warning');
		}

		// Get Registration ID from the result back to the Table after saving.
		$table = $this->getTable();

		if ($table->save($data) === true)
		{
			$data['id'] = $table->id;
		}
		else
		{
			$data['id'] = null;
		}

		if (parent::save($data))
		{
			// Save Custom Fields to database
			if (isset($data['custom_fields']) && is_array($data['custom_fields']))
			{
				icagendaCustomfields::saveToData($data['custom_fields'], $data['id'], 1);
			}

			return true;
		}

		return false;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param	integer	The id of the primary key.
	 *
	 * @return	mixed	Object on success, false on failure.
	 * @since	3.3.3
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			// Do any procesing on fields here if needed
		}

		return $item;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @since	3.3.3
	 */

	protected function prepareTable($table)
	{
		$date = JFactory::getDate();
		$user = JFactory::getUser();

		$table->name = htmlspecialchars_decode($table->name, ENT_QUOTES);

		if (empty($table->id))
		{
			// Set the values
			$table->created		= $date->toSql();
			$table->created_by	= $user->get('id');

			// Set ordering to the last item if not set
			if (empty($table->ordering))
			{
				$db = JFactory::getDbo();
				$query = $db->getQuery(true)
					->select('MAX(ordering)')
					->from($db->quoteName('#__icagenda_registration'));
				$db->setQuery($query);
				$max = $db->loadResult();

				$table->ordering = $max + 1;
			}
		}
		else
		{
			// Set the values
			$table->modified	= $date->toSql();
			$table->modified_by	= $user->get('id');
		}
	}
}
forms/event.xml000060400000032151152455705640007550 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_icagenda/models/fields" >
		<field
			name="id"
			type="text"
			label="JGLOBAL_FIELD_ID_LABEL"
			description ="JGLOBAL_FIELD_ID_DESC"
			class="readonly"
			size="10"
			readonly="true"
			default="0"
			/>
		<field
			name="title"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_TITLE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_TITLE"
			class="input-xlarge"
			size="30"
			required="true"
			/>
		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			/>
		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			class="span12 small"
			filter="intval"
			size="1"
			default="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="2">JARCHIVED</option>
			<option value="-2">JTRASHED</option>
		</field>
		<field
			name="approval"
			type="list"
			label="COM_ICAGENDA_EVENTS_APPROVAL"
			description="COM_ICAGENDA_EVENTS_APPROVAL_DESC"
			class="span12 small"
			filter="intval"
			size="1"
			default="0"
			>
			<option value="0">COM_ICAGENDA_APPROVED</option>
			<option value="1">COM_ICAGENDA_UNAPPROVED</option>
		</field>
		<field
			name="site_itemid"
			type="test"
			label="COM_ICAGENDA_FORM_FRONTEND_SUBMIT_ITEMID_LBL"
			description="COM_ICAGENDA_FORM_FRONTEND_SUBMIT_ITEMID_DESC"
			size="3"
			class="inputbox"
			readonly="true"
			default="0"
			/>
		<field
			name="access"
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="COM_ICAGENDA_ACCESS_DESC"
			class="span12 small"
			size="1"
			default="1"
		/>
		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="COM_ICAGENDA_FORM_DESC_LANGUAGE"
			class="span12 small"
			>
			<option value="*">JALL</option>
		</field>
		<field
			name="created"
			type="calendar"
			label="JGLOBAL_FIELD_CREATED_LABEL"
			format="%Y-%m-%d %H:%M:%S"
			filter="user_utc"
			/>
		<field
			name="created_by"
			type="user"
			label="JGLOBAL_FIELD_CREATED_BY_LABEL"
			description="JGLOBAL_FIELD_CREATED_BY_DESC"
			/>
		<field
			name="created_by_alias"
			type="text"
			label="JGLOBAL_FIELD_CREATED_BY_ALIAS_LABEL"
			description="JGLOBAL_FIELD_CREATED_BY_ALIAS_DESC"
			class="inputbox"
			size="20"
			/>
		<field
			name="username"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_USERNAME"
			description="COM_ICAGENDA_FORM_DESC_EVENT_USERNAME"
			size="40"
			class="inputbox"
			filter="safehtml"
			/>
		<field
			name="modified"
			type="calendar"
			label="JGLOBAL_FIELD_MODIFIED_LABEL"
			class="readonly"
			size="22"
			readonly="true"
			format="%Y-%m-%d %H:%M:%S"
			filter="user_utc"
			/>
		<field
			name="modified_by"
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			description="JGLOBAL_FIELD_MODIFIED_BY_DESC"
			class="readonly"
			readonly="true"
			filter="unset"
			/>
		<field name="checked_out" type="hidden" filter="unset" />
		<field name="checked_out_time" type="hidden" filter="unset" />
		<field
			name="catid"
			type="modal_cat"
			label="COM_ICAGENDA_FORM_LBL_EVENT_CATID"
			description="COM_ICAGENDA_FORM_DESC_EVENT_CATID"
			class="inputbox"
			required="true"
			/>
		<field
			name="image"
			type="media"
			label="COM_ICAGENDA_FORM_LBL_EVENT_IMAGE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_IMAGE"
			filter="safehtml"
			/>
		<field
			name="file"
			type="modal_icfile"
			class="inputbox"
			id="upload_file"
			label="COM_ICAGENDA_FORM_LBL_EVENT_FILE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_FILE"
			/>
		<field
			name="displaytime"
			type="radio"
			class="btn-group"
			label="COM_ICAGENDA_DISPLAY_TIME_LABEL"
			description="COM_ICAGENDA_DISPLAY_TIME_DESC"
			>
			<option value="0">JHIDE</option>
			<option value="1">JSHOW</option>
		</field>
		<field
			name="dates"
			type="modal_date"
			class="inputbox"
			label="COM_ICAGENDA_FORM_LBL_EVENT_DATES"
			description="COM_ICAGENDA_FORM_DESC_EVENT_DATES"
			default="0000-00-00 00:00"
			/>
		<!--field
			name="eventDates"
			type="modal_ic_singledates"
			label="COM_ICAGENDA_FORM_LBL_EVENT_DATES"
			description="COM_ICAGENDA_FORM_DESC_EVENT_DATES"
			class="inputbox"
			/-->
		<field
			name="startdate"
			type="modal_startdate"
			size="40"
			class="inputbox"
			label="COM_ICAGENDA_FORM_LBL_EVENTPERIOD_START"
			description="COM_ICAGENDA_FORM_DESC_EVENTPERIOD_START"
			/>
		<field
			name="enddate"
			type="modal_enddate"
			size="40"
			class="inputbox"
			label="COM_ICAGENDA_FORM_LBL_EVENTPERIOD_END"
			description="COM_ICAGENDA_FORM_DESC_EVENTPERIOD_END"
			/>
		<field
			name="weekdays"
			type="list"
			label="COM_ICAGENDA_FORM_LBL_WEEK_DAYS"
			description="COM_ICAGENDA_FORM_WEEK_DAYS_INFO_DESC"
			multiple="true"
			default=""
			>
			<option value="0">SUNDAY</option>
			<option value="1">MONDAY</option>
			<option value="2">TUESDAY</option>
			<option value="3">WEDNESDAY</option>
			<option value="4">THURSDAY</option>
			<option value="5">FRIDAY</option>
			<option value="6">SATURDAY</option>
		</field>
		<!--field
			name="weekdays_filter"
			type="modal_icfilter_weekdays"
			label="COM_ICAGENDA_FORM_LBL_WEEK_DAYS"
			description="COM_ICAGENDA_FORM_DESC_WEEK_DAYS"
			multiple="true"
			default=""
			/-->
		<field
			name="next"
			type="hidden"
			class="inputbox"
			default="0000-00-00 00:00:00"
			/>
		<field
			name="email"
			type="email"
			label="COM_ICAGENDA_FORM_LBL_EVENT_EMAIL"
			description="COM_ICAGENDA_FORM_DESC_EVENT_EMAIL"
			size="30"
			class="inputbox"
			filter="safehtml"
			/>
		<field
			name="phone"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_PHONE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_PHONE"
			size="30"
			class="inputbox"
			filter="safehtml"
			/>
		<field
			name="website"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_WEBSITE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_WEBSITE"
			size="30"
			class="inputbox"
			filter="safehtml"
			/>
		<field
			name="features"
			type="sql"
			label="COM_ICAGENDA_FORM_LBL_EVENT_FEATURES"
			description="COM_ICAGENDA_FORM_DESC_EVENT_FEATURES"
			query="SELECT id AS value, title AS features FROM #__icagenda_feature WHERE state=1 AND icon IS NOT NULL AND icon!='' ORDER BY features"
			multiple="true"
			class="inputbox"
			/>
		<!--field
			name="features"
			type="modal_features"
			label="COM_ICAGENDA_FORM_LBL_EVENT_FEATURES"
			description="COM_ICAGENDA_FORM_DESC_EVENT_FEATURES"
			multiple="true"
			class="inputbox"
			/-->
		<field
			name="custom_fields"
			type="hidden"
			class="inputbox"
			default=""
			/>
		<field
			name="place"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_VENUE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_VENUE"
			size="30"
			class="inputbox"
			filter="safehtml"
			/>
		<field
			name="coordinate"
			type="modal_coordinate"
			label="COM_ICAGENDA_FORM_LBL_EVENT_MAP"
			description="COM_ICAGENDA_FORM_DESC_EVENT_MAP"
			class="inputbox"
			/>
		<field
			name="address"
			type="text"
			label="COM_ICAGENDA_GOOGLE_MAPS_ADDRESS_LBL"
			description="COM_ICAGENDA_FORM_DESC_EVENT_LOCATION"
			class="inputbox"
			filter="safehtml"
			/>
		<field
			name="city"
			type="icmap_city"
			label="COM_ICAGENDA_FORM_LBL_EVENT_CITY"
			description="COM_ICAGENDA_FORM_DESC_EVENT_CITY"
			class="inputbox"
			filter="safehtml"
			/>
		<field
			name="country"
			type="icmap_country"
			label="COM_ICAGENDA_FORM_LBL_EVENT_COUNTRY"
			description="COM_ICAGENDA_FORM_DESC_EVENT_COUNTRY"
			class="inputbox"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="lat"
			type="icmap_lat"
			label="LATITUDE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_MAP"
			class="inputbox"
			/>
		<field
			name="lng"
			type="icmap_lng"
			label="LONGITUDE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_MAP"
			class="inputbox"
			/>
		<field
			name="shortdesc"
			type="modal_ictextarea_counter"
			label="COM_ICAGENDA_FORM_EVENT_SHORT_DESCRIPTION_LBL"
			description="COM_ICAGENDA_FORM_EVENT_SHORT_DESCRIPTION_DESC"
			class="span-12"
			row="3"
			cols="80"
			/>
		<field
			name="desc"
			type="editor"
			label="COM_ICAGENDA_FORM_LBL_EVENT_DESC"
			description="COM_ICAGENDA_FORM_DESC_EVENT_DESC"
			buttons="true"
			hide="readmore,pagebreak,helix_shortcode"
			class="inputbox"
			filter="JComponentHelper::filterText"
			/>
		<field
			name="metadesc"
			type="modal_ictextarea_counter"
			label="COM_ICAGENDA_FORM_EVENT_METADESC_LBL"
			description="COM_ICAGENDA_FORM_EVENT_METADESC_DESC"
			class="span-12"
			row="3"
			cols="80"
			/>
	</fieldset>
	<fields name="params">

		<!-- Registrations Tab - Individual Params -->
		<fieldset name="registrations"
			addfieldpath="/administrator/components/com_icagenda/assets/elements"
			>
			<field type="TitleHeader" label="COM_ICAGENDA_REGISTRATION_LABEL" />
			<field
				name="statutReg"
				type="radio"
				label="COM_ICAGENDA_REGISTRATION_LABEL"
				description="COM_ICAGENDA_REGISTRATION_DESC"
				labelclass="control-label"
				class="btn-group"
				default=""
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="0">JOFF</option>
				<option value="1">JON</option>
			</field>
			<field
				name="accessReg"
				type="accesslevel"
				label="JFIELD_ACCESS_LABEL"
				description="JFIELD_ACCESS_DESC"
				class="inputbox"
				size="1"
				default=""
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
			</field>
			<field type="TitleHeader" label="COM_ICAGENDA_REGISTRATION_FORM_OPTIONS_LABEL" />
			<field
				name="typeReg"
				type="list"
				label="COM_ICAGENDA_TYPE_REG_LABEL"
				description="COM_ICAGENDA_TYPE_REG_DESC"
				default="1"
				>
				<option value="1">COM_ICAGENDA_ADMIN_REGISTRATION_BY_INDIVIDUAL_DATE</option>
				<option value="2">COM_ICAGENDA_ADMIN_REGISTRATION_FOR_ALL_DATES</option>
			</field>
			<!--field type="Title" label="COM_ICAGENDA_MAX_REGISTRATIONS_DESC"
				class="styleblanck"/-->
			<!--field
				name="maxRegGlobal"
				type="radio"
				label="JGLOBAL_USE_GLOBAL"
				description="JGLOBAL_USE_GLOBAL"
				default="1"
				>
				<option value="1">JYES</option>
				<option value="0">JNO</option>
			</field-->
			<field
				name="maxReg"
				type="text"
				label="COM_ICAGENDA_MAX_REGISTRATIONS_LABEL"
				description="COM_ICAGENDA_MAX_REGISTRATIONS_DESC"
				size="3"
				default=""
				/>
			<field
				name="maxRlistGlobal"
				type="radio"
				label="COM_ICAGENDA_MAX_PER_REGISTRATION_LABEL"
				description="COM_ICAGENDA_MAX_PER_REGISTRATION_DESC"
				labelclass="control-label"
				class="btn-group"
				default=""
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="2">COM_ICAGENDA_LBL_CUSTOM_VALUE</option>
			</field>
			<field
				name="maxRlist"
				type="text"
				label="COM_ICAGENDA_LBL_CUSTOM_VALUE"
				description="COM_ICAGENDA_DESC_CUSTOM_VALUE"
				size="2"
				default=""
				/>
			<field type="TitleHeader" label="COM_ICAGENDA_REGISTRATION_BUTTON" />
			<!--field
				name="maxRlistGlobal"
				type="radio"
				label="COM_ICAGENDA_MAX_PER_REGISTRATION_LABEL"
				description="COM_ICAGENDA_MAX_PER_REGISTRATION_DESC"
				labelclass="control-label"
				class="btn-group"
				default=""
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="2">COM_ICAGENDA_LBL_CUSTOM_VALUE</option>
			</field-->
			<field
				name="RegButtonText"
				type="modal_ph_regbt"
				label="COM_ICAGENDA_REGISTRATION_BUTTON_TEXT"
				description="COM_ICAGENDA_REGISTRATION_BUTTON_TEXT_DESC"
				size="40"
				class="inputbox"
				default=""
				/>
			<field
				name="RegButtonLink"
				type="modal_iclink_type"
				label="COM_ICAGENDA_REGISTRATION_LINK_LBL"
				description="COM_ICAGENDA_REGISTRATION_LINK_DESC"
				labelclass="control-label"
				default=""
				/>
			<field
				name="RegButtonLink_Article"
				type="modal_iclink_article"
				label=" "
				class="inputbox"
				/>
			<field
				name="RegButtonLink_Url"
				type="modal_iclink_url"
				label=" "
				class="inputbox"
				/>
			<field
				name="RegButtonTarget"
				type="list"
				label="COM_ICAGENDA_BROWSER_TARGET"
				description="COM_ICAGENDA_REGISTRATION_LINK_BROWSER_TARGET_DESC"
				default="0"
				filter="options"
				class="inputbox"
				>
				<option value="0">JBROWSERTARGET_PARENT</option>
				<option value="1">JBROWSERTARGET_NEW</option>
			</field>
			<field type="Title" label=" "
				class="styleblanck"/>
		</fieldset>

		<!-- Registrations Tab - Actions -->
		<fieldset name="registration_actions">
		</fieldset>

		<!-- Option Tab - Options -->
		<fieldset name="options">
			<field type="Title" label="COM_ICAGENDA_ADDTHIS"
				class="styleblanck"/>
			<field
				name="atevent"
				type="radio"
				label="COM_ICAGENDA_ADDTHIS_DISPLAY_SHARING"
				description="COM_ICAGENDA_ADDTHIS_EVENT_DESC"
				class="btn-group"
				default=""
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="0">JHIDE</option>
				<option value="1">JSHOW</option>
			</field>
			<!--field
				name="mapTypeId"
				type="list"
				label="mapTypeId"
				description="mapTypeId"
				filter="safehtml"
				default="ROADMAP"
				>
				<option value="ROADMAP">ROADMAP</option>
				<option value="TERRAIN">TERRAIN</option>
				<option value="SATELLITE">SATELLITE</option>
				<option value="HYBRID">HYBRID</option>
			</field-->
		</fieldset>
	</fields>
</form>
forms/customfield.xml000060400000010221152455705640010737 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_icagenda/models/fields">
		<field
			name="id"
			type="text"
			class="readonly"
			label="JGLOBAL_FIELD_ID_LABEL"
			description ="JGLOBAL_FIELD_ID_DESC"
			size="10"
			default="0"
			readonly="true"
			/>
		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			class="span12 small"
			filter="intval"
			size="1"
			default="1"
			>
				<option value="1">JPUBLISHED</option>
				<option value="0">JUNPUBLISHED</option>
		</field>
		<field
			name="title"
			type="text"
			label="COM_ICAGENDA_CUSTOMFIELD_TITLE_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_TITLE_DESC"
			size="30"
			required="true"
			/>
		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			/>
		<field
			name="slug"
			type="text"
			label="COM_ICAGENDA_CUSTOMFIELD_SLUG_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_SLUG_DESC"
			/>
		<field
			name="description"
			type="editor"
			buttons="readmore,pagebreak"
			class="inputbox"
			filter="JComponentHelper::filterText"
			label="COM_ICAGENDA_CUSTOMFIELD_DESCRIPTION_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_DESCRIPTION_DESC"
			/>
		<field
			name="parent_form"
			type="list"
			filter="intval"
			required="true"
			label="COM_ICAGENDA_CUSTOMFIELD_PARENT_FORM_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_PARENT_FORM_DESC"
			default=""
			>
				<option value="">COM_ICAGENDA_CUSTOMFIELD_PARENT_SELECT</option>
				<option value="1">COM_ICAGENDA_CUSTOMFIELD_PARENT_REGISTRATION_FORM</option>
				<option value="2">COM_ICAGENDA_CUSTOMFIELD_PARENT_EVENT_EDIT</option>
		</field>
		<field
			name="type"
			type="list"
			required="true"
			label="COM_ICAGENDA_CUSTOMFIELD_TYPE_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_TYPE_DESC"
			default=""
			>
				<option value="">COM_ICAGENDA_CUSTOMFIELD_TYPE_SELECT</option>
				<option value="text">COM_ICAGENDA_CUSTOMFIELD_TYPE_TEXT</option>
				<option value="list">COM_ICAGENDA_CUSTOMFIELD_TYPE_LIST</option>
				<option value="radio">COM_ICAGENDA_CUSTOMFIELD_TYPE_RADIO</option>
		</field>
		<field
			name="options"
			type="textarea"
			label="COM_ICAGENDA_CUSTOMFIELD_OPTIONS_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_OPTIONS_DESC"
			/>
		<field
			name="default"
			type="text"
			label="COM_ICAGENDA_CUSTOMFIELD_DEFAULT_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_DEFAULT_DESC"
			/>
		<field
			name="required"
			type="radio"
			label="COM_ICAGENDA_CUSTOMFIELD_REQUIRED_LBL"
			description="COM_ICAGENDA_CUSTOMFIELD_REQUIRED_DESC"
			labelclass="control-label"
			class="btn-group"
			default="0"
			>
				<option value="0">JNO</option>
				<option value="1">JYES</option>
		</field>
		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="COM_ICAGENDA_CUSTOMFIELD_LANGUAGE_DESC"
			class="span12 small"
			>
				<option value="*">JALL</option>
		</field>
		<field
			name="created"
			type="calendar"
			label="JGLOBAL_FIELD_CREATED_LABEL"
			format="%Y-%m-%d %H:%M:%S"
			filter="user_utc"
			labelclass="control-label"
			/>
		<field
			name="created_by"
			type="user"
			label="JGLOBAL_FIELD_CREATED_BY_LABEL"
			description="JGLOBAL_FIELD_CREATED_BY_DESC"
			labelclass="control-label"
			/>
		<!-- created_by_alias to be removed ? Not really needed there... -->
		<field
			name="created_by_alias"
			type="text"
			label="JGLOBAL_FIELD_CREATED_BY_ALIAS_LABEL"
			description="JGLOBAL_FIELD_CREATED_BY_ALIAS_DESC"
			class="inputbox"
			size="20"
			labelclass="control-label"
			/>
		<field
			name="modified"
			type="calendar"
			class="readonly"
			label="JGLOBAL_FIELD_MODIFIED_LABEL"
			size="22"
			readonly="true"
			format="%Y-%m-%d %H:%M:%S"
			filter="user_utc"
			labelclass="control-label"
			/>
		<field
			name="modified_by"
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			description="JGLOBAL_FIELD_MODIFIED_BY_DESC"
			class="readonly"
			readonly="true"
			filter="unset"
			labelclass="control-label"
			/>
		<field name="checked_out" type="hidden" filter="unset" />
		<field name="checked_out_time" type="hidden" filter="unset" />
	</fieldset>
</form>
forms/index.html000060400000000054152455705640007677 0ustar00<html><body bgcolor="#FFFFFF"></body></html>forms/feature.xml000060400000004256152455705640010067 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_icagenda/models/fields">

		<field
			name="id"
			type="text"
			class="readonly"
			label="JGLOBAL_FIELD_ID_LABEL"
			description ="JGLOBAL_FIELD_ID_DESC"
			size="10"
			default="0"
			readonly="true"
		/>

		<field
			name="title"
			type="text"
			label="COM_ICAGENDA_FORM_FEATURE_TITLE_LABEL"
			description="COM_ICAGENDA_FORM_FEATURE_TITLE_DESC"
			size="30"
			required="true"
		/>

		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
		/>

		<field
			name="icon"
			type="imagelist"
			directory="images/icagenda/feature_icons/16_bit"
			exclude="\.(?:html|htm)$"
			hide_none="false"
			hide_default="true"
			label="COM_ICAGENDA_FORM_FEATURE_ICON_LABEL"
			description="COM_ICAGENDA_FORM_FEATURE_ICON_DESC"
			required="false"
		/>

		<field
			name="new_icon"
			type="media"
			label="COM_ICAGENDA_FORM_FEATURE_NEW_ICON_LABEL"
			description="COM_ICAGENDA_FORM_FEATURE_NEW_ICON_LABEL"
			filter="safehtml"
		/>

		<field
			name="icon_alt"
			type="text"
			label="COM_ICAGENDA_FORM_FEATURE_ICON_ALT_LABEL"
			description="COM_ICAGENDA_FORM_FEATURE_ICON_ALT_DESC"
			size="30"
			required="false"
		/>

		<field
			name="show_filter"
			type="radio"
			class="btn-group"
			default="1"
			label="COM_ICAGENDA_FORM_FEATURE_SHOW_FILTER_LABEL"
			description="COM_ICAGENDA_FORM_FEATURE_SHOW_FILTER_DESC">
				<option value="0">JNO</option>
				<option value="1">JYES</option>
		</field>

		<field
			name="desc"
			type="editor"
			buttons="readmore,pagebreak"
			class="inputbox"
			filter="JComponentHelper::filterText"
			label="COM_ICAGENDA_FORM_FEATURE_DESCRIPTION_LABEL"
			description="COM_ICAGENDA_FORM_FEATURE_DESCRIPTION_DESC"
		/>

		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			class="span12 small"
			filter="intval"
			size="1"
			default="1">
				<option value="1">JPUBLISHED</option>
				<option value="0">JUNPUBLISHED</option>
		</field>

		<field name="checked_out" type="hidden" filter="unset" />
		<field name="checked_out_time" type="hidden" filter="unset" />

	</fieldset>
</form>
forms/registration.xml000060400000000712152455705640011137 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_icagenda/models/fields" >
		<field
			name="captcha"
			type="captcha"
			label="COM_ICAGENDA_CAPTCHA_LABEL"
			description="COM_ICAGENDA_CAPTCHA_DESC"
			validate="captcha"
			namespace="registration"
		/>
		<field
			name="date"
			type="calendar"
			label="COM_ICAGENDA_CAPTCHA_LABEL"
			description="COM_ICAGENDA_CAPTCHA_DESC"
		/>
	</fieldset>
</form>
forms/mail.xml000060400000001511152455705640007345 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="eventid"
			type="modal_evt"
			label="ICEVENT"
			description =" "
			class="inputbox"
			size="10"
			default="0"
			/>
		<field
			name="date"
			type="modal_evt_date"
			size="30"
			class="inputbox"
			label="COM_ICAGENDA_REGISTRATION_DATE"
			description=" "
			filter="safehtml"
			/>
		<field
			name="subject"
			type="text"
			size="40"
			class="inputbox input-xxlarge"
			label="COM_ICAGENDA_FORM_LBL_NEWSLETTER_OBJ"
			description="COM_ICAGENDA_FORM_DESC_NEWSLETTER_OBJ"
			/>
		<field
			name="message"
			type="editor"
			class="inputbox"
			buttons="readmore,pagebreak"
			label="COM_ICAGENDA_FORM_LBL_NEWSLETTER_BODY"
			description="COM_ICAGENDA_FORM_DESC_NEWSLETTER_BODY"
			cols="70"
			rows="20"
			filter="safehtml"
			/>
	</fieldset>
</form>
forms/category.xml000060400000003005152455705640010240 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<!--fields addfieldpath="/administrator/components/com_icagenda/models/fields"-->
	<fieldset addfieldpath="/administrator/components/com_icagenda/models/fields">
		<field
			name="id"
			type="text"
			class="readonly"
			label="JGLOBAL_FIELD_ID_LABEL"
			description ="JGLOBAL_FIELD_ID_DESC"
			size="10"
			default="0"
			readonly="true"
		/>

		<field
 			name="title"
 			type="text"
 			label="COM_ICAGENDA_FORM_LBL_CATEGORY_TITLE"
			description="COM_ICAGENDA_FORM_DESC_CATEGORY_TITLE"
			size="30"
			required="true"
		/>

		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
		/>

		<field
			name="color"
			type="color"
			size="40"
			class="inputbox"
			label="COM_ICAGENDA_FORM_LBL_CATEGORY_COLOR"
			description="COM_ICAGENDA_FORM_DESC_CATEGORY_COLOR"
			default="#bdbdbd"
		/>

		<field
			name="desc"
			type="editor"
			buttons="readmore,pagebreak"
			class="inputbox"
			filter="JComponentHelper::filterText"
			label="COM_ICAGENDA_FORM_LBL_EVENT_DESC"
			description="COM_ICAGENDA_FORM_DESC_EVENT_DESC"
		/>

		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			class="span12 small"
			filter="intval"
			size="1"
			default="1">
				<option value="1">JPUBLISHED</option>
				<option value="0">JUNPUBLISHED</option>
		</field>

		<field name="checked_out" type="hidden" filter="unset" />
		<field name="checked_out_time" type="hidden" filter="unset" />

	</fieldset>
</form>
registrations.php000060400000051150152455705640010165 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.12 2015-09-22
 * @since		2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modellist');

/**
 * Methods supporting a list of iCagenda records.
 */
class iCagendaModelregistrations extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param	array			An optional associative array of configuration settings.
	 * @see		JController
	 * @since	1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'ordering', 'a.ordering',
				'userid', 'userid',
				'name', 'name',
				'username', 'username',
				'email', 'email',
				'phone', 'phone',
				'event', 'event',
				'date', 'a.date',
				'startdate', 'e.startdate',
				'people', 'a.people',
				'notes', 'a.notes',
				'evt_created_by', 'a.evt_created_by'
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = JFactory::getApplication('administrator');

		// Load the filter search.
		$search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		// Filter (dropdown) state.
		$published = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string');
		$this->setState('filter.state', $published);

		// Filter (dropdown) categories
		$categories = $this->getUserStateFromRequest($this->context.'.filter.categories', 'filter_categories', '', 'string');
		$this->setState('filter.categories', $categories);

		// Filter (dropdown) events
		$events = $this->getUserStateFromRequest($this->context.'.filter.events', 'filter_events', '', 'string');
		$this->setState('filter.events', $events);

		// Filter (dropdown) dates
		$dates = $this->getUserStateFromRequest($this->context.'.filter.dates', 'filter_dates', '', 'string');
		$this->setState('filter.dates', $dates);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_icagenda');
		$this->setState('params', $params);

		// List state information.
		parent::populateState('a.id', 'desc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param	string		$id	A prefix for the store id.
	 * @return	string		A store id.
	 * @since	1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id.= ':' . $this->getState('filter.search');
		$id.= ':' . $this->getState('filter.state');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return	JDatabaseQuery
	 * @since	1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.*'
			)
		);
		$query->from('`#__icagenda_registration` AS a');

		// Join over the events.
		$query->select('e.title AS event, e.created_by AS evt_created_by, e.state AS evt_state,
						e.startdate AS startdate, e.enddate AS enddate, e.displaytime AS displaytime');
		$query->join('LEFT', '#__icagenda_events AS e ON e.id=a.eventid');

		// Join over the categories.
		$query->select('c.id AS cat_id, c.title AS cat_title');
		$query->join('LEFT', '#__icagenda_category AS c ON c.id=e.catid');

		// Join over the users for the checked out user.
		$query->select('u.username AS username, u.name AS fullname');
		$query->join('LEFT', '#__users AS u ON u.id=a.userid');

		// Join over the users for the author.
		$query->select('ua.name AS author_name, ua.username AS author_username')
			->join('LEFT', '#__users AS ua ON ua.id = a.created_by');

		// Filter by published state
		$published = $this->getState('filter.state');

		if (is_numeric($published))
		{
			$query->where('a.state = '.(int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.state IN (0, 1))');
		}

		// Filter by edit access
		if ( ! JFactory::getUser()->authorise('core.edit', 'com_icagenda')
			&& JFactory::getUser()->authorise('core.edit.own', 'com_icagenda'))
		{
			$userID = JFactory::getUser()->get('id');
			$query->where('a.userid = ' . (int) $userID);
		}

		// Filter by search in content
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = '.(int) substr($search, 3));
			}
			else
			{
				if(version_compare(JVERSION, '3.0', 'lt'))
				{
					$search = $db->Quote('%'.$db->getEscaped($search, true).'%');
				}
				else
				{
					$search = $db->Quote('%'.$db->escape($search, true).'%');
				}
				$query->where('(u.username LIKE '.$search.'  OR  a.name LIKE '.$search.'  OR  a.userid LIKE '.$search.'  OR  a.email LIKE '.$search.'  OR  a.phone LIKE '.$search.'  OR  a.date LIKE '.$search.'  OR  a.period LIKE '.$search.'  OR  a.people LIKE '.$search.'  OR  a.notes LIKE '.$search.'  OR  e.title LIKE '.$search.' )');
			}
		}

		// Filter categories
		$category = $db->escape($this->getState('filter.categories'));

		if (!empty($category))
		{
			$query->where('(c.id=' . $db->q($category) . ')');
		}

		// Filter events
		$event = $db->escape($this->getState('filter.events'));

		if (!empty($event))
		{
			$query->where('(a.eventid=' . $db->q($event) . ')');
		}

		// Filter dates
		$date = $db->escape($this->getState('filter.dates'));

		if (!empty($date) && ! in_array($date, array('1', '2')))
		{
			$query->where($db->qn('a.date') . ' = ' . $db->q($date));
		}
		elseif ($date == 1)
		{
			$query->where($db->qn('a.date') . ' = ""');
			$query->where($db->qn('a.period') . ' = "0"');
		}
		elseif ($date == 2)
		{
			$query->where($db->qn('a.date') . ' = ""');
			$query->where($db->qn('a.period') . ' = "1"');
		}

		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering');
		$orderDirn	= $this->state->get('list.direction');

		if ($orderCol && $orderDirn)
		{
			if (version_compare(JVERSION, '3.0', 'lt'))
			{
				if ($orderCol == 'a.date')
				{
					$query->order($db->getEscaped($db->qn('a.period') . ' ' . $orderDirn));
				}

				$query->order($db->getEscaped($orderCol . ' ' . $orderDirn));
			}
			else
			{
				if ($orderCol == 'a.date')
				{
					$query->order($db->escape($db->qn('a.period') . ' ' . $orderDirn));
				}

				$query->order($db->escape($orderCol . ' ' . $orderDirn));
			}
		}

		return $query;
	}

	/**
	 * Gets a list of categories.
	 */
	function getCategories()
	{
		// Create a new query object.
		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select('c.id AS cat_id, c.title AS cat_title');
		$query->from('`#__icagenda_category` AS c');

		// Join over the events.
		$query->select('e.id AS id');
		$query->join('LEFT', '#__icagenda_events AS e ON e.catid=c.id');

		// Join over the registrations.
		$query->select('r.eventid AS event_id');
		$query->join('LEFT', '#__icagenda_registration AS r ON r.eventid=e.id');
		$query->where('(e.id = r.eventid)');
		$query->order('c.ordering ASC');

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

		$list = array();

		foreach ($categories as $c)
		{
			$list[$c->cat_id] = $c->cat_title . ' [' . $c->cat_id . ']';
		}

		return $list;
	}

	/**
	 * Gets a list of all events.
	 */
	function getEvents()
	{
		// Create a new query object.
		$db		= JFactory::getDBO();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select('e.id AS event, e.title AS title');
		$query->from('`#__icagenda_events` AS e');

		// Join over the categories.
		$query->select('c.id AS cat_id, c.title AS cat_title');
		$query->join('LEFT', '#__icagenda_category AS c ON c.id=e.catid');

		// Join over the registrations.
		$query->select('r.eventid AS eventid');
		$query->join('LEFT', '#__icagenda_registration AS r ON r.eventid=e.id');
		$query->where('(e.id = r.eventid)');
		$query->order('e.title ASC');

		// Filter by published state
//		$query->where('(e.state IN (0, 1))');

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

		$list = array();

		$catId = $db->escape($this->getState('filter.categories'));

		foreach ($events as $e)
		{
			if ( ! empty($catId) && $catId == $e->cat_id)
			{
				$list[$e->event] = $e->title . ' [' . $e->event . ']';
			}
			elseif (empty($catId))
			{
				$list[$e->event] = $e->title . ' [' . $e->event . ']';
			}
//			$list[$e->event] = $e->title . ' [' . $e->event . ']';
		}

		return $list;
	}

	/**
	 * Gets a list of dates.
	 */
	function getDates()
	{
		$params			= $this->getState('params');
		$dateFormat		= $params->get('date_format_global', 'Y - m - d');
		$dateSeparator	= $params->get('date_separator', ' ');
		$timeFormat		= ($params->get('timeformat', '1') == 1) ? 'H:i' : 'h:i A';

		// Create a new query object.
		$db		= JFactory::getDBO();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select('r.date AS date, r.period AS period, r.eventid AS eventid');
		$query->from('`#__icagenda_registration` AS r');

		// Join over the events (period).
		$query->select('e.startdate AS startdate, e.enddate AS enddate, e.displaytime AS displaytime');
		$query->join('LEFT', '#__icagenda_events AS e ON e.id=r.eventid');

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

		$list = array();

		$eventId = $db->escape($this->getState('filter.events'));

		$p = $e = 0;

		// Add to select dropdown the filters 'For all dates of the event' and/or 'For all the period',
		// depending of registrations in data, and selected event
		foreach ($dates as $d)
		{
//			$date	= (empty($d->date) && $d->period == 0)
//					? '[ ' . ucfirst(JText::_('COM_ICAGENDA_ADMIN_REGISTRATION_FOR_ALL_PERIOD')) . ' ]'
//					: '';
			$period	= (empty($d->date) && $d->period == 1)
					? '[ ' . ucfirst(JText::_('COM_ICAGENDA_ADMIN_REGISTRATION_FOR_ALL_DATES')) . ' ]'
					: '';

			if (empty($d->date)
				&& $d->period == 1
				&& $e == 0
				)
			{
				if ( ! empty($eventId) && $eventId == $d->eventid)
				{
					$e = $e+1;
					$list[2] = $period;
				}
				elseif (empty($eventId))
				{
					$e = $e+1;
					$list[2] = $period;
				}
			}
		}

		// Add to select dropdown the list of dates,
		// depending of registrations in data, and selected event
		foreach ($dates as $d)
		{
			$date = '';

			if (empty($d->date) && $d->period == 0)
			{
				if ( ! empty($eventId) && $eventId == $d->eventid)
				{
					if (iCDate::isDate($d->startdate))
					{
						$date = iCGlobalize::dateFormat($d->startdate, $dateFormat, $dateSeparator);

						if ($d->displaytime)
						{
							$date.= ' - ' . date($timeFormat, strtotime($d->startdate));
						}
					}
					if (iCDate::isDate($d->enddate))
					{
						$date.= ' > ' . iCGlobalize::dateFormat($d->enddate, $dateFormat, $dateSeparator);

						if ($d->displaytime)
						{
							$date.= ' - ' . date($timeFormat, strtotime($d->enddate));
						}
					}
				}
				else
				{
					$date = '[ ' . ucfirst(JText::_('COM_ICAGENDA_ADMIN_REGISTRATION_FOR_ALL_PERIOD')) . ' ]';
				}
			}
			else
			{
				$date	= iCDate::isDate($d->date)
						? JHtml::date($d->date, JText::_('DATE_FORMAT_LC3'), null) . ' - ' . date('H:i', strtotime($d->date))
						: $d->date;
			}

			$display_date = ($date != '0000-00-00 00:00:00' && $d->date) ? true : false;

			if ($display_date
				&& ! empty($eventId)
				&& $eventId == $d->eventid
				)
			{
				$list[$d->date] = $date;
			}
			elseif ($display_date
				&& empty($eventId)
				)
			{
				$list[$d->date] = $date;
			}

			if (empty($d->date)
				&& $d->period == 0
				&& $p == 0
				)
			{
				if ( ! empty($eventId) && $eventId == $d->eventid)
				{
					$p = $p+1;
					$list[1] = $date;
				}
				elseif (empty($eventId))
				{
					$p = $p+1;
					$list[1] = $date;
				}
			}
		}

		return $list;
	}
	/**
	 * Get file name
	 *
	 * @return  string    The file name
	 *
	 * @since   1.6
	 */
	public function getBaseName()
	{
		if (!isset($this->basename))
		{
			$app = JFactory::getApplication();
			$basename = $this->getState('basename');
			$basename = str_replace('__SITE__', $app->getCfg('sitename'), $basename);

			$eventId = $this->getState('filter.events');

			if (is_numeric($eventId))
			{
				$basename = str_replace('__EVENTID__', $eventId, $basename);
				$basename = str_replace('__EVENT__', $this->getEventTitle($eventId), $basename);
			}
			else
			{
				$basename = str_replace('__EVENTID__', '', $basename);
				$basename = str_replace('__EVENT__', '', $basename);
			}

			$date = $this->getState('filter.dates');

			if (!empty($date))
			{
				if (iCDate::isDate($date))
				{
					$basename = str_replace('__DATE__', JHtml::date($date, JText::_('DATE_FORMAT_LC3'), null)
											. ' - ' . date('H:i', strtotime($date)),
											$basename);
				}
				else
				{
					$basename = str_replace('__DATE__', $date, $basename);
				}
			}
			else
			{
				$basename = str_replace('__DATE__', '', $basename);
			}

			$this->basename = $basename;
		}

		return $this->basename;
	}

	/**
	 * Get the event title.
	 *
	 * @return  string    The event title
	 *
	 * @since   3.5.0
	 */
	protected function getEventTitle()
	{
		$eventId = $this->getState('filter.events');

		if ($eventId)
		{
			$db = $this->getDbo();
			$query = $db->getQuery(true)
				->select('title')
				->from($db->quoteName('#__icagenda_events'))
				->where($db->quoteName('id') . '=' . $db->quote($eventId));
			$db->setQuery($query);

			try
			{
				$title = $db->loadResult();
			}
			catch (RuntimeException $e)
			{
				$this->setError($e->getMessage());

				return false;
			}
		}
		else
		{
			$title = JText::_('COM_ICAGENDA_NO_EVENT_TITLE');
		}

		return $title;
	}

	/**
	 * Get the status name.
	 *
	 * @return  string    The status name
	 *
	 * @since   3.5.0
	 */
	protected function getStatusName($status)
	{
		$status_array = JHtml::_('jgrid.publishedOptions');

		foreach ($status_array AS $key => $name)
		{
			if ($status == $name->value)
			{
				$status_name = $name->text;
			}
		}

		return JText::_($status_name);
	}

	/**
	 * Get the file type.
	 *
	 * @return  string    The file type
	 *
	 * @since   3.5.0
	 */
	public function getFileType()
	{
		return $this->getState('compressed') ? 'zip' : 'csv';
	}

	/**
	 * Get the mime type.
	 *
	 * @return  string    The mime type.
	 *
	 * @since   3.5.0
	 */
	public function getMimeType()
	{
		return $this->getState('compressed') ? 'application/zip' : 'text/csv';
	}

	/**
	 * Get the separator for values.
	 *
	 * @return  string    The separator.
	 *
	 * @since   3.5.9
	 */
	public function getSeparator()
	{
		return ($this->getState('separator') == 1) ? "," : ";";
	}

	/**
	 * Get the content
	 *
	 * @return  string    The content.
	 *
	 * @since   3.5.0
	 */
	public function getContent()
	{
		if (!isset($this->content))
		{
			$separator = $this->getSeparator();

			foreach ($this->getItems() as $item)
			{
				// Adds filled custom fields
				$customfields = icagendaCustomfields::getList($item->id, 1);

 				$header_cfs	= array();

				if ($customfields)
				{
					foreach ($customfields AS $customfield)
					{
						$header_cfs[]= $customfield->cf_title;
					}
				}
			}

			// Add BOM UTF-8 to csv content
			$this->content	= chr(239) . chr(187) . chr(191);

			$this->content .= '"';

			if ($this->getState('event_title'))
			{
				$this->content .= str_replace('"', '""', JText::_('COM_ICAGENDA_REGISTRATION_EVENTID')) . '"';
			}
			else
			{
				$this->content .= '#' . '"';
			}

			if ($this->getState('date'))
			{
				$this->content .= $separator . '"' . str_replace('"', '""', JText::_('COM_ICAGENDA_REGISTRATION_DATE')) . '"';
			}

			if ($this->getState('tickets'))
			{
				$this->content .= $separator . '"' . str_replace('"', '""', JText::_('COM_ICAGENDA_REGISTRATION_TICKETS')) . '"';
			}

			if ($this->getState('name'))
			{
				$this->content .= $separator . '"' . str_replace('"', '""', JText::_('IC_NAME')) . '"';
			}

			if ($this->getState('email'))
			{
				$this->content .= $separator . '"' . str_replace('"', '""', JText::_('COM_ICAGENDA_REGISTRATION_EMAIL')) . '"';
			}

			if ($this->getState('phone'))
			{
				$this->content .= $separator . '"' . str_replace('"', '""', JText::_('COM_ICAGENDA_REGISTRATION_PHONE')) . '"';
			}

			if ($this->getState('customfields'))
			{
				foreach ($header_cfs AS $header)
				{
					$this->content .= $separator . '"' . str_replace('"', '""', $header) . '"';
				}
			}

			if ($this->getState('notes'))
			{
				$this->content .= $separator . '"' . str_replace('"', '""', JText::_('COM_ICAGENDA_REGISTRATION_NOTES_DISPLAY_LABEL')) . '"';
			}

			if ($this->getState('status'))
			{
				$this->content .= $separator . '"' . str_replace('"', '""', JText::_('JSTATUS')) . '"';
			}

			$this->content .= "\n";

			// Data Rows
			$n = 0;

			foreach ($this->getItems() as $item)
			{
				// Adds filled custom fields
				$customfields = icagendaCustomfields::getList($item->id, 1);

 				$values_cfs	= array();

				if ($customfields)
				{
					foreach ($customfields AS $customfield)
					{
						$cf_value = isset($customfield->cf_value) ? $customfield->cf_value : JText::_('IC_NOT_SPECIFIED');
						$values_cfs[]= $cf_value;
					}
				}

				$this->content .= '"';

				if ($this->getState('event_title'))
				{
					$this->content .= str_replace('"', '""', $item->event) . '"';
				}
				else
				{
					$n = $n + 1;
					$this->content .= $n . '"';
				}

				if ($this->getState('date'))
				{
					$this->content .= $separator . '"' .
						str_replace('"', '""', ($item->period == 1 ? JText::_('COM_ICAGENDA_REGISTRATION_ALL_DATES') : $item->date)) . '"';
				}

				if ($this->getState('tickets'))
				{
					$this->content .= $separator . '"' . str_replace('"', '""', $item->people) . '"';
				}

				if ($this->getState('name'))
				{
					$this->content .= $separator . '"' . str_replace('"', '""', $item->name) . '"';
				}

				if ($this->getState('email'))
				{
					$this->content .= $separator . '"' . str_replace('"', '""', $item->email) . '"';
				}

				if ($this->getState('phone'))
				{
					$this->content .= $separator . '"' . str_replace('"', '""', $item->phone) . '"';
				}

				if ($this->getState('customfields'))
				{
					foreach ($values_cfs AS $value)
					{
						$this->content .= $separator . '"' . str_replace('"', '""', $value) . '"';
					}
				}

				if ($this->getState('notes'))
				{
					$this->content .= $separator . '"' . str_replace('"', '""', $item->notes) . '"';
				}

				if ($this->getState('status'))
				{
					$this->content .= $separator . '"' . str_replace('"', '""', $this->getStatusName($item->state)) . '"';
				}

				$this->content .= "\n";
			}

			if ($this->getState('compressed'))
			{
				$app = JFactory::getApplication('administrator');

				$this->content = str_replace(CHR(13).CHR(10), " ", $this->content);

				$files = array();
				$files['registrations'] = array();
				$files['registrations']['name'] = $this->getBasename() . '.csv';
				$files['registrations']['data'] = $this->content;
				$files['registrations']['time'] = time();
				$ziproot = $app->get('tmp_path') . '/' . uniqid('icagenda_registrations_') . '.zip';

				// Run the packager
				jimport('joomla.filesystem.folder');
				jimport('joomla.filesystem.file');
				$delete = JFolder::files($app->get('tmp_path') . '/', uniqid('icagenda_registrations_'), false, true);

				if (!empty($delete))
				{
					if (!JFile::delete($delete))
					{
						// JFile::delete throws an error
						$this->setError(JText::_('COM_ICAGENDA_EXPORT_ERR_ZIP_DELETE_FAILURE'));

						return false;
					}
				}

				if (!$packager = JArchive::getAdapter('zip'))
				{
					$this->setError(JText::_('COM_ICAGENDA_EXPORT_ERR_ZIP_ADAPTER_FAILURE'));

					return false;
				}
				elseif (!$packager->create($ziproot, $files))
				{
					$this->setError(JText::_('COM_ICAGENDA_EXPORT_ERR_ZIP_CREATE_FAILURE'));

					return false;
				}

				$this->content = file_get_contents($ziproot);
			}
		}

		return $this->content;
	}
}
icagenda.php000060400000003711152455705640007023 0ustar00<?php
/** 
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 * 
 * @since		1.0
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

/**
 * iCagenda Model
 */

class iCagendaModelicagenda extends JModelItem
{
	function getText()
	{
		$db =& JFactory::getDBO();
		$query = 'SELECT * FROM #__icagenda';
		$db->setQuery( $query );
		$value =& $db->loadObjectList();
		return $value;
	}
	/**
	 * @var object item
	 */
	protected $item;
 
	/**
	 * Method to auto-populate the model state.
	 *
	 * This method should only be called once per instantiation and is designed
	 * to be called on the first call to the getState() method unless the model
	 * configuration flag to ignore the request is set.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return	void
	 * @since	2.5
	 */
	protected function populateState() 
	{
		$app = JFactory::getApplication();
		// Get the message id
		$id = JRequest::getInt('id');
		$this->setState('message.id', $id);
 

		// Load the parameters.
		$params = $app->getParams();
		$this->setState('params', $params);
		parent::populateState();
	}
 
	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	2.5
	 */
	public function getTable($type = 'iCagenda', $prefix = 'iCagendaTable', $config = array()) 
	{
		return JTable::getInstance($type, $prefix, $config);
	}
 
}events.php000060400000025175152455705640006604 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version 	3.5.7 2015-07-14
 * @since       3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modellist');

/**
 * This models supports retrieving lists of events.
 */
class iCagendaModelEvents extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param	array		An optional associative array of configuration settings.
	 * @see		JController
	 * @since	3.4.0
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'e.id',
				'ordering', 'e.ordering',
				'state', 'e.state',
				'access', 'e.access', 'access_level',
				'approval', 'e.approval',
				'created', 'e.created',
				'title', 'e.title',
				'username', 'e.username',
				'email', 'e.email',
				'category', 'e.category',
				'cat_color', 'e.catcolor',
				'image', 'e.image',
				'file', 'e.file',
				'next', 'e.next',
				'place', 'e.place',
				'city', 'e.city',
				'country', 'e.country',
				'desc', 'e.desc',
				'language', 'e.language',
				'location', 'e.location',
				'category_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 * NOT IN USE CURRENTLY
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = JFactory::getApplication();

		// Load the filter search.
		$search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		// Load the filter state.
		$published = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string');
		$this->setState('filter.state', $published);

		// Load the filter access.
		$access = $app->getUserStateFromRequest($this->context.'.filter.access', 'filter_access', '', 'string');
		$this->setState('filter.access', $access);

		// Load the filter language.
		$language = $app->getUserStateFromRequest($this->context.'.filter.language', 'filter_language', '', 'string');
		$this->setState('filter.language', $language);

		// Filter (dropdown) category
		$category = $this->getUserStateFromRequest($this->context.'.filter.category', 'filter_category');
//		$category = $app->input->get('filter_category');
		$this->setState('filter.category', $category);

		// Filter (dropdown) year
		$year = $this->getUserStateFromRequest($this->context.'.filter.year', 'filter_year', '', 'string');
		$this->setState('filter.year', $year);

		// Filter categoryId
		$categoryId = $this->getUserStateFromRequest($this->context . '.filter.category_id', 'filter_category_id');
		$this->setState('filter.category_id', $categoryId);

		// Filter (dropdown) upcoming
		$upcoming = $this->getUserStateFromRequest($this->context.'.filter.upcoming', 'filter_upcoming', '', 'string');
		$this->setState('filter.upcoming', $upcoming);

		// Load the parameters.
		$params = $app->getParams();
		$this->setState('params', $params);

		// List state information.
		parent::populateState('e.id', 'desc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param	string		$id	A prefix for the store id.
	 * @return	string		A store id.
	 * @since	3.4.0
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.state');
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.language');
		$id .= ':' . $this->getState('filter.category');
		$id .= ':' . $this->getState('filter.year');
//		$id .= ':' . $this->getState('filter.category_id.include');
		$id .= ':' . serialize($this->getState('filter.category_id'));

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return	JDatabaseQuery
	 * @since	3.4.0
	 */
	protected function getListQuery()
	{
		// Get the current user for authorisation checks
		$user	= JFactory::getUser();

		// Create a new query object.
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'e.*'
			)
		);
		$query->from($db->qn('#__icagenda_events') . ' AS e');

		// Join over the language
		$query->select('l.title AS language_title')
			->join('LEFT', $db->quoteName('#__languages') . ' AS l ON l.lang_code = e.language');

		// Join over the users for the checked out user.
//		$query->select('uc.name AS editor');
//		$query->join('LEFT', '#__users AS uc ON uc.id=e.checked_out');

		// Join over the asset groups.
//		$query->select('ag.title AS access_level')
//			->join('LEFT', '#__viewlevels AS ag ON ag.id = e.access');

		// Join the category
		$query->select('c.id AS cat_id, c.title AS cat_title, c.color AS cat_color, c.desc AS cat_desc,
						c.title AS category, c.color AS catcolor');
		$query->join('LEFT', '#__icagenda_category AS c ON c.id = e.catid');
		$query->where('c.state = 1');

		// Features - extract the number of displayable icons per event
		$query->select('feat.count AS features');
		$sub_query = $db->getQuery(true);
		$sub_query->select('fx.event_id, COUNT(*) AS count');
		$sub_query->from('`#__icagenda_feature_xref` AS fx');
		$sub_query->innerJoin("`#__icagenda_feature` AS f ON fx.feature_id=f.id AND f.state=1 AND f.icon<>'-1'");
		$sub_query->group('fx.event_id');
		$query->leftJoin('(' . (string) $sub_query . ') AS feat ON e.id=feat.event_id');

		// Join Total of registrations
		$query->select('r.count AS registered');
		$sub_query = $db->getQuery(true);
		$sub_query->select('r.state, r.date, r.eventid, sum(r.people) AS count');
		$sub_query->from('`#__icagenda_registration` AS r');
		$sub_query->where('r.state > 0');
		$sub_query->group('r.date, r.eventid');
		$query->leftJoin('(' . (string) $sub_query . ') AS r ON ((e.next = r.date OR r.date = "") AND e.id = r.eventid)');

		// Join over the users for the author.
//		$query->select('ua.name AS author_name, ua.username AS author_username')
//			->join('LEFT', '#__users AS ua ON ua.id = e.created_by');

		// Filter by published state
		$published = $this->getState('filter.state');

		if (is_numeric($published))
		{
			$query->where('e.state = '.(int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(e.state IN (0, 1))');
		}

		$userGroups	= $user->groups;
		$groupid	= JComponentHelper::getParams('com_icagenda')->get('approvalGroups', array("8"));
		$groupid	= is_array($groupid) ? $groupid : array($groupid);

		// Test if user login have Approval Rights
		if ( ! array_intersect($userGroups, $groupid)
			&& ! in_array('8', $userGroups))
		{
			$query->where('e.approval <> 1');
		}
		else
		{
			$query->where('e.approval < 2');
		}

		// Filter by access level.
		$access = $this->getState('filter.access');

		if ( ! empty($access)
			&& ! in_array('8', $userGroups))
		{
			$access_levels = implode(',', $user->getAuthorisedViewLevels());

			$query->where('e.access IN (' . $access_levels . ')');
//				->where('c.access IN (' . $access_levels . ')'); // To be added later, when access integrated to category
		}

		// Filter by language
		if ($this->getState('filter.language'))
		{
			$query->where('e.language in (' . $db->q(JFactory::getLanguage()->getTag()) . ',' . $db->q('*') . ')');
		}

		// Filter by search in title
//		$search = $this->getState('filter.search');

//		if (!empty($search))
//		{
//			if (stripos($search, 'id:') === 0)
//			{
//				$query->where('e.id = '.(int) substr($search, 3));
//			}
//			else
//			{
//				$search = $db->Quote('%'.$db->escape($search, true).'%');
//				$query->where('( e.title LIKE '.$search.' OR e.username LIKE '.$search.' OR e.id LIKE '.$search.' OR e.email LIKE '.$search.' OR e.file LIKE '.$search.' OR e.place LIKE '.$search.' OR e.city LIKE '.$search.' OR e.country LIKE '.$search.' OR e.desc LIKE '.$search.' OR c.title LIKE '.$search.')');
//			}
//		}

		// Filter by categories.
		$categoryId = $this->getState('filter.category_id');

		if (is_numeric($categoryId) && !empty($categoryId))
		{
			$query->where('e.catid = ' . $categoryId . '');
		}
		elseif (is_array($categoryId) && !empty($categoryId) && !in_array('0', $categoryId))
		{
			JArrayHelper::toInteger($categoryId);
			$categoryId = implode(',', $categoryId);
			$query->where('e.catid IN (' . $categoryId . ')');
		}

		// Filter by Dates
		$dates_filter = $this->getState('filter.upcoming', '0');

		// Get today date and datetime based on Joomla Config Timezone.
		$datetime_today	= JHtml::date('now', 'Y-m-d H:i:s');
		$date_today		= JHtml::date('now', 'Y-m-d');

		$all_dates_with_id	= icagendaEventsData::getAllDates($dates_filter, '2', $this->state->get('list.direction'), 'no');

		$dpp_array = $dpp_dates = array();

		foreach ($all_dates_with_id AS $dpp)
		{
			$dpp_alldates_array	= explode('_', $dpp);
			$dpp_date			= $dpp_alldates_array['0'];
			$dpp_id				= $dpp_alldates_array['1'];
			$dpp_dates[]		= $dpp_date;
			$dpp_array[]		= $dpp_id;
		}

		$list_id = implode(', ', $dpp_array);

		if (count($dpp_array))
		{
			$query->where('e.id IN (' . $list_id . ')');
		}
		else
		{
			return false;
		}

		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering');
		$orderDirn	= $this->state->get('list.direction');

		if ($orderCol && $orderDirn)
		{
			$query->order($db->escape($orderCol.' '.$orderDirn));
		}

		return $query;
	}

	/**
	 * Method to get an array of data items.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   12.2
	 */
	public function getItems()
	{
		if ($items = parent::getItems())
		{
			//Do any procesing on fields here if needed
//			foreach ($items AS $item)
//			{
//				$item->loadEventCustomFields	= icagendaEventData::loadEventCustomFields($item->id);
//				$item->registeredUsers			= icagendaRegistrationParticipants::registeredUsers($item);
//			}
		}

		return $items;
	}
}
customfields.php000060400000013062152455705640007771 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.4.0 2014-07-16
 * @since		3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modellist');

/**
 * Methods supporting a list of iCagenda custom fields.
 */
class iCagendaModelcustomfields extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param	array		An optional associative array of configuration settings.
	 * @see		JController
	 * @since	3.4.0
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'cf.id',
				'ordering', 'cf.ordering',
				'state', 'cf.state',
				'title', 'cf.title',
				'slug', 'cf.slug',
				'parent_form', 'cf.parent_form',
				'type', 'cf.type',
				'required', 'cf.required',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	3.4.0
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = JFactory::getApplication('administrator');

		// Load the filter state.
		$search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$published = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string');
		$this->setState('filter.state', $published);

		// Filter (dropdown) parent form
		$parent_form = $this->getUserStateFromRequest($this->context.'.filter.parent_form', 'filter_parent_form', '', 'string');
		$this->setState('filter.parent_form', $parent_form);

		// Filter (dropdown) field type
		$type = $this->getUserStateFromRequest($this->context.'.filter.type', 'filter_type', '', 'string');
		$this->setState('filter.type', $type);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_icagenda');
		$this->setState('params', $params);

		// List state information.
		parent::populateState('cf.title', 'asc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param	string		$id	A prefix for the store id.
	 * @return	string		A store id.
	 * @since	3.4.0
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id.= ':' . $this->getState('filter.search');
		$id.= ':' . $this->getState('filter.state');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return	JDatabaseQuery
	 * @since	3.4.0
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'cf.*'
			)
		);
		$query->from('`#__icagenda_customfields` AS cf');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor');
		$query->join('LEFT', '#__users AS uc ON uc.id=cf.checked_out');

		// Filter by published state
		$published = $this->getState('filter.state');

		if (is_numeric($published))
		{
			$query->where($db->qn('cf.state') . ' = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where($db->qn('cf.state') . ' IN (0, 1)');
		}

		// Filter by Parent Form
		$parent_form = $db->escape($this->getState('filter.parent_form'));

		if (!empty($parent_form))
		{
			$query->where($db->qn('cf.parent_form') . ' = ' . (int) $parent_form);
		}

		// Filter by Field Type
		$type = $db->escape($this->getState('filter.type'));

		if (!empty($type))
		{
			$query->where($db->qn('cf.type') . ' = ' . (string) $db->q($type));
		}

		// Search Filters
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->qn('cf.id') . ' = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->Quote('%'.$db->escape($search, true).'%');
				$query->where('( cf.title LIKE '.$search.'  OR  cf.slug LIKE '.$search.'  OR  cf.type LIKE '.$search.' )');
			}
		}

		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering');
		$orderDirn	= $this->state->get('list.direction');

		if ($orderCol && $orderDirn)
		{
			$query->order($db->escape($orderCol.' '.$orderDirn));
		}

		return $query;
	}

	/**
	 * Gets a list of Parent Forms.
	 *
	 * @since	3.4.0
	 */
	function getParentForm()
	{
		$list['1'] = JText::_('COM_ICAGENDA_CUSTOMFIELD_PARENT_REGISTRATION_FORM');
		$list['2'] = JText::_('COM_ICAGENDA_CUSTOMFIELD_PARENT_EVENT_EDIT');

		return $list;
	}

	/**
	 * Gets a list of Field Types.
	 *
	 * @since	3.4.0
	 */
	function getFieldTypes()
	{
		$type['text'] = JText::_('COM_ICAGENDA_CUSTOMFIELD_TYPE_TEXT');
		$type['list'] = JText::_('COM_ICAGENDA_CUSTOMFIELD_TYPE_LIST');
		$type['radio'] = JText::_('COM_ICAGENDA_CUSTOMFIELD_TYPE_RADIO');

		return $type;
	}
}
mail.php000060400000016364152455705640006222 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.9 2015-07-30
 * @since       2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modeladmin');
jimport('joomla.mail.mail');


/**
 * iCagenda model.
 */
class iCagendaModelMail extends JModelAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	1.6
	 */
	protected $text_prefix = 'COM_ICAGENDA';

	/**
	 * Method to get the row form.
	 *
	 * @param   array    $data      An optional array of data for the form to interogate.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm	A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_icagenda.mail', 'mail', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		if (version_compare(JVERSION, '3.0', 'lt'))
		{
			$data = JFactory::getApplication()->getUserState('com_icagenda.display.mail.data', array());

			if (empty($data))
			{
//				$data = $this->getItem();
				$data = JFactory::getApplication()->getUserState('com_icagenda.mail.data', array());
			}
		}
		else
		{
			$data = JFactory::getApplication()->getUserState('com_icagenda.display.mail.data', array());

			if (empty($data))
			{
				$data = JFactory::getApplication()->getUserState('com_icagenda.mail.data', array());
			}

			$this->preprocessData('com_icagenda.mail', $data);
		}

		return $data;
	}

	/**
	 * Method to preprocess the form
	 *
	 * @param   JForm   $form   A form object.
	 * @param   mixed   $data   The data expected for the form.
	 * @param   string  $group  The name of the plugin group to import (defaults to "content").
	 *
	 * @return  void
	 *
	 * @since   1.6
	 * @throws  Exception if there is an error loading the form.
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'user')
	{
		parent::preprocessForm($form, $data, $group);
	}

	/**
	 * Send the email
	 *
	 * @return  boolean
	 */
	public function send()
	{
		$app    = JFactory::getApplication();
		$data   = $app->input->post->get('jform', array(), 'array');
		$user   = JFactory::getUser();
		$access = new JAccess;

		// Set Form Data to Session
		$session = JFactory::getSession();
		$session->set('ic_newsletter', $data);

		$mailer = JFactory::getMailer();
		$config = JFactory::getConfig();

		$send	= '';

		$sender = array(
		    $app->getCfg( 'mailfrom' ),
		    $app->getCfg( 'fromname' )
		    );

		$mailer->setSender($sender);

//		$list		= array_key_exists('list', $data) ? $data['list'] : ''; // DEPRECATED
		$eventid	= array_key_exists('eventid', $data) ? $data['eventid'] : '';
		$date		= array_key_exists('date', $data) ? $data['date'] : '';

		$db     = $this->getDbo();
		$query	= $db->getQuery(true);
		$query->select('r.email, r.eventid, r.state, r.date, r.people')
			->from('`#__icagenda_registration` AS r');
		$query->where('r.state = 1');
		$query->where('r.email <> ""');
		$query->where('r.eventid = ' . (int) $eventid);

		if ($date != 'all')
		{
			if (iCDate::isDate($date))
			{
				$query->where('r.date = ' . $db->q($date));
			}
			elseif ($date == 1)
			{
				$query->where('r.period = 1');
			}
			elseif ($date)
			{
				// Fix for old date saving data
				$query->where('r.date = ' . $db->q($date));
			}
			else
			{
				$query->where('r.period = 0');
			}
		}

		$db->setQuery($query);

		$result	= $db->loadObjectList();

		$list	= '';
		$people	= 0;

		foreach ($result as $v)
		{
			$list.= $v->email . ', ';
			$people = ($people + $v->people);
		}

		$subject	= array_key_exists('subject', $data) ? $data['subject'] : '';
		$messageget	= array_key_exists('message', $data) ? $data['message'] : '';

		$list_emails	= explode(', ', $list);

		// Remove dupplicated email addresses
		$recipient			= array_unique($list_emails);
		$dupplicated_emails	= count($list_emails) - count($recipient);

		$obj		= $subject;
		$message	= $messageget;

		$recipient	= array_filter($recipient);
//		$mailer->addRecipient($recipient);
//		$mailer->addRecipient($sender);
		$mailer->addBCC($recipient);

		$content	= stripcslashes($message);
		$body		= str_replace('src="images/', 'src="' . JURI::root() . '/images/', $content);

//		$mailer->setSender(array( $mailfrom, $fromname ));
		$mailer->setSubject($obj);
		$mailer->isHTML(true);
		$mailer->Encoding = 'base64';
		$mailer->setBody($body);

		if ($obj && $body && $eventid && ($date || $date == '0'))
		{
			$send = $mailer->Send();
		}

		if ($send !== true)
		{
		    $app->enqueueMessage(JText::_('COM_ICAGENDA_NEWSLETTER_ERROR_ALERT'), 'error');

		    if ( ! $obj)
		    {
		    	$app->enqueueMessage('- ' . JText::_('COM_ICAGENDA_NEWSLETTER_NO_OBJ_ALERT'), 'error');
		    }
		    if ( ! $body)
		    {
		    	$app->enqueueMessage('- ' . JText::_('COM_ICAGENDA_NEWSLETTER_NO_BODY_ALERT'), 'error');
		    }
		    if ( ! $eventid && ( ! $date && $date != '0'))
		    {
		    	$app->enqueueMessage('- ' . JText::_('COM_ICAGENDA_NEWSLETTER_NO_EVENT_SELECTED'), 'error');
		    }
		    elseif ( $eventid && ( ! $date && $date != '0'))
		    {
		    	$app->enqueueMessage('- ' . JText::_('COM_ICAGENDA_NEWSLETTER_NO_DATE_SELECTED'), 'error');
		    }

		    return false;
		}
		else
		{
		    $app->enqueueMessage('<h2>' . JText::_('COM_ICAGENDA_NEWSLETTER_SUCCESS') . '</h2>', 'message');

			$app->enqueueMessage($this->listSend($recipient, 0, $people), 'message');

			if ($dupplicated_emails)
			{
				$app->enqueueMessage('<i>' . JText::sprintf('COM_ICAGENDA_NEWSLETTER_NB_EMAIL_NOT_SEND', $dupplicated_emails) . '</i>', 'message');
			}

//			$app->setUserState('com_icagenda.mail.data', null);
//			echo '<pre>'.print_r($recipient, true).'</pre>';

		    return true;
		}
	}

	public function listSend($recipient, $level = 0, $people = null)
	{
		$number		= 0;
		$list_send	= '';

		foreach($recipient AS $key => $value)
		{
			if (is_array($value) | is_object($value))
			{
				parent::listArray($value, $level+=1);
			}
			else
			{
//				$number = ($key + 1);
				$number = ($number + 1);

				$list_send.= str_repeat("&nbsp;", $level*3);
				$list_send.= $number . " : " . $value . "<br>";
			}
		}

//		$list_send.= '<div>&nbsp;</div>';
		$list_send.= '<h4>' . JText::_('COM_ICAGENDA_NEWSLETTER_NB_EMAIL_SEND').' = ' . $number . '';
		$list_send.= '<small> (' . JText::_('COM_ICAGENDA_REGISTRATION_TICKETS').': ' . $people . ')</small></h4>';

		return $list_send;
	}
}
customfield.php000060400000007401152455705640007606 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.4.0 2014-06-13
 * @since		3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modeladmin');


/**
 * iCagenda model.
 */
class iCagendaModelCustomfield extends JModelAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	3.4.0
	 */
	protected $text_prefix = 'COM_ICAGENDA';

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	3.4.0
	 */
	public function getTable($type = 'Customfield', $prefix = 'iCagendaTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		An optional array of data for the form to interogate.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	JForm	A JForm object on success, false on failure
	 * @since	3.4.0
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_icagenda.customfield', 'customfield',
								array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	3.4.0
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_icagenda.edit.customfield.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param	integer	The id of the primary key.
	 *
	 * @return	mixed	Object on success, false on failure.
	 * @since	3.4.0
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			//Do any procesing on fields here if needed
		}

		return $item;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @since	3.4.0
	 */
	protected function prepareTable( $table )
	{
		$app = JFactory::getApplication();

		$date = JFactory::getDate();
		$user = JFactory::getUser();

		if (empty($table->id))
		{
			// Set the values
			$table->created = $date->toSql();

			// Set ordering to the last item if not set
			if (empty($table->ordering))
			{
				$db = JFactory::getDbo();
				$query = $db->getQuery(true)
					->select('MAX(ordering)')
					->from($db->quoteName('#__icagenda_customfields'));
				$db->setQuery($query);
				$max = $db->loadResult();

				$table->ordering = $max + 1;
			}
		}
		else
		{
			// Set the values
			$table->modified = $date->toSql();
			$table->modified_by = $user->get('id');
		}

		// Alter the title for save as copy
		if ($app->input->get('task') == 'save2copy')
		{
			$table->title = iCString::increment($table->title);
			$table->alias = iCString::increment($table->alias, 'dash');
			$table->slug = iCString::increment($table->slug, 'underscore');
			$table->state = '0';
		}
	}
}
features.php000060400000010142152455705640007102 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      doorknob & Cyril Rezé
 * @link        http://www.joomlic.com
 *
 * @version     3.4.0 2014-07-02
 * @since       3.4.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modellist');

/**
 * Methods supporting a list of iCagenda records.
 */
class iCagendaModelfeatures extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param	array		An optional associative array of configuration settings.
	 * @see		JController
	 * @since	3.4.0
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'ordering', 'a.ordering',
				'state', 'a.state',
				'desc', 'a.desc',
				'icon', 'a.icon',
				'icon_alt', 'a.icon_alt',
				'show_filter', 'a.show_filter',
			);
		}

		parent::__construct($config);
	}


	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	3.4.0
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = JFactory::getApplication('administrator');

		// Load the filter state.
		$search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$published = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string');
		$this->setState('filter.state', $published);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_icagenda');
		$this->setState('params', $params);

		// List state information.
		parent::populateState('a.title', 'asc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param	string		$id	A prefix for the store id.
	 * @return	string		A store id.
	 * @since	3.4.0
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id.= ':' . $this->getState('filter.search');
		$id.= ':' . $this->getState('filter.state');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return	JDatabaseQuery
	 * @since	3.4.0
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db		= $this->getDbo();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.*'
			)
		);
		$query->from('#__icagenda_feature AS a');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor');
		$query->leftJoin('#__users AS uc ON uc.id=a.checked_out');

		// Filter by published state
		$published = $this->getState('filter.state');
		if (is_numeric($published))
		{
			$query->where('a.state=' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.state IN (0, 1))');
		}

		// Filter by search in title
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->Quote('%'.$db->escape($search, true).'%');
				$query->where("(a.title LIKE $search OR a.desc LIKE $search)");
			}
		}

		// Add the list ordering clause.
		$orderCol	= $this->state->get('list.ordering');
		$orderDirn	= $this->state->get('list.direction');

		if ($orderCol && $orderDirn)
		{
			$query->order($db->escape("$orderCol $orderDirn"));
		}

		return $query;
	}
}
info.php000060400000001240152455705640006216 0ustar00<?php
/** 
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 * 
 * @since		1.2.6
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.modellist');

/**
 * Methods supporting a list of iCagenda records.
 */
class iCagendaModelinfo extends JModelList
{
	

}
fields.php000060400000001242152455705640006533 0ustar00<?php
/** 
 *	iCagenda
 *----------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright	Copyright (C) 2012 JOOMLIC - All rights reserved.
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Jooml!C - http://www.joomlic.com
 * 
 * @since		1.2.6
 *----------------------------------------------------------------------------
*/

// No direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.modellist');

/**
 * Methods supporting a list of iCagenda records.
 */
class iCagendaModelfields extends JModelList
{
	

}
event.php000060400000034177152455705640006423 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.12 2015-09-25
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modeladmin');


/**
 * iCagenda model.
 */
class iCagendaModelEvent extends JModelAdmin
{
	/**
	 * @var		string	The prefix to use with controller messages.
	 * @since	1.0
	 */
	protected $text_prefix = 'COM_ICAGENDA';

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 *
	 * @since   3.5.6
	 */
	protected function canDelete($record)
	{
		if ( ! empty($record->id))
		{
			if ($record->state != -2)
			{
				return false;
			}

			$user = JFactory::getUser();

			if ($user->authorise('core.delete'))
			{
				icagendaCustomfields::deleteData($record->id, 2);
				icagendaCustomfields::cleanData(2);

				return true;
			}
		}

		return false;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @param   JTable  $table  A JTable object.
	 *
	 * @return  void
	 *
	 * @since	1.0
	 */
	protected function prepareTable( $table )
	{
		$date = JFactory::getDate();
		$user = JFactory::getUser();

		$table->name = htmlspecialchars_decode($table->name, ENT_QUOTES);

		if (empty($table->id))
		{
			// Set the values
			$table->created = $date->toSql();

			// Set ordering to the last item if not set
			if (empty($table->ordering))
			{
				$db = JFactory::getDbo();
				$query = $db->getQuery(true)
					->select('MAX(ordering)')
					->from($db->quoteName('#__icagenda_events'));
				$db->setQuery($query);
				$max = $db->loadResult();

				$table->ordering = $max + 1;
			}
		}
		else
		{
			// Set the values
			$table->modified = $date->toSql();
			$table->modified_by = $user->get('id');
		}
	}

	/**
	 * Returns a Table object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable    A database object
	 *
	 * @since	1.0
	 */
	public function getTable($type = 'Event', $prefix = 'iCagendaTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer $pk The id of the primary key.
	 *
	 * @return  mixed   Object on success, false on failure.
	 *
	 * @since	1.0
	 */
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk))
		{
			// Do any procesing on fields here if needed
		}

		return $item;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed  A JForm object on success, false on failure
	 *
	 * @since	1.0
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_icagenda.event', 'event',
								array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since	1.0
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$app = JFactory::getApplication();
		$data_array = $app->getUserState('com_icagenda.edit.event.data', array());

		if (empty($data_array))
		{
			$data = $this->getItem();
		}
		else
		{
			$data = new JObject;
			$data->setProperties($data_array);
		}

		// If not array, creates array with week days data
		if ( ! is_array($data->weekdays))
		{
			$data->weekdays = explode(',', $data->weekdays);
		}

		// Retrieves data, to display selected week days
		$arrayWeekDays = $data->weekdays;

		foreach ($arrayWeekDays as $allTest)
		{
			if ($allTest == '')
			{
				$data->weekdays = '0,1,2,3,4,5,6';
			}
		}

		// Set displaytime default value
		if ( ! isset($data->displaytime))
		{
			$data->displaytime = JComponentHelper::getParams('com_icagenda')->get('displaytime', '1');
		}

		// Set Features
		$data->features = $this->getFeatures($data->id);

		// Convert features into an array so that the form control can be set
		if ( ! isset($data->features))
		{
			$data->features = array();
		}

		if ( ! is_array($data->features))
		{
			$data->features = explode(',', $data->features);
		}

		return $data;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since	3.4.0
	 */
	public function save($data)
	{
		$input	= JFactory::getApplication()->input;
		$date	= JFactory::getDate();
		$user	= JFactory::getUser();

		// Fix version before 3.4.0 to set a created date (will use last modified date if exists, or current date)
		if (empty($data['created']))
		{
			$data['created'] = ( ! empty($data['modified'])) ? $data['modified'] : $date->toSql();
		}

		// Alter the title for save as copy
		if ($input->get('task') == 'save2copy')
		{
			$origTable = clone $this->getTable();
			$origTable->load($input->getInt('id'));

			if ($data['title'] == $origTable->title)
			{
				list($title, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']);
				$data['title'] = $title;
				$data['alias'] = $alias;
			}
			else
			{
				if ($data['alias'] == $origTable->alias)
				{
					$data['alias'] = '';
				}
			}
			$data['state'] = 0;
		}

		// Automatic handling of alias for empty fields
		if (in_array($input->get('task'), array('apply', 'save', 'save2new')) && (int) $input->get('id') == 0)
		{
			if ($data['alias'] == null)
			{
				if (JFactory::getConfig()->get('unicodeslugs') == 1)
				{
					$data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['title']);
				}
				else
				{
					$data['alias'] = JFilterOutput::stringURLSafe($data['title']);
				}

				$table = JTable::getInstance('Event', 'iCagendaTable');

				if ($table->load(array('alias' => $data['alias'], 'catid' => $data['catid'])))
				{
					$msg = JText::_('COM_ICAGENDA_ALERT_EVENT_SAVE_WARNING');
				}

				list($title, $alias) = $this->generateNewTitle($data['catid'], $data['alias'], $data['title']);
				$data['alias'] = $alias;

				if (isset($msg))
				{
					JFactory::getApplication()->enqueueMessage($msg, 'warning');
				}
			}
		}

		// Generates Alias if empty
		if ($data['alias'] == null || empty($data['alias']))
		{
			$data['alias'] = JFilterOutput::stringURLSafe($data['title']);

			if ($data['alias'] == null || empty($data['alias']))
			{
				if (JFactory::getConfig()->get('unicodeslugs') == 1)
				{
					$data['alias'] = JFilterOutput::stringURLUnicodeSlug($data['title']);
				}
				else
				{
					$data['alias'] = JFilterOutput::stringURLSafe($data['created']);
				}
			}
		}

		// Set File Uploaded
		if ( ! isset($data['file']))
		{
			$file = JRequest::getVar('jform', null, 'files', 'array');
			$fileUrl = $this->upload($file);
			$data['file'] = $fileUrl;
		}

		// Set Creator infos
		$userId	= $user->get('id');
		$userName = $user->get('name');

		if (empty($data['created_by']))
		{
			$data['created_by'] = (int) $userId;
		}

		$data['username'] = $userName;

		// Set Params
		if (isset($data['params']) && is_array($data['params']))
		{
			// Convert the params field to a string.
			$parameter = new JRegistry;
			$parameter->loadArray($data['params']);
			$data['params'] = (string)$parameter;
		}

		// Get Event ID from the result back to the Table after saving.
		$table = $this->getTable();

		if ($table->save($data) === true)
		{
			$data['id'] = $table->id;
		}
		else
		{
			$data['id'] = null;
		}

		if (parent::save($data))
		{
			// Save Features to database
			$this->maintainFeatures($data);

			// Save Custom Fields to database
			if (isset($data['custom_fields']) && is_array($data['custom_fields']))
			{
				icagendaCustomfields::saveToData($data['custom_fields'], $data['id'], 2);
			}

			return true;
		}

		return false;
	}

	/**
	 * Upload
	 *
	 * @since	3.5.3
	 */
	function upload($file)
	{
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');

		$filename = JFile::makeSafe($file['name']['file']);

		// Get media path
		$params_media	= JComponentHelper::getParams('com_media');
		$image_path		= $params_media->get('image_path', 'images');

		// Paths to thumbs folder
		$thumbsPath		= $image_path . '/icagenda/thumbs';

		if ($filename != '')
		{
			$src = $file['tmp_name']['file'];
			$dest =  JPATH_SITE . '/' . $image_path . '/icagenda/files/' . $filename;

			if ( ! is_dir($dest))
			{
				mkdir($intDir, 0755);
			}

			if (JFile::upload($src, $dest, false))
			{
				echo 'upload';
				return $image_path . '/icagenda/files/' . $filename;
			}

			return $image_path . '/icagenda/files/' . $filename;
		}
	}

	/**
	 * Maintain features to data
	 *
	 * @since	3.4.0
	 */
	protected function maintainFeatures($data)
	{
		// Get the list of feature ids to be linked to the event
		$features = isset($data['features']) && is_array($data['features']) ? implode(',', $data['features']) : '';

		$db = JFactory::getDbo();

		// Write any new feature records to the icagenda_feature_xref table
		if ( ! empty($features))
		{
			// Get a list of the valid features already present for this event
			$query = $db->getQuery(true);

			$query->select('feature_id')
				->from($db->qn('#__icagenda_feature_xref'));

			$query->where('event_id = ' . (int) $data['id']);
			$query->where('feature_id IN (' . $features . ')');

			$db->setQuery($query);

			$existing_features = $db->loadColumn(0);

			// Identify the insert list
			if (empty($existing_features))
			{
				$new_features = $data['features'];
			}
			else
			{
				$new_features = array();

				foreach ($data['features'] as $feature)
				{
					if ( ! in_array($feature, $existing_features))
					{
						$new_features[] = $feature;
					}
				}
			}
			// Write the needed xref records
			if ( ! empty($new_features))
			{
				$xref = new JObject;
				$xref->set('event_id', $data['id']);

				foreach ($new_features as $feature)
				{
					$xref->set('feature_id', $feature);
					$db->insertObject('#__icagenda_feature_xref', $xref);
					$db->setQuery($query);

					if ( ! $db->execute())
					{
						return false;
					}
				}
			}
		}

		// Delete any unwanted feature records from the icagenda_feature_xref table
		$query = $db->getQuery(true);
		$query->delete($db->qn('#__icagenda_feature_xref'));
		$query->where('event_id = ' . (int) $data['id']);

		if ( ! empty($features))
		{
			// Delete only unwanted features
			$query->where('feature_id NOT IN (' . $features . ')');
		}

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

		if ( ! $db->execute())
		{
			return false;
		}

		return true;
	}

	/**
	 * Extracts the list of Feature IDs linked to the event and returns an array
	 *
	 * @param	integer  $event_id
	 *
	 * @return	array/integer  Set of Feature IDs
	 *
	 * @since	3.5.3
	 */
	protected function getFeatures($event_id)
	{
		// Write any new feature records to the icagenda_feature_xref table
		if (empty($event_id))
		{
			return '';
		}
		else
		{
			$db = JFactory::getDbo();

			// Get a comma separated list of the ids of features present for this event
			// Note: Direct extraction of a comma separated list is avoided because each db type uses proprietary syntax
			$query = $db->getQuery(true);
			$query->select('fx.feature_id')
				->from($db->qn('#__icagenda_events', 'e'))
				->innerJoin('#__icagenda_feature_xref AS fx ON e.id=fx.event_id')
				->innerJoin('#__icagenda_feature AS f ON fx.feature_id=f.id AND f.state=1');
			$query->where('e.id = ' . (int) $event_id);
			$db->setQuery($query);
			$features = $db->loadColumn(0);

			// Return a comma separated list
			return implode(',', $features);
		}
	}

	/**
	 * Approve Function.
	 *
	 * @since   3.2.0
	 */
	function approve($cid, $publish)
	{
		if (count($cid))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = 'UPDATE #__icagenda_events'
					. ' SET approval = '.(int) $publish
					. ' WHERE id IN ( '.$cids.' )';
					$this->_db->setQuery( $query );

			if ( ! $this->_db->query())
			{
				$this->setError($this->_db->getErrorMsg());

				return false;
			}
		}

		return true;
	}

	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission set in the component.
	 *
	 * @since   3.6.0
	 */
//	protected function canDelete($record)
//	{
//		if ( ! empty($record->id))
//		{
//			if ($record->state != -2)
//			{
//				return false;
//			}

//			$user = JFactory::getUser();

//			return $user->authorise('core.delete', 'com_icagenda.event.' . (int) $record->id);
//		}

//		return false;
//	}

	/**
	 * Method to test whether a record can have its state edited.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission set in the component.
	 *
	 * @since   3.6.0
	 */
//	protected function canEditState($record)
//	{
//		$user = JFactory::getUser();

		// Check for existing event.
//		if (!empty($record->id))
//		{
//			return $user->authorise('core.edit.state', 'com_icagenda.event.' . (int) $record->id);
//		}
		// New event, so check against the category.
//		elseif (!empty($record->catid))
//		{
//			return $user->authorise('core.edit.state', 'com_icagenda.event.' . (int) $record->catid);
//		}
		// Default to component settings if neither event nor category known.
//		else
//		{
//			return parent::canEditState('com_icagenda');
//		}
//	}
}
forms/filter_items.xml000060400000007157152455712440011121 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_menus/models/fields" />
		<field
			name="menutype"
			type="menu"
			label="COM_MENUS_SELECT_MENU_FILTER"
			accesstype="manage"
			clientid=""
			showAll="false"
			filtermode="selector"
			onchange="this.form.submit();"
			>
			<option value="">COM_MENUS_SELECT_MENU</option>
		</field>
		<fields name="filter">
			<field
				name="search"
				type="text"
				inputmode="search"
				label="COM_MENUS_ITEMS_SEARCH_FILTER_LABEL"
				description="COM_MENUS_ITEMS_SEARCH_FILTER"
				hint="JSEARCH_FILTER"
			/>
			<field
				name="published"
				type="status"
				label="COM_MENUS_FILTER_PUBLISHED"
				description="COM_MENUS_FILTER_PUBLISHED_DESC"
				filter="*,0,1,-2"
				onchange="this.form.submit();"
				>
				<option value="">JOPTION_SELECT_PUBLISHED</option>
			</field>
			<field
				name="access"
				type="accesslevel"
				label="JOPTION_FILTER_ACCESS"
				description="JOPTION_FILTER_ACCESS_DESC"
				onchange="this.form.submit();"
				>
				<option value="">JOPTION_SELECT_ACCESS</option>
			</field>
			<field
				name="language"
				type="contentlanguage"
				label="JOPTION_FILTER_LANGUAGE"
				description="JOPTION_FILTER_LANGUAGE_DESC"
				onchange="this.form.submit();"
				>
				<option value="">JOPTION_SELECT_LANGUAGE</option>
				<option value="*">JALL</option>
			</field>
			<field
				name="level"
				type="integer"
				label="JOPTION_FILTER_LEVEL"
				description="JOPTION_FILTER_LEVEL_DESC"
				first="1"
				last="10"
				step="1"
				languages="*"
				onchange="this.form.submit();"
				>
				<option value="">JOPTION_SELECT_MAX_LEVELS</option>
			</field>
			<field
				name="parent_id"
				type="MenuItemByType"
				label="COM_MENUS_FILTER_PARENT_MENU_ITEM_LABEL"
				onchange="this.form.submit();"
				>
				<option value="">COM_MENUS_FILTER_SELECT_PARENT_MENU_ITEM</option>
			</field>
		</fields>
		<fields name="list">
			<field
				name="fullordering"
				type="list"
				label="JGLOBAL_SORT_BY"
				description="JGLOBAL_SORT_BY"
				statuses="*,0,1,2,-2"
				onchange="this.form.submit();"
				default="a.lft ASC"
				validate="options"
				>
				<option value="">JGLOBAL_SORT_BY</option>
				<option value="a.lft ASC">JGRID_HEADING_ORDERING_ASC</option>
				<option value="a.lft DESC">JGRID_HEADING_ORDERING_DESC</option>
				<option value="a.published ASC">JSTATUS_ASC</option>
				<option value="a.published DESC">JSTATUS_DESC</option>
				<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
				<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
				<option value="menutype_title ASC">COM_MENUS_HEADING_MENU_ASC</option>
				<option value="menutype_title DESC">COM_MENUS_HEADING_MENU_DESC</option>
				<option value="a.home ASC">COM_MENUS_HEADING_HOME_ASC</option>
				<option value="a.home DESC">COM_MENUS_HEADING_HOME_DESC</option>
				<option value="a.access ASC">JGRID_HEADING_ACCESS_ASC</option>
				<option value="a.access DESC">JGRID_HEADING_ACCESS_DESC</option>
				<option value="association ASC" requires="associations">JASSOCIATIONS_ASC</option>
				<option value="association DESC" requires="associations">JASSOCIATIONS_DESC</option>
				<option value="language ASC">JGRID_HEADING_LANGUAGE_ASC</option>
				<option value="language DESC">JGRID_HEADING_LANGUAGE_DESC</option>
				<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
				<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
			</field>
			<field
				name="limit"
				type="limitbox"
				label="COM_MENUS_LIST_LIMIT"
				description="COM_MENUS_LIST_LIMIT_DESC"
				class="input-mini"
				default="25"
				onchange="this.form.submit();"
			/>
		</fields>
</form>
forms/filter_fields.xml000060400000005403152456020240011225 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset name="group"
		addfieldpath="/administrator/components/com_fields/models/fields">
		<field
			name="context"
			type="fieldcontexts"
			onchange="this.form.submit();"
		/>
	</fieldset>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label=""
			hint="JSEARCH_FILTER"
			class="js-stools-search-string"
		/>

		<field
			name="state"
			type="status"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="group_id"
			type="fieldgroups"
			state="0,1,2"
			onchange="this.form.submit();"
			>
			<option value="">COM_FIELDS_VIEW_FIELDS_SELECT_GROUP</option>
		</field>

		<field
			name="assigned_cat_ids"
			type="category"
			onchange="this.form.submit();"
			>
			<option value="">COM_FIELDS_VIEW_FIELDS_SELECT_CATEGORY</option>
		</field>

		<field
			name="access"
			type="accesslevel"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_ACCESS</option>
		</field>

		<field
			name="language"
			type="contentlanguage"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
		</field>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			statuses="*,0,1,2,-2"
			onchange="this.form.submit();"
			default="a.ordering ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.state ASC">JSTATUS_ASC</option>
			<option value="a.state DESC">JSTATUS_DESC</option>
			<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="a.type ASC">COM_FIELDS_VIEW_FIELDS_SORT_TYPE_ASC</option>
			<option value="a.type DESC">COM_FIELDS_VIEW_FIELDS_SORT_TYPE_DESC</option>
			<option value="g.title ASC">COM_FIELDS_VIEW_FIELDS_SORT_GROUP_ASC</option>
			<option value="g.title DESC">COM_FIELDS_VIEW_FIELDS_SORT_GROUP_DESC</option>
			<option value="a.access ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="a.access DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option value="a.language ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="a.language DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="COM_FIELDS_LIST_LIMIT"
			description="COM_FIELDS_LIST_LIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
cache.php000060400000014544152456043610006332 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_cache
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\Utilities\ArrayHelper;

/**
 * Cache Model
 *
 * @since  1.6
 */
class CacheModelCache extends JModelList
{
	/**
	 * An Array of CacheItems indexed by cache group ID
	 *
	 * @var Array
	 */
	protected $_data = array();

	/**
	 * Group total
	 *
	 * @var integer
	 */
	protected $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	protected $_pagination = null;

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   3.5
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'group',
				'count',
				'size',
				'client_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   Field for ordering.
	 * @param   string  $direction  Direction of ordering.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'group', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));

		// Special case for client id.
		$clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int');
		$clientId = (!in_array($clientId, array (0, 1))) ? 0 : $clientId;
		$this->setState('client_id', $clientId);

		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   3.5
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':' . $this->getState('client_id');
		$id	.= ':' . $this->getState('filter.search');

		return parent::getStoreId($id);
	}

	/**
	 * Method to get cache data
	 *
	 * @return array
	 */
	public function getData()
	{
		if (empty($this->_data))
		{
			try
			{
				$cache = $this->getCache();
				$data  = $cache->getAll();

				if ($data && count($data) > 0)
				{
					// Process filter by search term.
					if ($search = $this->getState('filter.search'))
					{
						foreach ($data as $key => $cacheItem)
						{
							if (stripos($cacheItem->group, $search) === false)
							{
								unset($data[$key]);
								continue;
							}
						}
					}

					// Process ordering.
					$listOrder = $this->getState('list.ordering', 'group');
					$listDirn  = $this->getState('list.direction', 'ASC');

					$this->_data = ArrayHelper::sortObjects($data, $listOrder, strtolower($listDirn) === 'desc' ? -1 : 1, true, true);

					// Process pagination.
					$limit = (int) $this->getState('list.limit', 25);

					if ($limit !== 0)
					{
						$start = (int) $this->getState('list.start', 0);

						return array_slice($this->_data, $start, $limit);
					}
				}
				else
				{
					$this->_data = array();
				}
			}
			catch (JCacheExceptionConnecting $exception)
			{
				$this->setError(JText::_('COM_CACHE_ERROR_CACHE_CONNECTION_FAILED'));
				$this->_data = array();
			}
			catch (JCacheExceptionUnsupported $exception)
			{
				$this->setError(JText::_('COM_CACHE_ERROR_CACHE_DRIVER_UNSUPPORTED'));
				$this->_data = array();
			}
		}

		return $this->_data;
	}

	/**
	 * Method to get cache instance.
	 *
	 * @return JCacheController
	 */
	public function getCache($clientId = null)
	{
		$conf = JFactory::getConfig();

		if (is_null($clientId))
		{
			$clientId = $this->getState('client_id');
		}

		$options = array(
			'defaultgroup' => '',
			'storage'      => $conf->get('cache_handler', ''),
			'caching'      => true,
			'cachebase'    => (int) $clientId === 1 ? JPATH_ADMINISTRATOR . '/cache' : $conf->get('cache_path', JPATH_SITE . '/cache')
		);

		return JCache::getInstance('', $options);
	}

	/**
	 * Method to get client data.
	 *
	 * @return array
	 *
	 * @deprecated  4.0  No replacement.
	 */
	public function getClient()
	{
		return JApplicationHelper::getClientInfo($this->getState('client_id', 0));
	}

	/**
	 * Get the number of current Cache Groups.
	 *
	 * @return  integer
	 */
	public function getTotal()
	{
		if (empty($this->_total))
		{
			$this->_total = count($this->getData());
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the cache.
	 *
	 * @return  JPagination
	 */
	public function getPagination()
	{
		if (empty($this->_pagination))
		{
			$this->_pagination = new JPagination($this->getTotal(), $this->getState('list.start'), $this->getState('list.limit'));
		}

		return $this->_pagination;
	}

	/**
	 * Clean out a cache group as named by param.
	 * If no param is passed clean all cache groups.
	 *
	 * @param   string  $group  Cache group name.
	 *
	 * @return  boolean  True on success, false otherwise
	 */
	public function clean($group = '')
	{
		try
		{
			$this->getCache()->clean($group);
		}
		catch (JCacheExceptionConnecting $exception)
		{
			return false;
		}
		catch (JCacheExceptionUnsupported $exception)
		{
			return false;
		}

		Factory::getApplication()->triggerEvent('onAfterPurge', array($group));

		return true;
	}

	/**
	 * Purge an array of cache groups.
	 *
	 * @param   array  $array  Array of cache group names.
	 *
	 * @return  array  Array with errors, if they exist.
	 */
	public function cleanlist($array)
	{
		$errors = array();

		foreach ($array as $group)
		{
			if (!$this->clean($group))
			{
				$errors[] = $group;
			}
		}

		return $errors;
	}

	/**
	 * Purge all cache items.
	 *
	 * @return  boolean  True if successful; false otherwise.
	 */
	public function purge()
	{
		try
		{
			JFactory::getCache('')->gc();
		}
		catch (JCacheExceptionConnecting $exception)
		{
			return false;
		}
		catch (JCacheExceptionUnsupported $exception)
		{
			return false;
		}

		Factory::getApplication()->triggerEvent('onAfterPurge', array());

		return true;
	}
}
forms/filter_cache.xml000060400000002630152456043610011027 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<field
		name="client_id"
		type="list"
		onchange="jQuery('#filter_search, select[id^=filter_], #list_fullordering').val('');this.form.submit();"
		filtermode="selector"
		>
		<option value="0">JSITE</option>
		<option value="1">JADMINISTRATOR</option>
	</field>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_CACHE_FILTER_SEARCH_LABEL"
			description="COM_CACHE_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
			noresults="JGLOBAL_NO_MATCHING_RESULTS"
		/>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="group ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="group ASC">COM_CACHE_HEADING_GROUP_ASC</option>
			<option value="group DESC">COM_CACHE_HEADING_GROUP_DESC</option>
			<option value="count ASC">COM_CACHE_HEADING_COUNT_ASC</option>
			<option value="count DESC">COM_CACHE_HEADING_COUNT_DESC</option>
			<option value="size ASC">COM_CACHE_HEADING_SIZE_ASC</option>
			<option value="size DESC">COM_CACHE_HEADING_SIZE_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
overrides.php000060400000014716152456067220007275 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_languages
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Languages Overrides Model
 *
 * @since  2.5
 */
class LanguagesModelOverrides extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   2.5
	 */
	public function __construct($config = array())
	{
		parent::__construct($config);

		$this->filter_fields = array('key', 'text');
	}

	/**
	 * Retrieves the overrides data
	 *
	 * @param   boolean  $all  True if all overrides shall be returned without considering pagination, defaults to false
	 *
	 * @return  array  Array of objects containing the overrides of the override.ini file
	 *
	 * @since   2.5
	 */
	public function getOverrides($all = false)
	{
		// Get a storage key.
		$store = $this->getStoreId();

		// Try to load the data from internal storage.
		if (!empty($this->cache[$store]))
		{
			return $this->cache[$store];
		}

		$client = strtoupper($this->getState('filter.client'));

		// Parse the override.ini file in order to get the keys and strings.
		$fileName = constant('JPATH_' . $client) . '/language/overrides/' . $this->getState('filter.language') . '.override.ini';
		$strings  = JLanguageHelper::parseIniFile($fileName);

		// Delete the override.ini file if empty.
		if (file_exists($fileName) && $strings === array())
		{
			JFile::delete($fileName);
		}

		// Filter the loaded strings according to the search box.
		$search = $this->getState('filter.search');

		if ($search != '')
		{
			$search = preg_quote($search, '~');
			$matchvals = preg_grep('~' . $search . '~i', $strings);
			$matchkeys = array_intersect_key($strings, array_flip(preg_grep('~' . $search . '~i',  array_keys($strings))));
			$strings = array_merge($matchvals, $matchkeys);
		}

		// Consider the ordering
		if ($this->getState('list.ordering') == 'text')
		{
			if (strtoupper($this->getState('list.direction')) == 'DESC')
			{
				arsort($strings);
			}
			else
			{
				asort($strings);
			}
		}
		else
		{
			if (strtoupper($this->getState('list.direction')) == 'DESC')
			{
				krsort($strings);
			}
			else
			{
				ksort($strings);
			}
		}

		// Consider the pagination.
		if (!$all && $this->getState('list.limit') && $this->getTotal() > $this->getState('list.limit'))
		{
			$strings = array_slice($strings, $this->getStart(), $this->getState('list.limit'), true);
		}

		// Add the items to the internal cache.
		$this->cache[$store] = $strings;

		return $this->cache[$store];
	}

	/**
	 * Method to get the total number of overrides.
	 *
	 * @return  integer  The total number of overrides.
	 *
	 * @since   2.5
	 */
	public function getTotal()
	{
		// Get a storage key.
		$store = $this->getStoreId('getTotal');

		// Try to load the data from internal storage
		if (!empty($this->cache[$store]))
		{
			return $this->cache[$store];
		}

		// Add the total to the internal cache.
		$this->cache[$store] = count($this->getOverrides(true));

		return $this->cache[$store];
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	protected function populateState($ordering = 'key', $direction = 'asc')
	{
		// We call populate state first so that we can then set the filter.client and filter.language properties in afterwards
		parent::populateState($ordering, $direction);

		$app = JFactory::getApplication();

		$language_client = $this->getUserStateFromRequest('com_languages.overrides.language_client', 'language_client', '', 'cmd');
		$client          = substr($language_client, -1);
		$language        = substr($language_client, 0, -1);

		// Sets the search filter.
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$this->setState('language_client', $language . $client);
		$this->setState('filter.client', $client ? 'administrator' : 'site');
		$this->setState('filter.language', $language);

		// Add the 'language_client' value to the session to display a message if none selected
		$app->setUserState('com_languages.overrides.language_client', $language . $client);

		// Add filters to the session because they won't be stored there by 'getUserStateFromRequest' if they aren't in the current request.
		$app->setUserState('com_languages.overrides.filter.client', $client);
		$app->setUserState('com_languages.overrides.filter.language', $language);
	}

	/**
	 * Method to delete one or more overrides.
	 *
	 * @param   array  $cids  Array of keys to delete.
	 *
	 * @return  integer  Number of successfully deleted overrides, boolean false if an error occurred.
	 *
	 * @since   2.5
	 */
	public function delete($cids)
	{
		// Check permissions first.
		if (!JFactory::getUser()->authorise('core.delete', 'com_languages'))
		{
			$this->setError(JText::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'));

			return false;
		}

		jimport('joomla.filesystem.file');

		$filterclient = JFactory::getApplication()->getUserState('com_languages.overrides.filter.client');
		$client = $filterclient == 0 ? 'SITE' : 'ADMINISTRATOR';

		// Parse the override.ini file in oder to get the keys and strings.
		$fileName = constant('JPATH_' . $client) . '/language/overrides/' . $this->getState('filter.language') . '.override.ini';
		$strings  = JLanguageHelper::parseIniFile($fileName);

		// Unset strings that shall be deleted
		foreach ($cids as $key)
		{
			if (isset($strings[$key]))
			{
				unset($strings[$key]);
			}
		}

		// Write override.ini file with the strings.
		if (JLanguageHelper::saveToIniFile($fileName, $strings) === false)
		{
			return false;
		}

		$this->cleanCache();

		return count($cids);
	}

	/**
	 * Removes all of the cached strings from the table.
	 *
	 * @return  boolean  result of operation
	 *
	 * @since   3.4.2
	 */
	public function purge()
	{
		$db = JFactory::getDbo();

		// Note: TRUNCATE is a DDL operation
		// This may or may not mean depending on your database
		try
		{
			$db->truncateTable('#__overrider');
		}
		catch (RuntimeException $e)
		{
			return $e;
		}

		JFactory::getApplication()->enqueueMessage(JText::_('COM_LANGUAGES_VIEW_OVERRIDES_PURGE_SUCCESS'));
	}
}
strings.php000060400000010436152456067220006757 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_languages
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Languages Strings Model
 *
 * @since  2.5
 */
class LanguagesModelStrings extends JModelLegacy
{
	/**
	 * Method for refreshing the cache in the database with the known language strings.
	 *
	 * @return  boolean  True on success, Exception object otherwise.
	 *
	 * @since		2.5
	 */
	public function refresh()
	{
		JLoader::register('LanguagesHelper', JPATH_ADMINISTRATOR . '/components/com_languages/helpers/languages.php');

		$app = JFactory::getApplication();

		$app->setUserState('com_languages.overrides.cachedtime', null);

		// Empty the database cache first.
		try
		{
			$this->_db->setQuery('TRUNCATE TABLE ' . $this->_db->quoteName('#__overrider'));
			$this->_db->execute();
		}
		catch (RuntimeException $e)
		{
			return $e;
		}

		// Create the insert query.
		$query = $this->_db->getQuery(true)
			->insert($this->_db->quoteName('#__overrider'))
			->columns('constant, string, file');

		// Initialize some variables.
		$client   = $app->getUserState('com_languages.overrides.filter.client', 'site') ? 'administrator' : 'site';
		$language = $app->getUserState('com_languages.overrides.filter.language', 'en-GB');

		$base = constant('JPATH_' . strtoupper($client));
		$path = $base . '/language/' . $language;

		$files = array();

		// Parse common language directory.
		jimport('joomla.filesystem.folder');

		if (is_dir($path))
		{
			$files = JFolder::files($path, '.*ini$', false, true);
		}

		// Parse language directories of components.
		$files = array_merge($files, JFolder::files($base . '/components', '.*ini$', 3, true));

		// Parse language directories of modules.
		$files = array_merge($files, JFolder::files($base . '/modules', '.*ini$', 3, true));

		// Parse language directories of templates.
		$files = array_merge($files, JFolder::files($base . '/templates', '.*ini$', 3, true));

		// Parse language directories of plugins.
		$files = array_merge($files, JFolder::files(JPATH_PLUGINS, '.*ini$', 4, true));

		// Parse all found ini files and add the strings to the database cache.
		foreach ($files as $file)
		{
			$strings = LanguagesHelper::parseFile($file);

			if ($strings && count($strings))
			{
				$query->clear('values');

				foreach ($strings as $key => $string)
				{
					$query->values($this->_db->quote($key) . ',' . $this->_db->quote($string) . ',' . $this->_db->quote(JPath::clean($file)));
				}

				try
				{
					$this->_db->setQuery($query);
					$this->_db->execute();
				}
				catch (RuntimeException $e)
				{
					return $e;
				}
			}
		}

		// Update the cached time.
		$app->setUserState('com_languages.overrides.cachedtime.' . $client . '.' . $language, time());

		return true;
	}

	/**
	 * Method for searching language strings.
	 *
	 * @return  array  Array of results on success, Exception object otherwise.
	 *
	 * @since		2.5
	 */
	public function search()
	{
		$results = array();
		$input   = JFactory::getApplication()->input;
		$filter  = JFilterInput::getInstance();
		$searchTerm = $input->getString('searchstring');

		$limitstart = $input->getInt('more');

		try
		{
			$searchstring = $this->_db->quote('%' . $filter->clean($searchTerm, 'TRIM') . '%');

			// Create the search query.
			$query = $this->_db->getQuery(true)
				->select('constant, string, file')
				->from($this->_db->quoteName('#__overrider'));

			if ($input->get('searchtype') == 'constant')
			{
				$query->where('constant LIKE ' . $searchstring);
			}
			else
			{
				$query->where('string LIKE ' . $searchstring);
			}

			// Consider the limitstart according to the 'more' parameter and load the results.
			$this->_db->setQuery($query, $limitstart, 10);
			$results['results'] = $this->_db->loadObjectList();

			// Check whether there are more results than already loaded.
			$query->clear('select')->clear('limit')
				->select('COUNT(id)');
			$this->_db->setQuery($query);

			if ($this->_db->loadResult() > $limitstart + 10)
			{
				// If this is set a 'More Results' link will be displayed in the view.
				$results['more'] = $limitstart + 10;
			}
		}
		catch (RuntimeException $e)
		{
			return $e;
		}

		return $results;
	}
}
language.php000060400000014016152456067220007047 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_languages
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Languages Component Language Model
 *
 * @since  1.5
 */
class LanguagesModelLanguage extends JModelAdmin
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 */
	public function __construct($config = array())
	{
		$config = array_merge(
			array(
				'event_after_save'  => 'onExtensionAfterSave',
				'event_before_save' => 'onExtensionBeforeSave',
				'events_map'        => array(
					'save' => 'extension'
				)
			), $config
		);

		parent::__construct($config);
	}

	/**
	 * Override to get the table.
	 *
	 * @param   string  $name     Name of the table.
	 * @param   string  $prefix   Table name prefix.
	 * @param   array   $options  Array of options.
	 *
	 * @return  JTable
	 *
	 * @since   1.6
	 */
	public function getTable($name = '', $prefix = '', $options = array())
	{
		return JTable::getInstance('Language');
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$app    = JFactory::getApplication('administrator');
		$params = JComponentHelper::getParams('com_languages');

		// Load the User state.
		$langId = $app->input->getInt('lang_id');
		$this->setState('language.id', $langId);

		// Load the parameters.
		$this->setState('params', $params);
	}

	/**
	 * Method to get a member item.
	 *
	 * @param   integer  $langId  The id of the member to get.
	 *
	 * @return  mixed  User data object on success, false on failure.
	 *
	 * @since   1.0
	 */
	public function getItem($langId = null)
	{
		$langId = (!empty($langId)) ? $langId : (int) $this->getState('language.id');

		// Get a member row instance.
		$table = $this->getTable();

		// Attempt to load the row.
		$return = $table->load($langId);

		// Check for a table object error.
		if ($return === false && $table->getError())
		{
			$this->setError($table->getError());

			return false;
		}

		// Set a valid accesslevel in case '0' is stored due to a bug in the installation SQL (was fixed with PR 2714).
		if ($table->access == '0')
		{
			$table->access = (int) JFactory::getConfig()->get('access');
		}

		$properties = $table->getProperties(1);
		$value      = ArrayHelper::toObject($properties, 'JObject');

		return $value;
	}

	/**
	 * Method to get the group form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed  A JForm object on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_languages.language', 'language', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_languages.edit.language.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		$this->preprocessData('com_languages.language', $data);

		return $data;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		$langId = (!empty($data['lang_id'])) ? $data['lang_id'] : (int) $this->getState('language.id');
		$isNew  = true;

		$dispatcher = JEventDispatcher::getInstance();
		JPluginHelper::importPlugin($this->events_map['save']);

		$table   = $this->getTable();
		$context = $this->option . '.' . $this->name;

		// Load the row if saving an existing item.
		if ($langId > 0)
		{
			$table->load($langId);
			$isNew = false;
		}

		// Prevent white spaces, including East Asian double bytes.
		$spaces = array('/\xE3\x80\x80/', ' ');

		$data['lang_code'] = str_replace($spaces, '', $data['lang_code']);

		// Prevent saving an incorrect language tag
		if (!preg_match('#\b([a-z]{2,3})[-]([A-Z]{2})\b#', $data['lang_code']))
		{
			$this->setError(JText::_('COM_LANGUAGES_ERROR_LANG_TAG'));

			return false;
		}

		$data['sef'] = str_replace($spaces, '', $data['sef']);
		$data['sef'] = JApplicationHelper::stringURLSafe($data['sef']);

		// Prevent saving an empty url language code
		if ($data['sef'] === '')
		{
			$this->setError(JText::_('COM_LANGUAGES_ERROR_SEF'));

			return false;
		}

		// Bind the data.
		if (!$table->bind($data))
		{
			$this->setError($table->getError());

			return false;
		}

		// Check the data.
		if (!$table->check())
		{
			$this->setError($table->getError());

			return false;
		}

		// Trigger the before save event.
		$result = $dispatcher->trigger($this->event_before_save, array($context, &$table, $isNew));

		// Check the event responses.
		if (in_array(false, $result, true))
		{
			$this->setError($table->getError());

			return false;
		}

		// Store the data.
		if (!$table->store())
		{
			$this->setError($table->getError());

			return false;
		}

		// Trigger the after save event.
		$dispatcher->trigger($this->event_after_save, array($context, &$table, $isNew));

		$this->setState('language.id', $table->lang_id);

		// Clean the cache.
		$this->cleanCache();

		return true;
	}

	/**
	 * Custom clean cache method.
	 *
	 * @param   string   $group     Optional cache group name.
	 * @param   integer  $clientId  Application client id.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function cleanCache($group = null, $clientId = 0)
	{
		parent::cleanCache('_system');
		parent::cleanCache('com_languages');
	}
}
override.php000060400000014046152456067220007106 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_languages
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Languages Override Model
 *
 * @since  2.5
 */
class LanguagesModelOverride extends JModelAdmin
{
	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed A JForm object on success, false on failure.
	 *
	 * @since   2.5
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_languages.override', 'override', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		$client   = $this->getState('filter.client', 'site');
		$language = $this->getState('filter.language', 'en-GB');
		$langName = JLanguage::getInstance($language)->getName();

		if (!$langName)
		{
			// If a language only exists in frontend, its metadata cannot be
			// loaded in backend at the moment, so fall back to the language tag.
			$langName = $language;
		}

		$form->setValue('client', null, JText::_('COM_LANGUAGES_VIEW_OVERRIDE_CLIENT_' . strtoupper($client)));
		$form->setValue('language', null, JText::sprintf('COM_LANGUAGES_VIEW_OVERRIDE_LANGUAGE', $langName, $language));
		$form->setValue('file', null, JPath::clean(constant('JPATH_' . strtoupper($client)) . '/language/overrides/' . $language . '.override.ini'));

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed The data for the form.
	 *
	 * @since   2.5
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_languages.edit.override.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		$this->preprocessData('com_languages.override', $data);

		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   string  $pk  The key name.
	 *
	 * @return  mixed  	Object on success, false otherwise.
	 *
	 * @since   2.5
	 */
	public function getItem($pk = null)
	{
		$input    = JFactory::getApplication()->input;
		$pk       = !empty($pk) ? $pk : $input->get('id');
		$fileName = constant('JPATH_' . strtoupper($this->getState('filter.client')))
			. '/language/overrides/' . $this->getState('filter.language', 'en-GB') . '.override.ini';
		$strings  = JLanguageHelper::parseIniFile($fileName);

		$result = new stdClass;
		$result->key      = '';
		$result->override = '';

		if (isset($strings[$pk]))
		{
			$result->key      = $pk;
			$result->override = $strings[$pk];
		}

		$oppositeFileName = constant('JPATH_' . strtoupper($this->getState('filter.client') == 'site' ? 'administrator' : 'site'))
			. '/language/overrides/' . $this->getState('filter.language', 'en-GB') . '.override.ini';
		$oppositeStrings  = JLanguageHelper::parseIniFile($oppositeFileName);
		$result->both = isset($oppositeStrings[$pk]) && ($oppositeStrings[$pk] == $strings[$pk]);

		return $result;
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array    $data            The form data.
	 * @param   boolean  $oppositeClient  Indicates whether the override should not be created for the current client.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   2.5
	 */
	public function save($data, $oppositeClient = false)
	{
		jimport('joomla.filesystem.file');

		$app = JFactory::getApplication();

		$client   = $app->getUserState('com_languages.overrides.filter.client', 0);
		$language = $app->getUserState('com_languages.overrides.filter.language', 'en-GB');

		// If the override should be created for both.
		if ($oppositeClient)
		{
			$client = 1 - $client;
		}

		// Return false if the constant is a reserved word, i.e. YES, NO, NULL, FALSE, ON, OFF, NONE, TRUE
		$blacklist = array('YES', 'NO', 'NULL', 'FALSE', 'ON', 'OFF', 'NONE', 'TRUE');

		if (in_array($data['key'], $blacklist))
		{
			$this->setError(JText::_('COM_LANGUAGES_OVERRIDE_ERROR_RESERVED_WORDS'));

			return false;
		}

		$client = $client ? 'administrator' : 'site';

		// Parse the override.ini file in oder to get the keys and strings.
		$fileName = constant('JPATH_' . strtoupper($client)) . '/language/overrides/' . $language . '.override.ini';
		$strings  = JLanguageHelper::parseIniFile($fileName);

		if (isset($strings[$data['id']]))
		{
			// If an existent string was edited check whether
			// the name of the constant is still the same.
			if ($data['key'] == $data['id'])
			{
				// If yes, simply override it.
				$strings[$data['key']] = $data['override'];
			}
			else
			{
				// If no, delete the old string and prepend the new one.
				unset($strings[$data['id']]);
				$strings = array($data['key'] => $data['override']) + $strings;
			}
		}
		else
		{
			// If it is a new override simply prepend it.
			$strings = array($data['key'] => $data['override']) + $strings;
		}

		// Write override.ini file with the strings.
		if (JLanguageHelper::saveToIniFile($fileName, $strings) === false)
		{
			return false;
		}

		// If the override should be stored for both clients save
		// it also for the other one and prevent endless recursion.
		if (isset($data['both']) && $data['both'] && !$oppositeClient)
		{
			return $this->save($data, true);
		}

		return true;
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication();

		$client = $app->getUserStateFromRequest('com_languages.overrides.filter.client', 'filter_client', 0, 'int') ? 'administrator' : 'site';
		$this->setState('filter.client', $client);

		$language = $app->getUserStateFromRequest('com_languages.overrides.filter.language', 'filter_language', 'en-GB', 'cmd');
		$this->setState('filter.language', $language);
	}
}
forms/language.xml000060400000005063152456067220010210 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field 
			name="lang_id" 
			type="text"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			class="readonly"
			default="0"
			readonly="true"
		/>

		<field 
			name="lang_code" 
			type="text"
			label="COM_LANGUAGES_FIELD_LANG_TAG_LABEL"
			description="COM_LANGUAGES_FIELD_LANG_TAG_DESC"
			maxlength="7"
			required="true"
			size="10"
		/>

		<field 
			name="title"
			type="text"
			label="JGLOBAL_TITLE"
			description="COM_LANGUAGES_FIELD_TITLE_DESC"
			maxlength="50"
			required="true"
			size="40"
		/>

		<field 
			name="title_native"
			type="text"
			label="COM_LANGUAGES_FIELD_TITLE_NATIVE_LABEL"
			description="COM_LANGUAGES_FIELD_TITLE_NATIVE_DESC"
			maxlength="50"
			required="true"
			size="40"
		/>

		<field 
			name="sef" 
			type="text"
			label="COM_LANGUAGES_FIELD_LANG_CODE_LABEL"
			description="COM_LANGUAGES_FIELD_LANG_CODE_DESC"
			maxlength="50"
			required="true"
			size="10"
		/>

		<field
			name="image"
			type="filelist"
			label="COM_LANGUAGES_FIELD_IMAGE_LABEL"
			description="COM_LANGUAGES_FIELD_IMAGE_DESC"
			stripext="1"
			directory="media/mod_languages/images/"
			hide_none="1"
			hide_default="1"
			filter="\.gif$"
			size="10"
			>
			<option value="">JNONE</option>
		</field>

		<field 
			name="description" 
			type="textarea"
			label="JGLOBAL_DESCRIPTION"
			description="COM_LANGUAGES_FIELD_DESCRIPTION_DESC"
			cols="80"
			rows="5"
		/>

		<field 
			name="published" 
			type="list"
			label="JSTATUS"
			description="COM_LANGUAGES_FIELD_PUBLISHED_DESC"
			default="1"
			size="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="-2">JTRASHED</option>
		</field>
		
		<field 
			name="access" 
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="JFIELD_ACCESS_DESC"
			size="1"
		/>
	</fieldset>
	<fieldset name="metadata" label="JGLOBAL_FIELDSET_METADATA_OPTIONS">
		<field 
			name="metakey" 
			type="textarea"
			label="JFIELD_META_KEYWORDS_LABEL"
			description="JFIELD_META_KEYWORDS_DESC"
			rows="3"
			cols="30"
		/>

		<field 
			name="metadesc" 
			type="textarea"
			label="JFIELD_META_DESCRIPTION_LABEL"
			description="JFIELD_META_DESCRIPTION_DESC"
			rows="3"
			cols="30"
		/>
	</fieldset>
	<fieldset name="site_name" label="COM_LANGUAGES_FIELDSET_SITE_NAME_LABEL">
		<field 
			name="sitename" 
			type="text"
			label="COM_LANGUAGES_FIELD_SITE_NAME_LABEL"
			description="COM_LANGUAGES_FIELD_SITE_NAME_DESC"
			filter="string"
			size="50"
		/>
	</fieldset>
</form>
forms/filter_overrides.xml000060400000001220152456067220011763 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<field
		name="language_client"
		type="languageclient"
		onchange="this.form.submit();"
		>
		<option value="">COM_LANGUAGES_OVERRIDE_SELECT_LANGUAGE</option>
	</field>

	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="JSEARCH_FILTER"
			description="COM_LANGUAGES_VIEW_OVERRIDES_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

	</fields>
	<fields name="list">
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/override.xml000060400000003737152456067220010252 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="key"
			type="text"
			label="COM_LANGUAGES_OVERRIDE_FIELD_KEY_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_KEY_DESC"
			size="60"
			required="true"
			filter="LanguagesHelper::filterKey" 
		/>

		<field
			name="override"
			type="textarea"
			label="COM_LANGUAGES_OVERRIDE_FIELD_OVERRIDE_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_OVERRIDE_DESC"
			cols="50"
			rows="5"
			filter="LanguagesHelper::filterText" 
		/>

		<field
			name="both"
			type="checkbox"
			label="COM_LANGUAGES_OVERRIDE_FIELD_BOTH_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_BOTH_DESC"
			value="true"
			filter="boolean" 
		/>

		<field
			name="searchstring"
			type="text"
			label="COM_LANGUAGES_OVERRIDE_FIELD_SEARCHSTRING_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_SEARCHSTRING_DESC"
			size="50"
		/>

		<field
			name="searchtype"
			type="list"
			label="COM_LANGUAGES_OVERRIDE_FIELD_SEARCHTYPE_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_SEARCHTYPE_DESC"
			default="value"
			>
			<option value="constant">COM_LANGUAGES_OVERRIDE_FIELD_SEARCHTYPE_CONSTANT</option>
			<option value="value">COM_LANGUAGES_OVERRIDE_FIELD_SEARCHTYPE_TEXT</option>
		</field>

		<field 
			name="language" 
			type="text"
			label="COM_LANGUAGES_OVERRIDE_FIELD_LANGUAGE_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_LANGUAGE_DESC"
			filter="unset"
			readonly="true"
			class="readonly"
			size="50"
		/>

		<field 
			name="client" 
			type="text"
			label="COM_LANGUAGES_OVERRIDE_FIELD_CLIENT_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_CLIENT_DESC"
			filter="unset"
			readonly="true"
			class="readonly"
			size="50"
		/>

		<field 
			name="file" 
			type="text"
			label="COM_LANGUAGES_OVERRIDE_FIELD_FILE_LABEL"
			description="COM_LANGUAGES_OVERRIDE_FIELD_FILE_DESC"
			filter="unset"
			readonly="true"
			class="readonly"
			size="80"
		/>

		<field
			name="id"
			type="hidden"
		/>
	</fieldset>
</form>
forms/filter_installed.xml000060400000004601152456067220011746 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<field
		name="client_id"
		type="list"
		onchange="jQuery('#filter_search, select[id^=filter_], #list_fullordering').val('');this.form.submit();"
		filtermode="selector"
		>
		<option value="0">JSITE</option>
		<option value="1">JADMINISTRATOR</option>
	</field>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_LANGUAGES_INSTALLED_FILTER_SEARCH_LABEL"
			description="COM_LANGUAGES_INSTALLED_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
			noresults="JGLOBAL_NO_MATCHING_RESULTS"
		/>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="name ASC">COM_LANGUAGES_HEADING_LANGUAGE_ASC</option>
			<option value="name DESC">COM_LANGUAGES_HEADING_LANGUAGE_DESC</option>
			<option value="nativeName ASC">COM_LANGUAGES_HEADING_TITLE_NATIVE_ASC</option>
			<option value="nativeName DESC">COM_LANGUAGES_HEADING_TITLE_NATIVE_DESC</option>
			<option value="language ASC">COM_LANGUAGES_HEADING_LANG_TAG_ASC</option>
			<option value="language DESC">COM_LANGUAGES_HEADING_LANG_TAG_DESC</option>
			<option value="published ASC">COM_LANGUAGES_HEADING_DEFAULT_ASC</option>
			<option value="published DESC">COM_LANGUAGES_HEADING_DEFAULT_DESC</option>
			<option value="version ASC">COM_LANGUAGES_HEADING_VERSION_ASC</option>
			<option value="version DESC">COM_LANGUAGES_HEADING_VERSION_DESC</option>
			<option value="creationDate ASC">COM_LANGUAGES_HEADING_DATE_ASC</option>
			<option value="creationDate DESC">COM_LANGUAGES_HEADING_DATE_DESC</option>
			<option value="author ASC">COM_LANGUAGES_HEADING_AUTHOR_ASC</option>
			<option value="author DESC">COM_LANGUAGES_HEADING_AUTHOR_DESC</option>
			<option value="authorEmail ASC">COM_LANGUAGES_HEADING_AUTHOR_EMAIL_ASC</option>
			<option value="authorEmail DESC">COM_LANGUAGES_HEADING_AUTHOR_EMAIL_DESC</option>
			<option value="extension_id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="extension_id DESC">JGRID_HEADING_ID_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_languages.xml000060400000002027152456067220011735 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_INSTALLER_LANGUAGES_FILTER_SEARCH_LABEL"
			description="COM_INSTALLER_LANGUAGES_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="name ASC">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="name DESC">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="element ASC">COM_INSTALLER_HEADING_LANGUAGE_TAG_ASC</option>
			<option value="element DESC">COM_INSTALLER_HEADING_LANGUAGE_TAG_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
    </fields>
</form>
fields/languageclient.php000060400000003361152456067220011515 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_newsfeeds
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JFormHelper::loadFieldClass('list');

/**
 * Client Language List field.
 *
 * @since  3.9.0
 */
class JFormFieldLanguageclient extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var		string
	 * @since   3.9.0
	 */
	protected $type = 'Languageclient';

	/**
	 * Cached form field options.
	 *
	 * @var		array
	 * @since   3.9.0
	 */
	protected $cache = array();

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.9.0
	 */
	protected function getOptions()
	{
		// Try to load the data from our mini-cache.
		if (!empty($this->cache))
		{
			return $this->cache;
		}

		// Get all languages of frontend and backend.
		$languages       = array();
		$site_languages  = JLanguageHelper::getKnownLanguages(JPATH_SITE);
		$admin_languages = JLanguageHelper::getKnownLanguages(JPATH_ADMINISTRATOR);

		// Create a single array of them.
		foreach ($site_languages as $tag => $language)
		{
			$languages[$tag . '0'] = JText::sprintf('COM_LANGUAGES_VIEW_OVERRIDES_LANGUAGES_BOX_ITEM', $language['name'], JText::_('JSITE'));
		}

		foreach ($admin_languages as $tag => $language)
		{
			$languages[$tag . '1'] = JText::sprintf('COM_LANGUAGES_VIEW_OVERRIDES_LANGUAGES_BOX_ITEM', $language['name'], JText::_('JADMINISTRATOR'));
		}

		// Sort it by language tag and by client after that.
		ksort($languages);

		// Add the languages to the internal cache.
		$this->cache = array_merge(parent::getOptions(), $languages);

		return $this->cache;
	}
}
installed.php000060400000024573152456067220007254 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_languages
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Languages Component Languages Model
 *
 * @since  1.6
 */
class LanguagesModelInstalled extends JModelList
{
	/**
	 * @var object client object
	 * @deprecated 4.0
	 */
	protected $client = null;

	/**
	 * @var object user object
	 */
	protected $user = null;

	/**
	 * @var boolean|JExeption True, if FTP settings should be shown, or an exception
	 */
	protected $ftp = null;

	/**
	 * @var string option name
	 */
	protected $option = null;

	/**
	 * @var array languages description
	 */
	protected $data = null;

	/**
	 * @var int total number of languages
	 */
	protected $total = null;

	/**
	 * @var int total number of languages installed
	 * @deprecated 4.0
	 */
	protected $langlist = null;

	/**
	 * @var string language path
	 */
	protected $path = null;

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   3.5
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'name',
				'nativeName',
				'language',
				'author',
				'published',
				'version',
				'creationDate',
				'author',
				'authorEmail',
				'extension_id',
				'client_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'name', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));

		// Special case for client id.
		$clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int');
		$clientId = (!in_array($clientId, array (0, 1))) ? 0 : $clientId;
		$this->setState('client_id', $clientId);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_languages');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id	.= ':' . $this->getState('client_id');
		$id	.= ':' . $this->getState('filter.search');

		return parent::getStoreId($id);
	}

	/**
	 * Method to get the client object.
	 *
	 * @return  object
	 *
	 * @since   1.6
	 */
	public function getClient()
	{
		return JApplicationHelper::getClientInfo($this->getState('client_id', 0));
	}

	/**
	 * Method to get the ftp credentials.
	 *
	 * @return  object
	 *
	 * @since   1.6
	 */
	public function getFtp()
	{
		if (is_null($this->ftp))
		{
			$this->ftp = JClientHelper::setCredentialsFromRequest('ftp');
		}

		return $this->ftp;
	}

	/**
	 * Method to get the option.
	 *
	 * @return  object
	 *
	 * @since   1.6
	 */
	public function getOption()
	{
		$option = $this->getState('option');

		return $option;
	}

	/**
	 * Method to get Languages item data.
	 *
	 * @return  array
	 *
	 * @since   1.6
	 */
	public function getData()
	{
		// Fetch language data if not fetched yet.
		if (is_null($this->data))
		{
			$this->data = array();

			$isCurrentLanguageRtl = JFactory::getLanguage()->isRtl();
			$params               = JComponentHelper::getParams('com_languages');
			$installedLanguages   = JLanguageHelper::getInstalledLanguages(null, true, true, null, null, null);

			// Compute all the languages.
			foreach ($installedLanguages as $clientId => $languages)
			{
				$defaultLanguage = $params->get(JApplicationHelper::getClientInfo($clientId)->name, 'en-GB');

				foreach ($languages as $lang)
				{
					$row               = new stdClass;
					$row->language     = $lang->element;
					$row->name         = $lang->metadata['name'];
					$row->nativeName   = isset($lang->metadata['nativeName']) ? $lang->metadata['nativeName'] : '-';
					$row->client_id    = (int) $lang->client_id;
					$row->extension_id = (int) $lang->extension_id;
					$row->author       = $lang->manifest['author'];
					$row->creationDate = $lang->manifest['creationDate'];
					$row->authorEmail  = $lang->manifest['authorEmail'];
					$row->version      = $lang->manifest['version'];
					$row->published    = $defaultLanguage === $row->language ? 1 : 0;
					$row->checked_out  = 0;

					// Fix wrongly set parentheses in RTL languages
					if ($isCurrentLanguageRtl)
					{
						$row->name       = html_entity_decode($row->name . '&#x200E;', ENT_QUOTES, 'UTF-8');
						$row->nativeName = html_entity_decode($row->nativeName . '&#x200E;', ENT_QUOTES, 'UTF-8');
					}

					$this->data[] = $row;
				}
			}
		}

		$installedLanguages = array_merge($this->data);

		// Process filters.
		$clientId = (int) $this->getState('client_id');
		$search   = $this->getState('filter.search');

		foreach ($installedLanguages as $key => $installedLanguage)
		{
			// Filter by client id.
			if (in_array($clientId, array(0, 1)))
			{
				if ($installedLanguage->client_id !== $clientId)
				{
					unset($installedLanguages[$key]);
					continue;
				}
			}

			// Filter by search term.
			if (!empty($search))
			{
				if (stripos($installedLanguage->name, $search) === false
					&& stripos($installedLanguage->nativeName, $search) === false
					&& stripos($installedLanguage->language, $search) === false)
				{
					unset($installedLanguages[$key]);
					continue;
				}
			}
		}

		// Process ordering.
		$listOrder = $this->getState('list.ordering', 'name');
		$listDirn  = $this->getState('list.direction', 'ASC');
		$installedLanguages = ArrayHelper::sortObjects($installedLanguages, $listOrder, strtolower($listDirn) === 'desc' ? -1 : 1, true, true);

		// Process pagination.
		$limit = (int) $this->getState('list.limit', 25);

		// Sets the total for pagination.
		$this->total = count($installedLanguages);

		if ($limit !== 0)
		{
			$start = (int) $this->getState('list.start', 0);

			return array_slice($installedLanguages, $start, $limit);
		}

		return $installedLanguages;
	}

	/**
	 * Method to get installed languages data.
	 *
	 * @return  string	An SQL query.
	 *
	 * @since   1.6
	 *
	 * @deprecated   4.0
	 */
	protected function getLanguageList()
	{
		// Create a new db object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$client = $this->getState('client_id');
		$type = 'language';

		// Select field element from the extensions table.
		$query->select($this->getState('list.select', 'a.element'))
			->from('#__extensions AS a');

		$type = $db->quote($type);
		$query->where('(a.type = ' . $type . ')')
			->where('state = 0')
			->where('enabled = 1')
			->where('client_id=' . (int) $client);

		// For client_id = 1 do we need to check language table also?
		$db->setQuery($query);

		$this->langlist = $db->loadColumn();

		return $this->langlist;
	}

	/**
	 * Method to get the total number of Languages items.
	 *
	 * @return  integer
	 *
	 * @since   1.6
	 */
	public function getTotal()
	{
		if (is_null($this->total))
		{
			$this->getData();
		}

		return $this->total;
	}

	/**
	 * Method to set the default language.
	 *
	 * @param   integer  $cid  Id of the language to publish.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	public function publish($cid)
	{
		if ($cid)
		{
			$client = $this->getClient();

			$params = JComponentHelper::getParams('com_languages');
			$params->set($client->name, $cid);

			$table = JTable::getInstance('extension');
			$id    = $table->find(array('element' => 'com_languages'));

			// Load.
			if (!$table->load($id))
			{
				$this->setError($table->getError());

				return false;
			}

			$table->params = (string) $params;

			// Pre-save checks.
			if (!$table->check())
			{
				$this->setError($table->getError());

				return false;
			}

			// Save the changes.
			if (!$table->store())
			{
				$this->setError($table->getError());

				return false;
			}
		}
		else
		{
			$this->setError(JText::_('COM_LANGUAGES_ERR_NO_LANGUAGE_SELECTED'));

			return false;
		}

		// Clean the cache of com_languages and component cache.
		$this->cleanCache();
		$this->cleanCache('_system', 0);
		$this->cleanCache('_system', 1);

		return true;
	}

	/**
	 * Method to get the folders.
	 *
	 * @return  array  Languages folders.
	 *
	 * @since   1.6
	 */
	protected function getFolders()
	{
		if (is_null($this->folders))
		{
			$path = $this->getPath();
			jimport('joomla.filesystem.folder');
			$this->folders = JFolder::folders($path, '.', false, false, array('.svn', 'CVS', '.DS_Store', '__MACOSX', 'pdf_fonts', 'overrides'));
		}

		return $this->folders;
	}

	/**
	 * Method to get the path.
	 *
	 * @return  string	The path to the languages folders.
	 *
	 * @since   1.6
	 */
	protected function getPath()
	{
		if (is_null($this->path))
		{
			$client     = $this->getClient();
			$this->path = JLanguageHelper::getLanguagePath($client->path);
		}

		return $this->path;
	}

	/**
	 * Method to compare two languages in order to sort them.
	 *
	 * @param   object  $lang1  The first language.
	 * @param   object  $lang2  The second language.
	 *
	 * @return  integer
	 *
	 * @since   1.6
	 *
	 * @deprecated   4.0
	 */
	protected function compareLanguages($lang1, $lang2)
	{
		return strcmp($lang1->name, $lang2->name);
	}

	/**
	 * Method to switch the administrator language.
	 *
	 * @param   string  $cid  The language tag.
	 *
	 * @return  boolean
	 *
	 * @since   3.5
	 */
	public function switchAdminLanguage($cid)
	{
		if ($cid)
		{
			$client = $this->getClient();

			if ($client->name == 'administrator')
			{
				JFactory::getApplication()->setUserState('application.lang', $cid);
			}
		}
		else
		{
			JError::raiseWarning(500, JText::_('COM_LANGUAGES_ERR_NO_LANGUAGE_SELECTED'));

			return false;
		}

		return true;
	}
}
languages.php000060400000013625152456067220007237 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

jimport('joomla.updater.update');
use Joomla\String\StringHelper;

/**
 * Languages Installer Model
 *
 * @since  2.5.7
 */
class InstallerModelLanguages extends JModelList
{
	/**
	 * Language count
	 *
	 * @var     integer
	 * @since   3.7.0
	 */
	private $languageCount;

	/**
	 * Constructor override, defines a whitelist of column filters.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   2.5.7
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'name',
				'element',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Get the Update Site
	 *
	 * @since   3.7.0
	 *
	 * @return  string  The URL of the Accredited Languagepack Updatesite XML
	 */
	private function getUpdateSite()
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->select($db->qn('us.location'))
			->from($db->qn('#__extensions', 'e'))
			->where($db->qn('e.type') . ' = ' . $db->q('package'))
			->where($db->qn('e.element') . ' = ' . $db->q('pkg_en-GB'))
			->where($db->qn('e.client_id') . ' = 0')
			->join('LEFT', $db->qn('#__update_sites_extensions', 'use') . ' ON ' . $db->qn('use.extension_id') . ' = ' . $db->qn('e.extension_id'))
			->join('LEFT', $db->qn('#__update_sites', 'us') . ' ON ' . $db->qn('us.update_site_id') . ' = ' . $db->qn('use.update_site_id'));

		return $db->setQuery($query)->loadResult();
	}

	/**
	 * Method to get an array of data items.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   3.7.0
	 */
	public function getItems()
	{
		// Get a storage key.
		$store = $this->getStoreId();

		// Try to load the data from internal storage.
		if (isset($this->cache[$store]))
		{
			return $this->cache[$store];
		}

		try
		{
			// Load the list items and add the items to the internal cache.
			$this->cache[$store] = $this->getLanguages();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		return $this->cache[$store];
	}

	/**
	 * Gets an array of objects from the updatesite.
	 *
	 * @return  object[]  An array of results.
	 *
	 * @since   3.0
	 * @throws  RuntimeException
	 */
	protected function getLanguages()
	{
		$updateSite = $this->getUpdateSite();

		// Check whether the updateserver is found
		if (empty($updateSite))
		{
			JFactory::getApplication()->enqueueMessage(JText::_('COM_INSTALLER_MSG_WARNING_NO_LANGUAGES_UPDATESERVER'), 'warning');

			return;
		}

		$http = new JHttp;

		try
		{
			$response = $http->get($updateSite);
		}
		catch (RuntimeException $e)
		{
			$response = null;
		}

		if ($response === null || $response->code !== 200)
		{
			JFactory::getApplication()->enqueueMessage(JText::sprintf('COM_INSTALLER_MSG_ERROR_CANT_CONNECT_TO_UPDATESERVER', $updateSite), 'error');

			return;
		}

		$updateSiteXML = simplexml_load_string($response->body);
		$languages     = array();
		$search        = strtolower($this->getState('filter.search'));

		foreach ($updateSiteXML->extension as $extension)
		{
			$language = new stdClass;

			foreach ($extension->attributes() as $key => $value)
			{
				$language->$key = (string) $value;
			}

			if ($search)
			{
				if (strpos(strtolower($language->name), $search) === false
					&& strpos(strtolower($language->element), $search) === false)
				{
					continue;
				}
			}

			$languages[$language->name] = $language;
		}

		// Workaround for php 5.3
		$that = $this;

		// Sort the array by value of subarray
		usort(
			$languages,
			function($a, $b) use ($that)
			{
				$ordering = $that->getState('list.ordering');

				if (strtolower($that->getState('list.direction')) === 'asc')
				{
					return StringHelper::strcmp($a->$ordering, $b->$ordering);
				}
				else
				{
					return StringHelper::strcmp($b->$ordering, $a->$ordering);
				}
			}
		);

		// Count the non-paginated list
		$this->languageCount = count($languages);
		$limit               = ($this->getState('list.limit') > 0) ? $this->getState('list.limit') : $this->languageCount;

		return array_slice($languages, $this->getStart(), $limit);
	}

	/**
	 * Returns a record count for the updatesite.
	 *
	 * @param   JDatabaseQuery|string  $query  The query.
	 *
	 * @return  integer  Number of rows for query.
	 *
	 * @since   3.7.0
	 */
	protected function _getListCount($query)
	{
		return $this->languageCount;
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   2.5.7
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');

		return parent::getStoreId($id);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   list order
	 * @param   string  $direction  direction in the list
	 *
	 * @return  void
	 *
	 * @since   2.5.7
	 */
	protected function populateState($ordering = 'name', $direction = 'asc')
	{
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));

		$this->setState('extension_message', JFactory::getApplication()->getUserState('com_installer.extension_message'));

		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to compare two languages in order to sort them.
	 *
	 * @param   object  $lang1  The first language.
	 * @param   object  $lang2  The second language.
	 *
	 * @return  integer
	 *
	 * @since   3.7.0
	 */
	protected function compareLanguages($lang1, $lang2)
	{
		return strcmp($lang1->name, $lang2->name);
	}
}
forms/filter_templates.xml000060400000002406152456070150011762 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_templates/models/fields" />
	<field
		name="client_id"
		type="list"
		filtermode="selector"
		onchange="jQuery('#filter_search, select[id^=filter_], #list_fullordering').val('');this.form.submit();"
		>
		<option value="0">JSITE</option>
		<option value="1">JADMINISTRATOR</option>
	</field>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="JSEARCH_FILTER"
			description="COM_TEMPLATES_TEMPLATES_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
			noresults="COM_TEMPLATES_MSG_MANAGE_NO_TEMPLATES"
		/>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="a.element ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.element ASC">COM_TEMPLATES_HEADING_TEMPLATE_ASC</option>
			<option value="a.element DESC">COM_TEMPLATES_HEADING_TEMPLATE_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/style.xml000060400000001637152456070150007564 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="id"
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			id="id"
			default="0"
			readonly="true"
			class="readonly"
		/>

		<field
			name="template"
			type="text"
			label="COM_TEMPLATES_FIELD_TEMPLATE_LABEL"
			description="COM_TEMPLATES_FIELD_TEMPLATE_DESC"
			class="readonly"
			size="30"
			readonly="true" 
		/>

		<field
			name="client_id"
			type="hidden"
			label="COM_TEMPLATES_FIELD_CLIENT_LABEL"
			description="COM_TEMPLATES_FIELD_CLIENT_DESC"
			class="readonly"
			default="0"
			readonly="true" 
		/>

		<field
			name="title"
			type="text"
			label="COM_TEMPLATES_FIELD_TITLE_LABEL"
			description="COM_TEMPLATES_FIELD_TITLE_DESC"
			class="input-xxlarge input-large-text"
			size="50"
			required="true" 
		/>

		<field 
			name="assigned" 
			type="hidden" 
		/>

	</fieldset>
</form>
forms/style_administrator.xml000060400000000547152456070150012523 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="home"
			type="radio"
			label="COM_TEMPLATES_FIELD_HOME_LABEL"
			description="COM_TEMPLATES_FIELD_HOME_ADMINISTRATOR_DESC"
			class="btn-group btn-group-yesno"
			default="0"
			>
			<option value="1">JYES</option>
			<option value="0">JNO</option>
		</field>
	</fieldset>
</form>
forms/style_site.xml000060400000000503152456070150010577 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="home"
			type="contentlanguage"
			label="COM_TEMPLATES_FIELD_HOME_LABEL"
			description="COM_TEMPLATES_FIELD_HOME_SITE_DESC"
			default="0"
			>
			<option value="0">JNO</option>
			<option value="1">JALL</option>
		</field>
	</fieldset>
</form>
forms/filter_styles.xml000060400000004213152456070150011305 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_templates/models/fields" />
	<field
		name="client_id"
		type="list"
		filtermode="selector"
		onchange="jQuery('#filter_search, select[id^=filter_], #list_fullordering').val('');this.form.submit();"
		>
		<option value="0">JSITE</option>
		<option value="1">JADMINISTRATOR</option>
	</field>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="JSEARCH_FILTER"
			description="COM_TEMPLATES_STYLES_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
			noresults="COM_TEMPLATES_MSG_MANAGE_NO_STYLES"
		/>
		<field
			name="menuitem"
			type="menuitem"
			label="COM_TEMPLATES_OPTION_SELECT_MENU_ITEM"
			disable="separator,alias,heading,url"
			showon="client_id:0"
			onchange="this.form.submit();"
			>
			<option	value="">COM_TEMPLATES_OPTION_SELECT_MENU_ITEM</option>
			<option	value="-1">COM_TEMPLATES_OPTION_NONE</option>
		</field>
		<field
			name="template"
			type="templatename"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_TEMPLATE</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="a.template ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.title ASC">COM_TEMPLATES_HEADING_STYLE_ASC</option>
			<option value="a.title DESC">COM_TEMPLATES_HEADING_STYLE_DESC</option>
			<option value="a.home ASC">COM_TEMPLATES_HEADING_DEFAULT_ASC</option>
			<option value="a.home DESC">COM_TEMPLATES_HEADING_DEFAULT_DESC</option>
			<option value="a.template ASC">COM_TEMPLATES_HEADING_TEMPLATE_ASC</option>
			<option value="a.template DESC">COM_TEMPLATES_HEADING_TEMPLATE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
    </fields>
</form>
forms/source.xml000060400000000701152456070150007713 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field
			name="extension_id"
			type="hidden" 
		/>

		<field
			name="filename"
			type="hidden"
		 />

		<field
			name="source"
			type="editor"
			label="COM_TEMPLATES_FIELD_SOURCE_LABEL"
			description="COM_TEMPLATES_FIELD_SOURCE_DESC"
			editor="codemirror|none"
			buttons="no"
			height="500px"
			rows="20"
			cols="80"
			syntax="php"
			filter="raw" 
		/>
	</fieldset>
</form>
template.php000060400000111003152456070150007065 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_templates
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Template model class.
 *
 * @since  1.6
 */
class TemplatesModelTemplate extends JModelForm
{
	/**
	 * The information in a template
	 *
	 * @var    stdClass
	 * @since  1.6
	 */
	protected $template = null;

	/**
	 * The path to the template
	 *
	 * @var    stdClass
	 * @since  3.2
	 */
	protected $element = null;

	/**
	 * Internal method to get file properties.
	 *
	 * @param   string  $path  The base path.
	 * @param   string  $name  The file name.
	 *
	 * @return  object
	 *
	 * @since   1.6
	 */
	protected function getFile($path, $name)
	{
		$temp = new stdClass;

		if ($template = $this->getTemplate())
		{
			$temp->name = $name;
			$temp->id = urlencode(base64_encode($path . $name));

			return $temp;
		}
	}

	/**
	 * Method to get a list of all the files to edit in a template.
	 *
	 * @return  array  A nested array of relevant files.
	 *
	 * @since   1.6
	 */
	public function getFiles()
	{
		$result = array();

		if ($template = $this->getTemplate())
		{
			jimport('joomla.filesystem.folder');
			$app    = JFactory::getApplication();
			$client = JApplicationHelper::getClientInfo($template->client_id);
			$path   = JPath::clean($client->path . '/templates/' . $template->element . '/');
			$lang   = JFactory::getLanguage();

			// Load the core and/or local language file(s).
			$lang->load('tpl_' . $template->element, $client->path, null, false, true) ||
			$lang->load('tpl_' . $template->element, $client->path . '/templates/' . $template->element, null, false, true);
			$this->element = $path;

			if (!is_writable($path))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_DIRECTORY_NOT_WRITABLE'), 'error');
			}

			if (is_dir($path))
			{
				$result = $this->getDirectoryTree($path);
			}
			else
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_TEMPLATE_FOLDER_NOT_FOUND'), 'error');

				return false;
			}
		}

		return $result;
	}

	/**
	 * Get the directory tree.
	 *
	 * @param   string  $dir  The path of the directory to scan
	 *
	 * @return  array
	 *
	 * @since   3.2
	 */
	public function getDirectoryTree($dir)
	{
		$result = array();

		$dirFiles = scandir($dir);

		foreach ($dirFiles as $key => $value)
		{
			if (!in_array($value, array('.', '..')))
			{
				if (is_dir($dir . $value))
				{
					$relativePath = str_replace($this->element, '', $dir . $value);
					$result['/' . $relativePath] = $this->getDirectoryTree($dir . $value . '/');
				}
				else
				{
					$ext           = pathinfo($dir . $value, PATHINFO_EXTENSION);
					$allowedFormat = $this->checkFormat($ext);

					if ($allowedFormat == true)
					{
						$relativePath = str_replace($this->element, '', $dir);
						$info = $this->getFile('/' . $relativePath, $value);
						$result[] = $info;
					}
				}
			}
		}

		return $result;
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		jimport('joomla.filesystem.file');
		$app = JFactory::getApplication('administrator');

		// Load the User state.
		$pk = $app->input->getInt('id');
		$this->setState('extension.id', $pk);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_templates');
		$this->setState('params', $params);
	}

	/**
	 * Method to get the template information.
	 *
	 * @return  mixed  Object if successful, false if not and internal error is set.
	 *
	 * @since   1.6
	 */
	public function &getTemplate()
	{
		if (empty($this->template))
		{
			$pk  = $this->getState('extension.id');
			$db  = $this->getDbo();
			$app = JFactory::getApplication();

			// Get the template information.
			$query = $db->getQuery(true)
				->select('extension_id, client_id, element, name, manifest_cache')
				->from('#__extensions')
				->where($db->quoteName('extension_id') . ' = ' . (int) $pk)
				->where($db->quoteName('type') . ' = ' . $db->quote('template'));
			$db->setQuery($query);

			try
			{
				$result = $db->loadObject();
			}
			catch (RuntimeException $e)
			{
				$app->enqueueMessage($e->getMessage(), 'warning');
				$this->template = false;

				return false;
			}

			if (empty($result))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_EXTENSION_RECORD_NOT_FOUND'), 'error');
				$this->template = false;
			}
			else
			{
				$this->template = $result;
			}
		}

		return $this->template;
	}

	/**
	 * Method to check if new template name already exists
	 *
	 * @return  boolean   true if name is not used, false otherwise
	 *
	 * @since	2.5
	 */
	public function checkNewName()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('COUNT(*)')
			->from('#__extensions')
			->where('name = ' . $db->quote($this->getState('new_name')));
		$db->setQuery($query);

		return ($db->loadResult() == 0);
	}

	/**
	 * Method to check if new template name already exists
	 *
	 * @return  string     name of current template
	 *
	 * @since	2.5
	 */
	public function getFromName()
	{
		return $this->getTemplate()->element;
	}

	/**
	 * Method to check if new template name already exists
	 *
	 * @return  boolean   true if name is not used, false otherwise
	 *
	 * @since	2.5
	 */
	public function copy()
	{
		$app = JFactory::getApplication();

		if ($template = $this->getTemplate())
		{
			jimport('joomla.filesystem.folder');
			$client = JApplicationHelper::getClientInfo($template->client_id);
			$fromPath = JPath::clean($client->path . '/templates/' . $template->element . '/');

			// Delete new folder if it exists
			$toPath = $this->getState('to_path');

			if (JFolder::exists($toPath))
			{
				if (!JFolder::delete($toPath))
				{
					$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_COULD_NOT_WRITE'), 'error');

					return false;
				}
			}

			// Copy all files from $fromName template to $newName folder
			if (!JFolder::copy($fromPath, $toPath) || !$this->fixTemplateName())
			{
				return false;
			}

			return true;
		}
		else
		{
			$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_INVALID_FROM_NAME'), 'error');

			return false;
		}
	}

	/**
	 * Method to delete tmp folder
	 *
	 * @return  boolean   true if delete successful, false otherwise
	 *
	 * @since	2.5
	 */
	public function cleanup()
	{
		// Clear installation messages
		$app = JFactory::getApplication();
		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		// Delete temporary directory
		return JFolder::delete($this->getState('to_path'));
	}

	/**
	 * Method to rename the template in the XML files and rename the language files
	 *
	 * @return  boolean  true if successful, false otherwise
	 *
	 * @since	2.5
	 */
	protected function fixTemplateName()
	{
		// Rename Language files
		// Get list of language files
		$result   = true;
		$files    = JFolder::files($this->getState('to_path'), '.ini', true, true);
		$newName  = strtolower($this->getState('new_name'));
		$template = $this->getTemplate();
		$oldName  = $template->element;
		$manifest = json_decode($template->manifest_cache);

		jimport('joomla.filesystem.file');

		foreach ($files as $file)
		{
			$newFile = '/' . str_replace($oldName, $newName, basename($file));
			$result  = JFile::move($file, dirname($file) . $newFile) && $result;
		}

		// Edit XML file
		$xmlFile = $this->getState('to_path') . '/templateDetails.xml';

		if (JFile::exists($xmlFile))
		{
			$contents = file_get_contents($xmlFile);
			$pattern[] = '#<name>\s*' . $manifest->name . '\s*</name>#i';
			$replace[] = '<name>' . $newName . '</name>';
			$pattern[] = '#<language(.*)' . $oldName . '(.*)</language>#';
			$replace[] = '<language${1}' . $newName . '${2}</language>';
			$contents = preg_replace($pattern, $replace, $contents);
			$result = JFile::write($xmlFile, $contents) && $result;
		}

		return $result;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm    A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		$app = JFactory::getApplication();

		// Codemirror or Editor None should be enabled
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('COUNT(*)')
			->from('#__extensions as a')
			->where(
				'(a.name =' . $db->quote('plg_editors_codemirror') .
				' AND a.enabled = 1) OR (a.name =' .
				$db->quote('plg_editors_none') .
				' AND a.enabled = 1)'
			);
		$db->setQuery($query);
		$state = $db->loadResult();

		if ((int) $state < 1)
		{
			$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_EDITOR_DISABLED'), 'warning');
		}

		// Get the form.
		$form = $this->loadForm('com_templates.source', 'source', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		$data = $this->getSource();

		$this->preprocessData('com_templates.source', $data);

		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @return  mixed  Object on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function &getSource()
	{
		$app = JFactory::getApplication();
		$item = new stdClass;

		if (!$this->template)
		{
			$this->getTemplate();
		}

		if ($this->template)
		{
			$input    = JFactory::getApplication()->input;
			$fileName = base64_decode($input->get('file'));
			$client   = JApplicationHelper::getClientInfo($this->template->client_id);

			try
			{
				$filePath = JPath::check($client->path . '/templates/' . $this->template->element . '/' . $fileName);
			}
			catch (Exception $e)
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_FOUND'), 'error');

				return;
			}

			if (file_exists($filePath))
			{
				$item->extension_id = $this->getState('extension.id');
				$item->filename = $fileName;
				$item->source = file_get_contents($filePath);
			}
			else
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_FOUND'), 'error');
			}
		}

		return $item;
	}

	/**
	 * Method to store the source file contents.
	 *
	 * @param   array  $data  The source data to save.
	 *
	 * @return  boolean  True on success, false otherwise and internal error set.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		jimport('joomla.filesystem.file');

		// Get the template.
		$template = $this->getTemplate();

		if (empty($template))
		{
			return false;
		}

		$app = JFactory::getApplication();
		$fileName = base64_decode($app->input->get('file'));
		$client = JApplicationHelper::getClientInfo($template->client_id);
		$filePath = JPath::clean($client->path . '/templates/' . $template->element . '/' . $fileName);

		// Include the extension plugins for the save events.
		JPluginHelper::importPlugin('extension');

		$user = get_current_user();
		chown($filePath, $user);
		JPath::setPermissions($filePath, '0644');

		// Try to make the template file writable.
		if (!is_writable($filePath))
		{
			$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_SOURCE_FILE_NOT_WRITABLE'), 'warning');
			$app->enqueueMessage(JText::sprintf('COM_TEMPLATES_FILE_PERMISSIONS', JPath::getPermissions($filePath)), 'warning');

			if (!JPath::isOwner($filePath))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_CHECK_FILE_OWNERSHIP'), 'warning');
			}

			return false;
		}

		// Make sure EOL is Unix
		$data['source'] = str_replace(array("\r\n", "\r"), "\n", $data['source']);

		$return = JFile::write($filePath, $data['source']);

		if (!$return)
		{
			$app->enqueueMessage(JText::sprintf('COM_TEMPLATES_ERROR_FAILED_TO_SAVE_FILENAME', $fileName), 'error');

			return false;
		}

		// Get the extension of the changed file.
		$explodeArray = explode('.', $fileName);
		$ext = end($explodeArray);

		if ($ext == 'less')
		{
			$app->enqueueMessage(JText::sprintf('COM_TEMPLATES_COMPILE_LESS', $fileName));
		}

		return true;
	}

	/**
	 * Get overrides folder.
	 *
	 * @param   string  $name  The name of override.
	 * @param   string  $path  Location of override.
	 *
	 * @return  object  containing override name and path.
	 *
	 * @since   3.2
	 */
	public function getOverridesFolder($name,$path)
	{
		$folder = new stdClass;
		$folder->name = $name;
		$folder->path = base64_encode($path . $name);

		return $folder;
	}

	/**
	 * Get a list of overrides.
	 *
	 * @return  array containing overrides.
	 *
	 * @since   3.2
	 */
	public function getOverridesList()
	{
		if ($template = $this->getTemplate())
		{
			$client        = JApplicationHelper::getClientInfo($template->client_id);
			$componentPath = JPath::clean($client->path . '/components/');
			$modulePath    = JPath::clean($client->path . '/modules/');
			$pluginPath    = JPath::clean(JPATH_ROOT . '/plugins/');
			$layoutPath    = JPath::clean(JPATH_ROOT . '/layouts/');
			$components    = JFolder::folders($componentPath);

			foreach ($components as $component)
			{
				if (file_exists($componentPath . '/' . $component . '/views/'))
				{
					$viewPath = JPath::clean($componentPath . '/' . $component . '/views/');
				}
				elseif (file_exists($componentPath . '/' . $component . '/view/'))
				{
					$viewPath = JPath::clean($componentPath . '/' . $component . '/view/');
				}
				else
				{
					$viewPath = '';
				}

				if ($viewPath)
				{
					$views = JFolder::folders($viewPath);

					foreach ($views as $view)
					{
						// Only show the view has layout inside it
						if (file_exists($viewPath . $view . '/tmpl'))
						{
							$result['components'][$component][] = $this->getOverridesFolder($view, $viewPath);
						}
					}
				}
			}

			foreach (JFolder::folders($pluginPath) as $pluginGroup)
			{
				foreach (JFolder::folders($pluginPath . '/' . $pluginGroup) as $plugin)
				{
					if (file_exists($pluginPath . '/' . $pluginGroup . '/' . $plugin . '/tmpl/'))
					{
						$pluginLayoutPath = JPath::clean($pluginPath . '/' . $pluginGroup . '/');
						$result['plugins'][$pluginGroup][] = $this->getOverridesFolder($plugin, $pluginLayoutPath);
					}
				}
			}

			$modules = JFolder::folders($modulePath);

			foreach ($modules as $module)
			{
				$result['modules'][] = $this->getOverridesFolder($module, $modulePath);
			}

			$layoutFolders = JFolder::folders($layoutPath);

			foreach ($layoutFolders as $layoutFolder)
			{
				$layoutFolderPath = JPath::clean($layoutPath . '/' . $layoutFolder . '/');
				$layouts = JFolder::folders($layoutFolderPath);

				foreach ($layouts as $layout)
				{
					$result['layouts'][$layoutFolder][] = $this->getOverridesFolder($layout, $layoutFolderPath);
				}
			}

			// Check for layouts in component folders
			foreach ($components as $component)
			{
				if (file_exists($componentPath . '/' . $component . '/layouts/'))
				{
					$componentLayoutPath = JPath::clean($componentPath . '/' . $component . '/layouts/');

					if ($componentLayoutPath)
					{
						$layouts = JFolder::folders($componentLayoutPath);

						foreach ($layouts as $layout)
						{
							$result['layouts'][$component][] = $this->getOverridesFolder($layout, $componentLayoutPath);
						}
					}
				}
			}
		}

		if (!empty($result))
		{
			return $result;
		}
	}

	/**
	 * Create overrides.
	 *
	 * @param   string  $override  The override location.
	 *
	 * @return   boolean  true if override creation is successful, false otherwise
	 *
	 * @since   3.2
	 */
	public function createOverride($override)
	{
		jimport('joomla.filesystem.folder');

		if ($template = $this->getTemplate())
		{
			$app          = JFactory::getApplication();
			$explodeArray = explode(DIRECTORY_SEPARATOR, $override);
			$name         = end($explodeArray);
			$client       = JApplicationHelper::getClientInfo($template->client_id);

			if (stristr($name, 'mod_') != false)
			{
				$htmlPath   = JPath::clean($client->path . '/templates/' . $template->element . '/html/' . $name);
			}
			elseif (stristr($override, 'com_') != false)
			{
				$size = count($explodeArray);

				$url = JPath::clean($explodeArray[$size - 3] . '/' . $explodeArray[$size - 1]);

				if ($explodeArray[$size - 2] == 'layouts')
				{
					$htmlPath = JPath::clean($client->path . '/templates/' . $template->element . '/html/layouts/' . $url);
				}
				else
				{
					$htmlPath = JPath::clean($client->path . '/templates/' . $template->element . '/html/' . $url);
				}
			}
			elseif (stripos($override, JPath::clean(JPATH_ROOT . '/plugins/')) === 0)
			{
				$size       = count($explodeArray);
				$layoutPath = JPath::clean('plg_' . $explodeArray[$size - 2] . '_' . $explodeArray[$size - 1]);
				$htmlPath   = JPath::clean($client->path . '/templates/' . $template->element . '/html/' . $layoutPath);
			}
			else
			{
				$layoutPath = implode('/', array_slice($explodeArray, -2));
				$htmlPath   = JPath::clean($client->path . '/templates/' . $template->element . '/html/layouts/' . $layoutPath);
			}

			// Check Html folder, create if not exist
			if (!JFolder::exists($htmlPath))
			{
				if (!JFolder::create($htmlPath))
				{
					$app->enqueueMessage(JText::_('COM_TEMPLATES_FOLDER_ERROR'), 'error');

					return false;
				}
			}

			if (stristr($name, 'mod_') != false)
			{
				$return = $this->createTemplateOverride(JPath::clean($override . '/tmpl'), $htmlPath);
			}
			elseif (stristr($override, 'com_') != false && stristr($override, 'layouts') == false)
			{
				$return = $this->createTemplateOverride(JPath::clean($override . '/tmpl'), $htmlPath);
			}
			elseif (stripos($override, JPath::clean(JPATH_ROOT . '/plugins/')) === 0)
			{
				$return = $this->createTemplateOverride(JPath::clean($override . '/tmpl'), $htmlPath);
			}
			else
			{
				$return = $this->createTemplateOverride($override, $htmlPath);
			}

			if ($return)
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_OVERRIDE_CREATED') . str_replace(JPATH_ROOT, '', $htmlPath));

				return true;
			}
			else
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_OVERRIDE_FAILED'), 'error');

				return false;
			}
		}
	}

	/**
	 * Create override folder & file
	 *
	 * @param   string  $overridePath  The override location
	 * @param   string  $htmlPath      The html location
	 *
	 * @return  boolean                True on success. False otherwise.
	 */
	public function createTemplateOverride($overridePath, $htmlPath)
	{
		$return = false;

		if (empty($overridePath) || empty($htmlPath))
		{
			return $return;
		}

		// Get list of template folders
		$folders = JFolder::folders($overridePath, null, true, true);

		if (!empty($folders))
		{
			foreach ($folders as $folder)
			{
				$htmlFolder = $htmlPath . str_replace($overridePath, '', $folder);

				if (!JFolder::exists($htmlFolder))
				{
					JFolder::create($htmlFolder);
				}
			}
		}

		// Get list of template files (Only get *.php file for template file)
		$files = JFolder::files($overridePath, '.php', true, true);

		if (empty($files))
		{
			return true;
		}

		foreach ($files as $file)
		{
			$overrideFilePath = str_replace($overridePath, '', $file);
			$htmlFilePath = $htmlPath . $overrideFilePath;

			if (JFile::exists($htmlFilePath))
			{
				// Generate new unique file name base on current time
				$today = JFactory::getDate();
				$htmlFilePath = JFile::stripExt($htmlFilePath) . '-' . $today->format('Ymd-His') . '.' . JFile::getExt($htmlFilePath);
			}

			$return = JFile::copy($file, $htmlFilePath, '', true);
		}

		return $return;
	}

	/**
	 * Compile less using the less compiler under /build.
	 *
	 * @param   string  $input  The relative location of the less file.
	 *
	 * @return  boolean  true if compilation is successful, false otherwise
	 *
	 * @since   3.2
	 */
	public function compileLess($input)
	{
		if ($template = $this->getTemplate())
		{
			$app          = JFactory::getApplication();
			$client       = JApplicationHelper::getClientInfo($template->client_id);
			$path         = JPath::clean($client->path . '/templates/' . $template->element . '/');
			$inFile       = urldecode(base64_decode($input));
			$explodeArray = explode('/', $inFile);
			$fileName     = end($explodeArray);
			$outFile      = current(explode('.', $fileName));

			$less = new JLess;
			$less->setFormatter(new JLessFormatterJoomla);

			try
			{
				$less->compileFile($path . $inFile, $path . 'css/' . $outFile . '.css');

				return true;
			}
			catch (Exception $e)
			{
				$app->enqueueMessage($e->getMessage(), 'error');
			}
		}
	}

	/**
	 * Delete a particular file.
	 *
	 * @param   string  $file  The relative location of the file.
	 *
	 * @return   boolean  True if file deletion is successful, false otherwise
	 *
	 * @since   3.2
	 */
	public function deleteFile($file)
	{
		if ($template = $this->getTemplate())
		{
			$app      = JFactory::getApplication();
			$client   = JApplicationHelper::getClientInfo($template->client_id);
			$path     = JPath::clean($client->path . '/templates/' . $template->element . '/');
			$filePath = $path . urldecode(base64_decode($file));

			$return = JFile::delete($filePath);

			if (!$return)
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_DELETE_FAIL'), 'error');

				return false;
			}

			return true;
		}
	}

	/**
	 * Create new file.
	 *
	 * @param   string  $name      The name of file.
	 * @param   string  $type      The extension of the file.
	 * @param   string  $location  Location for the new file.
	 *
	 * @return  boolean  true if file created successfully, false otherwise
	 *
	 * @since   3.2
	 */
	public function createFile($name, $type, $location)
	{
		if ($template = $this->getTemplate())
		{
			$app    = JFactory::getApplication();
			$client = JApplicationHelper::getClientInfo($template->client_id);
			$path   = JPath::clean($client->path . '/templates/' . $template->element . '/');

			if (file_exists(JPath::clean($path . '/' . $location . '/' . $name . '.' . $type)))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_EXISTS'), 'error');

				return false;
			}

			if (!fopen(JPath::clean($path . '/' . $location . '/' . $name . '.' . $type), 'x'))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_CREATE_ERROR'), 'error');

				return false;
			}

			// Check if the format is allowed and will be showed in the backend
			$check = $this->checkFormat($type);

			// Add a message if we are not allowed to show this file in the backend.
			if (!$check)
			{
				$app->enqueueMessage(JText::sprintf('COM_TEMPLATES_WARNING_FORMAT_WILL_NOT_BE_VISIBLE', $type), 'warning');
			}

			return true;
		}
	}

	/**
	 * Upload new file.
	 *
	 * @param   string  $file      The name of the file.
	 * @param   string  $location  Location for the new file.
	 *
	 * @return   boolean  True if file uploaded successfully, false otherwise
	 *
	 * @since   3.2
	 */
	public function uploadFile($file, $location)
	{
		jimport('joomla.filesystem.folder');

		if ($template = $this->getTemplate())
		{
			$app      = JFactory::getApplication();
			$client   = JApplicationHelper::getClientInfo($template->client_id);
			$path     = JPath::clean($client->path . '/templates/' . $template->element . '/');
			$fileName = JFile::makeSafe($file['name']);

			$err = null;
			JLoader::register('TemplateHelper', JPATH_ADMINISTRATOR . '/components/com_templates/helpers/template.php');

			if (!TemplateHelper::canUpload($file, $err))
			{
				// Can't upload the file
				return false;
			}

			if (file_exists(JPath::clean($path . '/' . $location . '/' . $file['name'])))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_EXISTS'), 'error');

				return false;
			}

			if (!JFile::upload($file['tmp_name'], JPath::clean($path . '/' . $location . '/' . $fileName)))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_UPLOAD_ERROR'), 'error');

				return false;
			}

			$url = JPath::clean($location . '/' . $fileName);

			return $url;
		}
	}

	/**
	 * Create new folder.
	 *
	 * @param   string  $name      The name of the new folder.
	 * @param   string  $location  Location for the new folder.
	 *
	 * @return   boolean  True if override folder is created successfully, false otherwise
	 *
	 * @since   3.2
	 */
	public function createFolder($name, $location)
	{
		jimport('joomla.filesystem.folder');

		if ($template = $this->getTemplate())
		{
			$app    = JFactory::getApplication();
			$client = JApplicationHelper::getClientInfo($template->client_id);
			$path   = JPath::clean($client->path . '/templates/' . $template->element . '/');

			if (file_exists(JPath::clean($path . '/' . $location . '/' . $name . '/')))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FOLDER_EXISTS'), 'error');

				return false;
			}

			if (!JFolder::create(JPath::clean($path . '/' . $location . '/' . $name)))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FOLDER_CREATE_ERROR'), 'error');

				return false;
			}

			return true;
		}
	}

	/**
	 * Delete a folder.
	 *
	 * @param   string  $location  The name and location of the folder.
	 *
	 * @return  boolean  True if override folder is deleted successfully, false otherwise
	 *
	 * @since   3.2
	 */
	public function deleteFolder($location)
	{
		jimport('joomla.filesystem.folder');

		if ($template = $this->getTemplate())
		{
			$app    = JFactory::getApplication();
			$client = JApplicationHelper::getClientInfo($template->client_id);
			$path   = JPath::clean($client->path . '/templates/' . $template->element . '/' . $location);

			if (!file_exists($path))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FOLDER_NOT_EXISTS'), 'error');

				return false;
			}

			$return = JFolder::delete($path);

			if (!$return)
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_DELETE_ERROR'), 'error');

				return false;
			}

			return true;
		}
	}

	/**
	 * Rename a file.
	 *
	 * @param   string  $file  The name and location of the old file
	 * @param   string  $name  The new name of the file.
	 *
	 * @return  string  Encoded string containing the new file location.
	 *
	 * @since   3.2
	 */
	public function renameFile($file, $name)
	{
		if ($template = $this->getTemplate())
		{
			$app          = JFactory::getApplication();
			$client       = JApplicationHelper::getClientInfo($template->client_id);
			$path         = JPath::clean($client->path . '/templates/' . $template->element . '/');
			$fileName     = base64_decode($file);
			$explodeArray = explode('.', $fileName);
			$type         = end($explodeArray);
			$explodeArray = explode('/', $fileName);
			$newName      = str_replace(end($explodeArray), $name . '.' . $type, $fileName);

			if (file_exists($path . $newName))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_EXISTS'), 'error');

				return false;
			}

			if (!rename($path . $fileName, $path . $newName))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_RENAME_ERROR'), 'error');

				return false;
			}

			return base64_encode($newName);
		}
	}

	/**
	 * Get an image address, height and width.
	 *
	 * @return  array an associative array containing image address, height and width.
	 *
	 * @since   3.2
	 */
	public function getImage()
	{
		if ($template = $this->getTemplate())
		{
			$app      = JFactory::getApplication();
			$client   = JApplicationHelper::getClientInfo($template->client_id);
			$fileName = base64_decode($app->input->get('file'));
			$path     = JPath::clean($client->path . '/templates/' . $template->element . '/');

			if (stristr($client->path, 'administrator') == false)
			{
				$folder = '/templates/';
			}
			else
			{
				$folder = '/administrator/templates/';
			}

			$uri = JUri::root(true) . $folder . $template->element;

			if (file_exists(JPath::clean($path . $fileName)))
			{
				$JImage = new JImage(JPath::clean($path . $fileName));
				$image['address'] = $uri . $fileName;
				$image['path']    = $fileName;
				$image['height']  = $JImage->getHeight();
				$image['width']   = $JImage->getWidth();
			}

			else
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_IMAGE_FILE_NOT_FOUND'), 'error');

				return false;
			}

			return $image;
		}
	}

	/**
	 * Crop an image.
	 *
	 * @param   string  $file  The name and location of the file
	 * @param   string  $w     width.
	 * @param   string  $h     height.
	 * @param   string  $x     x-coordinate.
	 * @param   string  $y     y-coordinate.
	 *
	 * @return  boolean     true if image cropped successfully, false otherwise.
	 *
	 * @since   3.2
	 */
	public function cropImage($file, $w, $h, $x, $y)
	{
		if ($template = $this->getTemplate())
		{
			$app      = JFactory::getApplication();
			$client   = JApplicationHelper::getClientInfo($template->client_id);
			$relPath  = base64_decode($file);
			$path     = JPath::clean($client->path . '/templates/' . $template->element . '/' . $relPath);

			try
			{
				$image      = new \JImage($path);
				$properties = $image->getImageFileProperties($path);

				switch ($properties->mime)
				{
					case 'image/png':
						$imageType = \IMAGETYPE_PNG;
						break;
					case 'image/gif':
						$imageType = \IMAGETYPE_GIF;
						break;
					default:
						$imageType = \IMAGETYPE_JPEG;
				}

				$image->crop($w, $h, $x, $y, false);
				$image->toFile($path, $imageType);

				return true;
			}
			catch (Exception $e)
			{
				$app->enqueueMessage($e->getMessage(), 'error');
			}
		}
	}

	/**
	 * Resize an image.
	 *
	 * @param   string  $file    The name and location of the file
	 * @param   string  $width   The new width of the image.
	 * @param   string  $height  The new height of the image.
	 *
	 * @return   boolean  true if image resize successful, false otherwise.
	 *
	 * @since   3.2
	 */
	public function resizeImage($file, $width, $height)
	{
		if ($template = $this->getTemplate())
		{
			$app     = JFactory::getApplication();
			$client  = JApplicationHelper::getClientInfo($template->client_id);
			$relPath = base64_decode($file);
			$path    = JPath::clean($client->path . '/templates/' . $template->element . '/' . $relPath);

			try
			{
				$image      = new \JImage($path);
				$properties = $image->getImageFileProperties($path);

				switch ($properties->mime)
				{
					case 'image/png':
						$imageType = \IMAGETYPE_PNG;
						break;
					case 'image/gif':
						$imageType = \IMAGETYPE_GIF;
						break;
					default:
						$imageType = \IMAGETYPE_JPEG;
				}

				$image->resize($width, $height, false, \JImage::SCALE_FILL);
				$image->toFile($path, $imageType);

				return true;
			}
			catch (Exception $e)
			{
				$app->enqueueMessage($e->getMessage(), 'error');
			}
		}
	}

	/**
	 * Template preview.
	 *
	 * @return  object  object containing the id of the template.
	 *
	 * @since   3.2
	 */
	public function getPreview()
	{
		$app = JFactory::getApplication();
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		$query->select('id, client_id');
		$query->from('#__template_styles');
		$query->where($db->quoteName('template') . ' = ' . $db->quote($this->template->element));

		$db->setQuery($query);

		try
		{
			$result = $db->loadObject();
		}
		catch (RuntimeException $e)
		{
			$app->enqueueMessage($e->getMessage(), 'warning');
		}

		if (empty($result))
		{
			$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_EXTENSION_RECORD_NOT_FOUND'), 'warning');
		}
		else
		{
			return $result;
		}
	}

	/**
	 * Rename a file.
	 *
	 * @return  mixed  array on success, false on failure
	 *
	 * @since   3.2
	 */
	public function getFont()
	{
		if ($template = $this->getTemplate())
		{
			$app          = JFactory::getApplication();
			$client       = JApplicationHelper::getClientInfo($template->client_id);
			$relPath      = base64_decode($app->input->get('file'));
			$explodeArray = explode('/', $relPath);
			$fileName     = end($explodeArray);
			$path         = JPath::clean($client->path . '/templates/' . $template->element . '/' . $relPath);

			if (stristr($client->path, 'administrator') == false)
			{
				$folder = '/templates/';
			}
			else
			{
				$folder = '/administrator/templates/';
			}

			$uri = JUri::root(true) . $folder . $template->element;

			if (file_exists(JPath::clean($path)))
			{
				$font['address'] = $uri . $relPath;

				$font['rel_path'] = $relPath;

				$font['name'] = $fileName;
			}

			else
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_FONT_FILE_NOT_FOUND'), 'error');

				return false;
			}

			return $font;
		}
	}

	/**
	 * Copy a file.
	 *
	 * @param   string  $newName   The name of the copied file
	 * @param   string  $location  The final location where the file is to be copied
	 * @param   string  $file      The name and location of the file
	 *
	 * @return   boolean  true if image resize successful, false otherwise.
	 *
	 * @since   3.2
	 */
	public function copyFile($newName, $location, $file)
	{
		if ($template = $this->getTemplate())
		{
			$app          = JFactory::getApplication();
			$client       = JApplicationHelper::getClientInfo($template->client_id);
			$relPath      = base64_decode($file);
			$explodeArray = explode('.', $relPath);
			$ext          = end($explodeArray);
			$path         = JPath::clean($client->path . '/templates/' . $template->element . '/');
			$newPath      = JPath::clean($path . '/' . $location . '/' . $newName . '.' . $ext);

			if (file_exists($newPath))
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_EXISTS'), 'error');

				return false;
			}

			if (JFile::copy($path . $relPath, $newPath))
			{
				$app->enqueueMessage(JText::sprintf('COM_TEMPLATES_FILE_COPY_SUCCESS', $newName . '.' . $ext));

				return true;
			}
			else
			{
				return false;
			}
		}
	}

	/**
	 * Get the compressed files.
	 *
	 * @return   array if file exists, false otherwise
	 *
	 * @since   3.2
	 */
	public function getArchive()
	{
		if ($template = $this->getTemplate())
		{
			$app     = JFactory::getApplication();
			$client  = JApplicationHelper::getClientInfo($template->client_id);
			$relPath = base64_decode($app->input->get('file'));
			$path    = JPath::clean($client->path . '/templates/' . $template->element . '/' . $relPath);

			if (file_exists(JPath::clean($path)))
			{
				$files = array();
				$zip = new ZipArchive;

				if ($zip->open($path) === true)
				{
					for ($i = 0; $i < $zip->numFiles; $i++)
					{
						$entry = $zip->getNameIndex($i);
						$files[] = $entry;
					}
				}
				else
				{
					$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_ARCHIVE_OPEN_FAIL'), 'error');

					return false;
				}
			}
			else
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_ERROR_FONT_FILE_NOT_FOUND'), 'error');

				return false;
			}

			return $files;
		}
	}

	/**
	 * Extract contents of an archive file.
	 *
	 * @param   string  $file  The name and location of the file
	 *
	 * @return  boolean  true if image extraction is successful, false otherwise.
	 *
	 * @since   3.2
	 */
	public function extractArchive($file)
	{
		if ($template = $this->getTemplate())
		{
			$app          = JFactory::getApplication();
			$client       = JApplicationHelper::getClientInfo($template->client_id);
			$relPath      = base64_decode($file);
			$explodeArray = explode('/', $relPath);
			$fileName     = end($explodeArray);
			$folderPath   = stristr($relPath, $fileName, true);
			$path         = JPath::clean($client->path . '/templates/' . $template->element . '/' . $folderPath . '/');

			if (file_exists(JPath::clean($path . '/' . $fileName)))
			{
				$zip = new ZipArchive;

				if ($zip->open(JPath::clean($path . '/' . $fileName)) === true)
				{
					for ($i = 0; $i < $zip->numFiles; $i++)
					{
						$entry = $zip->getNameIndex($i);

						if (file_exists(JPath::clean($path . '/' . $entry)))
						{
							$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_ARCHIVE_EXISTS'), 'error');

							return false;
						}
					}

					$zip->extractTo($path);

					return true;
				}
				else
				{
					$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_ARCHIVE_OPEN_FAIL'), 'error');

					return false;
				}
			}
			else
			{
				$app->enqueueMessage(JText::_('COM_TEMPLATES_FILE_ARCHIVE_NOT_FOUND'), 'error');

				return false;
			}
		}
	}

	/**
	 * Check if the extension is allowed and will be shown in the template manager
	 *
	 * @param   string  $ext  The extension to check if it is allowed
	 *
	 * @return  boolean  true if the extension is allowed false otherwise
	 *
	 * @since   3.6.0
	 */
	protected function checkFormat($ext)
	{
		if (!isset($this->allowedFormats))
		{
			$params       = JComponentHelper::getParams('com_templates');
			$imageTypes   = explode(',', $params->get('image_formats'));
			$sourceTypes  = explode(',', $params->get('source_formats'));
			$fontTypes    = explode(',', $params->get('font_formats'));
			$archiveTypes = explode(',', $params->get('compressed_formats'));

			$this->allowedFormats = array_merge($imageTypes, $sourceTypes, $fontTypes, $archiveTypes);
		}

		return in_array($ext, $this->allowedFormats);
	}
}
style.php000060400000043360152456070150006424 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_templates
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;

/**
 * Template style model.
 *
 * @since  1.6
 */
class TemplatesModelStyle extends JModelAdmin
{
	/**
	 * The help screen key for the module.
	 *
	 * @var	    string
	 * @since   1.6
	 */
	protected $helpKey = 'JHELP_EXTENSIONS_TEMPLATE_MANAGER_STYLES_EDIT';

	/**
	 * The help screen base URL for the module.
	 *
	 * @var     string
	 * @since   1.6
	 */
	protected $helpURL;

	/**
	 * Item cache.
	 *
	 * @var    array
	 * @since  1.6
	 */
	private $_cache = array();

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 */
	public function __construct($config = array())
	{
		$config = array_merge(
			array(
				'event_before_delete' => 'onExtensionBeforeDelete',
				'event_after_delete'  => 'onExtensionAfterDelete',
				'event_before_save'   => 'onExtensionBeforeSave',
				'event_after_save'    => 'onExtensionAfterSave',
				'events_map'          => array('delete' => 'extension', 'save' => 'extension')
			), $config
		);

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * @note    Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication('administrator');

		// Load the User state.
		$pk = $app->input->getInt('id');
		$this->setState('style.id', $pk);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_templates');
		$this->setState('params', $params);
	}

	/**
	 * Method to delete rows.
	 *
	 * @param   array  &$pks  An array of item ids.
	 *
	 * @return  boolean  Returns true on success, false on failure.
	 *
	 * @since   1.6
	 * @throws  Exception
	 */
	public function delete(&$pks)
	{
		$pks        = (array) $pks;
		$user       = JFactory::getUser();
		$table      = $this->getTable();
		$dispatcher = JEventDispatcher::getInstance();
		$context    = $this->option . '.' . $this->name;

		JPluginHelper::importPlugin($this->events_map['delete']);

		// Iterate the items to delete each one.
		foreach ($pks as $pk)
		{
			if ($table->load($pk))
			{
				// Access checks.
				if (!$user->authorise('core.delete', 'com_templates'))
				{
					throw new Exception(JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));
				}

				// You should not delete a default style
				if ($table->home != '0')
				{
					JError::raiseWarning(500, JText::_('COM_TEMPLATES_STYLE_CANNOT_DELETE_DEFAULT_STYLE'));

					return false;
				}

				// Trigger the before delete event.
				$result = $dispatcher->trigger($this->event_before_delete, array($context, $table));

				if (in_array(false, $result, true) || !$table->delete($pk))
				{
					$this->setError($table->getError());

					return false;
				}

				// Trigger the after delete event.
				$dispatcher->trigger($this->event_after_delete, array($context, $table));
			}
			else
			{
				$this->setError($table->getError());

				return false;
			}
		}

		// Clean cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to duplicate styles.
	 *
	 * @param   array  &$pks  An array of primary key IDs.
	 *
	 * @return  boolean  True if successful.
	 *
	 * @throws  Exception
	 */
	public function duplicate(&$pks)
	{
		$user = JFactory::getUser();

		// Access checks.
		if (!$user->authorise('core.create', 'com_templates'))
		{
			throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
		}

		$dispatcher = JEventDispatcher::getInstance();
		$context    = $this->option . '.' . $this->name;

		// Include the plugins for the save events.
		JPluginHelper::importPlugin($this->events_map['save']);

		$table = $this->getTable();

		foreach ($pks as $pk)
		{
			if ($table->load($pk, true))
			{
				// Reset the id to create a new record.
				$table->id = 0;

				// Reset the home (don't want dupes of that field).
				$table->home = 0;

				// Alter the title.
				$m = null;
				$table->title = $this->generateNewTitle(null, null, $table->title);

				if (!$table->check())
				{
					throw new Exception($table->getError());
				}

				// Trigger the before save event.
				$result = $dispatcher->trigger($this->event_before_save, array($context, &$table, true));

				if (in_array(false, $result, true) || !$table->store())
				{
					throw new Exception($table->getError());
				}

				// Trigger the after save event.
				$dispatcher->trigger($this->event_after_save, array($context, &$table, true));
			}
			else
			{
				throw new Exception($table->getError());
			}
		}

		// Clean cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to change the title.
	 *
	 * @param   integer  $categoryId  The id of the category.
	 * @param   string   $alias       The alias.
	 * @param   string   $title       The title.
	 *
	 * @return  string  New title.
	 *
	 * @since   1.7.1
	 */
	protected function generateNewTitle($categoryId, $alias, $title)
	{
		// Alter the title
		$table = $this->getTable();

		while ($table->load(array('title' => $title)))
		{
			$title = StringHelper::increment($title);
		}

		return $title;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      An optional array of data for the form to interrogate.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm  A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// The folder and element vars are passed when saving the form.
		if (empty($data))
		{
			$item	   = $this->getItem();
			$clientId  = $item->client_id;
			$template  = $item->template;
		}
		else
		{
			$clientId  = ArrayHelper::getValue($data, 'client_id');
			$template  = ArrayHelper::getValue($data, 'template');
		}

		// Add the default fields directory
		$baseFolder = $clientId ? JPATH_ADMINISTRATOR : JPATH_SITE;
		JForm::addFieldPath($baseFolder . '/templates/' . $template . '/field');

		// These variables are used to add data from the plugin XML files.
		$this->setState('item.client_id', $clientId);
		$this->setState('item.template', $template);

		// Get the form.
		$form = $this->loadForm('com_templates.style', 'style', array('control' => 'jform', 'load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		// Modify the form based on access controls.
		if (!$this->canEditState((object) $data))
		{
			// Disable fields for display.
			$form->setFieldAttribute('home', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is a record you can edit.
			$form->setFieldAttribute('home', 'filter', 'unset');
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_templates.edit.style.data', array());

		if (empty($data))
		{
			$data = $this->getItem();
		}

		$this->preprocessData('com_templates.style', $data);

		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed  Object on success, false on failure.
	 */
	public function getItem($pk = null)
	{
		$pk = (!empty($pk)) ? $pk : (int) $this->getState('style.id');

		if (!isset($this->_cache[$pk]))
		{
			// Get a row instance.
			$table = $this->getTable();

			// Attempt to load the row.
			$return = $table->load($pk);

			// Check for a table object error.
			if ($return === false && $table->getError())
			{
				$this->setError($table->getError());

				return false;
			}

			// Convert to the JObject before adding other data.
			$properties        = $table->getProperties(1);
			$this->_cache[$pk] = ArrayHelper::toObject($properties, 'JObject');

			// Convert the params field to an array.
			$registry = new Registry($table->params);
			$this->_cache[$pk]->params = $registry->toArray();

			// Get the template XML.
			$client = JApplicationHelper::getClientInfo($table->client_id);
			$path   = JPath::clean($client->path . '/templates/' . $table->template . '/templateDetails.xml');

			if (file_exists($path))
			{
				$this->_cache[$pk]->xml = simplexml_load_file($path);
			}
			else
			{
				$this->_cache[$pk]->xml = null;
			}
		}

		return $this->_cache[$pk];
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param   type    $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A database object
	 */
	public function getTable($type = 'Style', $prefix = 'TemplatesTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to allow derived classes to preprocess the form.
	 *
	 * @param   JForm   $form   A JForm object.
	 * @param   mixed   $data   The data expected for the form.
	 * @param   string  $group  The name of the plugin group to import (defaults to "content").
	 *
	 * @return  void
	 *
	 * @since   1.6
	 * @throws  Exception if there is an error in the form event.
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		$clientId = $this->getState('item.client_id');
		$template = $this->getState('item.template');
		$lang     = JFactory::getLanguage();
		$client   = JApplicationHelper::getClientInfo($clientId);

		if (!$form->loadFile('style_' . $client->name, true))
		{
			throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
		}

		jimport('joomla.filesystem.path');

		$formFile = JPath::clean($client->path . '/templates/' . $template . '/templateDetails.xml');

		// Load the core and/or local language file(s).
			$lang->load('tpl_' . $template, $client->path, null, false, true)
		||	$lang->load('tpl_' . $template, $client->path . '/templates/' . $template, null, false, true);

		if (file_exists($formFile))
		{
			// Get the template form.
			if (!$form->loadFile($formFile, false, '//config'))
			{
				throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
			}
		}

		// Disable home field if it is default style

		if ((is_array($data) && array_key_exists('home', $data) && $data['home'] == '1')
			|| (is_object($data) && isset($data->home) && $data->home == '1'))
		{
			$form->setFieldAttribute('home', 'readonly', 'true');
		}

		// Attempt to load the xml file.
		if (!$xml = simplexml_load_file($formFile))
		{
			throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
		}

		// Get the help data from the XML file if present.
		$help = $xml->xpath('/extension/help');

		if (!empty($help))
		{
			$helpKey = trim((string) $help[0]['key']);
			$helpURL = trim((string) $help[0]['url']);

			$this->helpKey = $helpKey ?: $this->helpKey;
			$this->helpURL = $helpURL ?: $this->helpURL;
		}

		// Trigger the default form events.
		parent::preprocessForm($form, $data, $group);
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 */
	public function save($data)
	{
		// Detect disabled extension
		$extension = JTable::getInstance('Extension');

		if ($extension->load(array('enabled' => 0, 'type' => 'template', 'element' => $data['template'], 'client_id' => $data['client_id'])))
		{
			$this->setError(JText::_('COM_TEMPLATES_ERROR_SAVE_DISABLED_TEMPLATE'));

			return false;
		}

		$app        = JFactory::getApplication();
		$dispatcher = JEventDispatcher::getInstance();
		$table      = $this->getTable();
		$pk         = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('style.id');
		$isNew      = true;

		// Include the extension plugins for the save events.
		JPluginHelper::importPlugin($this->events_map['save']);

		// Load the row if saving an existing record.
		if ($pk > 0)
		{
			$table->load($pk);
			$isNew = false;
		}

		if ($app->input->get('task') == 'save2copy')
		{
			$data['title']    = $this->generateNewTitle(null, null, $data['title']);
			$data['home']     = 0;
			$data['assigned'] = '';
		}

		// Bind the data.
		if (!$table->bind($data))
		{
			$this->setError($table->getError());

			return false;
		}

		// Prepare the row for saving
		$this->prepareTable($table);

		// Check the data.
		if (!$table->check())
		{
			$this->setError($table->getError());

			return false;
		}

		// Trigger the before save event.
		$result = $dispatcher->trigger($this->event_before_save, array('com_templates.style', &$table, $isNew));

		// Store the data.
		if (in_array(false, $result, true) || !$table->store())
		{
			$this->setError($table->getError());

			return false;
		}

		$user = JFactory::getUser();

		if ($user->authorise('core.edit', 'com_menus') && $table->client_id == 0)
		{
			$n    = 0;
			$db   = $this->getDbo();
			$user = JFactory::getUser();

			if (!empty($data['assigned']) && is_array($data['assigned']))
			{
				$data['assigned'] = ArrayHelper::toInteger($data['assigned']);

				// Update the mapping for menu items that this style IS assigned to.
				$query = $db->getQuery(true)
					->update('#__menu')
					->set('template_style_id = ' . (int) $table->id)
					->where('id IN (' . implode(',', $data['assigned']) . ')')
					->where('template_style_id != ' . (int) $table->id)
					->where('checked_out IN (0,' . (int) $user->id . ')');
				$db->setQuery($query);
				$db->execute();
				$n += $db->getAffectedRows();
			}

			// Remove style mappings for menu items this style is NOT assigned to.
			// If unassigned then all existing maps will be removed.
			$query = $db->getQuery(true)
				->update('#__menu')
				->set('template_style_id = 0');

			if (!empty($data['assigned']))
			{
				$query->where('id NOT IN (' . implode(',', $data['assigned']) . ')');
			}

			$query->where('template_style_id = ' . (int) $table->id)
				->where('checked_out IN (0,' . (int) $user->id . ')');
			$db->setQuery($query);
			$db->execute();

			$n += $db->getAffectedRows();

			if ($n > 0)
			{
				$app->enqueueMessage(JText::plural('COM_TEMPLATES_MENU_CHANGED', $n));
			}
		}

		// Clean the cache.
		$this->cleanCache();

		// Trigger the after save event.
		$dispatcher->trigger($this->event_after_save, array('com_templates.style', &$table, $isNew));

		$this->setState('style.id', $table->id);

		return true;
	}

	/**
	 * Method to set a template style as home.
	 *
	 * @param   integer  $id  The primary key ID for the style.
	 *
	 * @return  boolean  True if successful.
	 *
	 * @throws	Exception
	 */
	public function setHome($id = 0)
	{
		$user = JFactory::getUser();
		$db   = $this->getDbo();

		// Access checks.
		if (!$user->authorise('core.edit.state', 'com_templates'))
		{
			throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
		}

		$style = JTable::getInstance('Style', 'TemplatesTable');

		if (!$style->load((int) $id))
		{
			throw new Exception(JText::_('COM_TEMPLATES_ERROR_STYLE_NOT_FOUND'));
		}

		// Detect disabled extension
		$extension = JTable::getInstance('Extension');

		if ($extension->load(array('enabled' => 0, 'type' => 'template', 'element' => $style->template, 'client_id' => $style->client_id)))
		{
			throw new Exception(JText::_('COM_TEMPLATES_ERROR_SAVE_DISABLED_TEMPLATE'));
		}

		// Reset the home fields for the client_id.
		$query = $db->getQuery(true)
			->update('#__template_styles')
			->set('home = ' .  $db->q('0'))
			->where('client_id = ' . (int) $style->client_id)
			->where('home = ' . $db->q('1'));
		$db->setQuery($query);
		$db->execute();

		// Set the new home style.
		$query = $db->getQuery(true)
			->update('#__template_styles')
			->set('home = ' . $db->q('1'))
			->where('id = ' . (int) $id);
		$db->setQuery($query);
		$db->execute();

		// Clean the cache.
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to unset a template style as default for a language.
	 *
	 * @param   integer  $id  The primary key ID for the style.
	 *
	 * @return  boolean  True if successful.
	 *
	 * @throws	Exception
	 */
	public function unsetHome($id = 0)
	{
		$user = JFactory::getUser();
		$db   = $this->getDbo();

		// Access checks.
		if (!$user->authorise('core.edit.state', 'com_templates'))
		{
			throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
		}

		// Lookup the client_id.
		$query = $db->getQuery(true)
			->select('client_id, home')
			->from('#__template_styles')
			->where('id = ' . (int) $id);
		$db->setQuery($query);
		$style = $db->loadObject();

		if (!is_numeric($style->client_id))
		{
			throw new Exception(JText::_('COM_TEMPLATES_ERROR_STYLE_NOT_FOUND'));
		}
		elseif ($style->home == '1')
		{
			throw new Exception(JText::_('COM_TEMPLATES_ERROR_CANNOT_UNSET_DEFAULT_STYLE'));
		}

		// Set the new home style.
		$query = $db->getQuery(true)
			->update('#__template_styles')
			->set('home = ' . $db->q('0'))
			->where('id = ' . (int) $id);
		$db->setQuery($query);
		$db->execute();

		// Clean the cache.
		$this->cleanCache();

		return true;
	}

	/**
	 * Get the necessary data to load an item help screen.
	 *
	 * @return  object  An object with key, url, and local properties for loading the item help screen.
	 *
	 * @since   1.6
	 */
	public function getHelp()
	{
		return (object) array('key' => $this->helpKey, 'url' => $this->helpURL);
	}

	/**
	 * Custom clean cache method
	 *
	 * @param   string   $group     The cache group
	 * @param   integer  $clientId  The ID of the client
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function cleanCache($group = null, $clientId = 0)
	{
		parent::cleanCache('com_templates');
		parent::cleanCache('_system');
	}
}
styles.php000060400000015232152456070150006604 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_templates
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\String\StringHelper;

/**
 * Methods supporting a list of template style records.
 *
 * @since  1.6
 */
class TemplatesModelStyles extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JControllerLegacy
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'title', 'a.title',
				'template', 'a.template',
				'home', 'a.home',
				'menuitem',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.template', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.template', $this->getUserStateFromRequest($this->context . '.filter.template', 'filter_template', '', 'string'));
		$this->setState('filter.menuitem', $this->getUserStateFromRequest($this->context . '.filter.menuitem', 'filter_menuitem', '', 'cmd'));

		// Special case for the client id.
		$clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int');
		$clientId = (!in_array($clientId, array (0, 1))) ? 0 : $clientId;
		$this->setState('client_id', $clientId);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_templates');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('client_id');
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.template');
		$id .= ':' . $this->getState('filter.menuitem');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 */
	protected function getListQuery()
	{
		$clientId = (int) $this->getState('client_id');

		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.template, a.title, a.home, a.client_id, l.title AS language_title, l.image as image, l.sef AS language_sef'
			)
		);
		$query->from($db->quoteName('#__template_styles', 'a'))
			->where($db->quoteName('a.client_id') . ' = ' . $clientId);

		// Join on menus.
		$query->select('COUNT(m.template_style_id) AS assigned')
			->join('LEFT', $db->quoteName('#__menu', 'm') . ' ON ' . $db->quoteName('m.template_style_id') . ' = ' . $db->quoteName('a.id'))
			->group('a.id, a.template, a.title, a.home, a.client_id, l.title, l.image, e.extension_id, l.sef');

		// Join over the language.
		$query->join('LEFT', $db->quoteName('#__languages', 'l') . ' ON ' . $db->quoteName('l.lang_code') . ' = ' . $db->quoteName('a.home'));

		// Filter by extension enabled.
		$query->select($db->quoteName('extension_id', 'e_id'))
			->join('LEFT', $db->quoteName('#__extensions', 'e') . ' ON e.element = a.template AND e.client_id = a.client_id')
			->where($db->quoteName('e.enabled') . ' = 1')
			->where($db->quoteName('e.type') . ' = ' . $db->quote('template'));

		// Filter by template.
		if ($template = $this->getState('filter.template'))
		{
			$query->where($db->quoteName('a.template') . ' = ' . $db->quote($template));
		}

		// Filter by menuitem.
		$menuItemId = $this->getState('filter.menuitem');

		if ($clientId === 0 && is_numeric($menuItemId))
		{
			// If user selected the templates styles that are not assigned to any page.
			if ((int) $menuItemId === -1)
			{
				// Only custom template styles overrides not assigned to any menu item.
				$query->where($db->quoteName('a.home') . ' = ' . $db->quote(0))
					->where($db->quoteName('m.id') . ' IS NULL');
			}
			// If user selected the templates styles assigned to particular pages.
			else
			{
				// Subquery to get the language of the selected menu item.
				$menuItemLanguageSubQuery = $db->getQuery(true);
				$menuItemLanguageSubQuery->select($db->quoteName('language'))
					->from($db->quoteName('#__menu'))
					->where($db->quoteName('id') . ' = ' . $menuItemId);

				// Subquery to get the language of the selected menu item.
				$templateStylesMenuItemsSubQuery = $db->getQuery(true);
				$templateStylesMenuItemsSubQuery->select($db->quoteName('id'))
					->from($db->quoteName('#__menu'))
					->where($db->quoteName('template_style_id') . ' = ' . $db->quoteName('a.id'));

				// Main query where clause.
				$query->where('(' .
					// Default template style (fallback template style to all menu items).
					$db->quoteName('a.home') . ' = ' . $db->quote(1) . ' OR ' .
					// Default template style for specific language (fallback template style to the selected menu item language).
					$db->quoteName('a.home') . ' IN (' . $menuItemLanguageSubQuery . ') OR ' .
					// Custom template styles override (only if assigned to the selected menu item).
					'(' . $db->quoteName('a.home') . ' = ' . $db->quote(0) . ' AND ' . $menuItemId . ' IN (' . $templateStylesMenuItemsSubQuery . '))' .
					')'
				);
			}
		}

		// Filter by search in title.
		if ($search = $this->getState('filter.search'))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->quoteName('a.id') . ' = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . StringHelper::strtolower($search) . '%');
				$query->where('(' . ' LOWER(a.template) LIKE ' . $search . ' OR LOWER(a.title) LIKE ' . $search . ')');
			}
		}

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'a.template')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}
}
templates.php000060400000010271152456070150007255 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_templates
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\String\StringHelper;

/**
 * Methods supporting a list of template extension records.
 *
 * @since  1.6
 */
class TemplatesModelTemplates extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JControllerLegacy
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'name', 'a.name',
				'folder', 'a.folder',
				'element', 'a.element',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'state', 'a.state',
				'enabled', 'a.enabled',
				'ordering', 'a.ordering',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Override parent getItems to add extra XML metadata.
	 *
	 * @return  array
	 *
	 * @since   1.6
	 */
	public function getItems()
	{
		$items = parent::getItems();

		foreach ($items as &$item)
		{
			$client = JApplicationHelper::getClientInfo($item->client_id);
			$item->xmldata = TemplatesHelper::parseXMLTemplateFile($client->path, $item->element);
		}

		return $items;
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.extension_id, a.name, a.element, a.client_id'
			)
		);
		$query->from($db->quoteName('#__extensions', 'a'))
			->where($db->quoteName('a.client_id') . ' = ' . (int) $this->getState('client_id'))
			->where($db->quoteName('a.enabled') . ' = 1')
			->where($db->quoteName('a.type') . ' = ' . $db->quote('template'));

		// Filter by search in title.
		if ($search = $this->getState('filter.search'))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->quoteName('a.id') . ' = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . StringHelper::strtolower($search) . '%');
				$query->where('(' . ' LOWER(a.element) LIKE ' . $search . ' OR LOWER(a.name) LIKE ' . $search . ')');
			}
		}

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'a.element')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('client_id');
		$id .= ':' . $this->getState('filter.search');

		return parent::getStoreId($id);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.element', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));

		// Special case for the client id.
		$clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int');
		$clientId = (!in_array($clientId, array (0, 1))) ? 0 : $clientId;
		$this->setState('client_id', $clientId);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_templates');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}
}
fields/templatename.php000060400000002223152456070150011177 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_templates
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('TemplatesHelper', JPATH_ADMINISTRATOR . '/components/com_templates/helpers/templates.php');

JFormHelper::loadFieldClass('list');

/**
 * Template Name field.
 *
 * @since  3.5
 */
class JFormFieldTemplateName extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var	   string
	 * @since  3.5
	 */
	protected $type = 'TemplateName';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   1.6
	 */
	public function getOptions()
	{
		// Get the client_id filter from the user state.
		$clientId = JFactory::getApplication()->getUserStateFromRequest('com_templates.styles.client_id', 'client_id', '0', 'string');

		// Get the templates for the selected client_id.
		$options = TemplatesHelper::getTemplateOptions($clientId);

		// Merge into the parent options.
		return array_merge(parent::getOptions(), $options);
	}
}
fields/templatelocation.php000060400000001610152456070150012066 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_templates
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('TemplatesHelper', JPATH_ADMINISTRATOR . '/components/com_templates/helpers/templates.php');

JFormHelper::loadFieldClass('list');

/**
 * Template Location field.
 *
 * @since  3.5
 */
class JFormFieldTemplateLocation extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var	   string
	 * @since  3.5
	 */
	protected $type = 'TemplateLocation';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.5
	 */
	public function getOptions()
	{
		$options = TemplatesHelper::getClientOptions();

		return array_merge(parent::getOptions(), $options);
	}
}
mailto.php000060400000005223152456112370006546 0ustar00<?php
/**
 * @package     Joomla.Site
 * @subpackage  com_users
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Mailto model class.
 *
 * @since  3.8.9
 */
class MailtoModelMailto extends JModelForm
{
	/**
	 * Method to get the mailto form.
	 *
	 * The base form is loaded from XML and then an event is fired
	 * for users plugins to extend the form with extra fields.
	 *
	 * @param   array    $data      An optional array of data for the form to interrogate.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm	A JForm object on success, false on failure
	 *
	 * @since   3.8.9
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_mailto.mailto', 'mailto', array('load_data' => $loadData));

		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  array  The default data is an empty array.
	 *
	 * @since   3.8.9
	 */
	protected function loadFormData()
	{
		$user = JFactory::getUser();
		$app  = JFactory::getApplication();
		$data = $app->getUserState('mailto.mailto.form.data', array());

		$data['link'] = urldecode($app->input->get('link', '', 'BASE64'));

		if ($data['link'] == '')
		{
			JError::raiseError(403, JText::_('COM_MAILTO_LINK_IS_MISSING'));

			return false;
		}

		// Load with previous data, if it exists
		$data['sender']    = $app->input->post->getString('sender', '');
		$data['subject']   = $app->input->post->getString('subject', '');
		$data['emailfrom'] = JStringPunycode::emailToPunycode($app->input->post->getString('emailfrom', ''));
		$data['emailto']   = JStringPunycode::emailToPunycode($app->input->post->getString('emailto', ''));

		if (!$user->guest)
		{
			$data['sender']    = $user->name;
			$data['emailfrom'] = $user->email;
		}

		$app->setUserState('mailto.mailto.form.data', $data);

		$this->preprocessData('com_mailto.mailto', $data);

		return $data;
	}

	/**
	 * Get the request data
	 *
	 * @return  array  The requested data
	 *
	 * @since   3.8.9
	 */
	public function getData()
	{
		$input = JFactory::getApplication()->input;

		$data['emailto']    = $input->get('emailto', '', 'string');
		$data['sender']     = $input->get('sender', '', 'string');
		$data['emailfrom']  = $input->get('emailfrom', '', 'string');
		$data['subject']    = $input->get('subject', '', 'string');
		$data['consentbox'] = $input->get('consentbox', '', 'string');

		return $data;
	}
}
forms/mailto.xml000060400000001447152456112370007711 0ustar00<?xml version="1.0" encoding="utf-8" ?>
<form>
	<fieldset name="default">
		<field
			name="emailto"
			type="email"
			label="COM_MAILTO_EMAIL_TO"
			filter="string"
			required="true"
			size="30"
			validate="email"
			autocomplete="email"
		/>

		<field
			name="sender"
			type="text"
			label="COM_MAILTO_SENDER"
			filter="string"
			required="true"
			size="30"
		/>

		<field
			name="emailfrom"
			type="email"
			label="COM_MAILTO_YOUR_EMAIL"
			filter="string"
			required="true"
			size="30"
			validate="email"
			autocomplete="email"
		/>

		<field
			name="subject"
			type="text"
			label="COM_MAILTO_SUBJECT"
			filter="string"
			required="true"
			size="30"
		/>

		<field
			name="captcha"
			type="captcha"
			label="COM_MAILTO_CAPTCHA"
			validate="captcha"
		/>
	</fieldset>
</form>
forms/advanced.xml000060400000002050152456151500010156 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fields name="params">
		<fieldset
			name="advanced">

			<field
				name="module_tag"
				type="moduletag"
				label="COM_MODULES_FIELD_MODULE_TAG_LABEL"
				description="COM_MODULES_FIELD_MODULE_TAG_DESC"
				default="div"
				validate="options"
			/>

			<field
				name="bootstrap_size"
				type="integer"
				label="COM_MODULES_FIELD_BOOTSTRAP_SIZE_LABEL"
				description="COM_MODULES_FIELD_BOOTSTRAP_SIZE_DESC"
				first="0"
				last="12"
				step="1"
			/>

			<field
				name="header_tag"
				type="headertag"
				label="COM_MODULES_FIELD_HEADER_TAG_LABEL"
				description="COM_MODULES_FIELD_HEADER_TAG_DESC"
				default="h3"
				validate="options"
			/>

			<field
				name="header_class"
				type="text"
				label="COM_MODULES_FIELD_HEADER_CLASS_LABEL"
				description="COM_MODULES_FIELD_HEADER_CLASS_DESC"
			/>

			<field
				name="style"
				type="chromestyle"
				label="COM_MODULES_FIELD_MODULE_STYLE_LABEL"
				description="COM_MODULES_FIELD_MODULE_STYLE_DESC"
			/>
		</fieldset>
	</fields>
</form>
forms/module.xml000060400000006371152456151500007710 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field 
			name="id" 
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			default="0"
			readonly="true"
		/>

		<field 
			name="title" 
			type="text"
			label="JGLOBAL_TITLE"
			description="COM_MODULES_FIELD_TITLE_DESC"
			class="input-xxlarge input-large-text"
			size="40"
			maxlength="100"
			required="true"
		/>

		<field 
			name="note" 
			type="text"
			label="COM_MODULES_FIELD_NOTE_LABEL"
			description="COM_MODULES_FIELD_NOTE_DESC"
			maxlength="255"
			size="40"
			class="span12"
		/>

		<field 
			name="module" 
			type="hidden"
			label="COM_MODULES_FIELD_MODULE_LABEL"
			description="COM_MODULES_FIELD_MODULE_DESC"
			readonly="readonly"
			size="20"
		/>

		<field 
			name="showtitle" 
			type="radio"
			label="COM_MODULES_FIELD_SHOWTITLE_LABEL"
			description="COM_MODULES_FIELD_SHOWTITLE_DESC"
			class="btn-group btn-group-yesno"
			default="1"
			size="1"
			>
			<option value="1">JSHOW</option>
			<option value="0">JHIDE</option>
		</field>

		<field 
			name="published" 
			type="list"
			label="JSTATUS"
			description="COM_MODULES_FIELD_PUBLISHED_DESC"
			class="chzn-color-state"
			default="1"
			size="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="-2">JTRASHED</option>
		</field>

		<field
			name="publish_up"
			type="calendar"
			label="COM_MODULES_FIELD_PUBLISH_UP_LABEL"
			description="COM_MODULES_FIELD_PUBLISH_UP_DESC"
			filter="user_utc"
			translateformat="true"
			showtime="true"
			size="22"
		/>

		<field
			name="publish_down"
			type="calendar"
			label="COM_MODULES_FIELD_PUBLISH_DOWN_LABEL"
			description="COM_MODULES_FIELD_PUBLISH_DOWN_DESC"
			filter="user_utc"
			translateformat="true"
			showtime="true"
			size="22"
		/>

		<field 
			name="client_id" 
			type="hidden"
			label="COM_MODULES_FIELD_CLIENT_ID_LABEL"
			description="COM_MODULES_FIELD_CLIENT_ID_DESC"
			readonly="true"
			size="1"
		/>

		<field 
			name="position" 
			type="moduleposition"
			label="COM_MODULES_FIELD_POSITION_LABEL"
			description="COM_MODULES_FIELD_POSITION_DESC"
			default=""
			maxlength="50"
		/>

		<field 
			name="access" 
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="JFIELD_ACCESS_DESC"
			size="1"
		/>

		<field 
			name="ordering" 
			type="moduleorder"
			label="JFIELD_ORDERING_LABEL"
			description="JFIELD_ORDERING_DESC"
			linked="position"
		/>

		<field 
			name="content" 
			type="editor"
			label="COM_MODULES_FIELD_CONTENT_LABEL"
			description="COM_MODULES_FIELD_CONTENT_DESC"
			buttons="true"
			filter="JComponentHelper::filterText"
			hide="readmore,pagebreak,module"
		/>

		<field 
			name="language" 
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="JFIELD_MODULE_LANGUAGE_DESC"
			>
			<option value="*">JALL</option>
		</field>

		<field 
			name="assignment" 
			type="hidden"
		/>

		<field 
			name="assigned" 
			type="hidden"
		/>

		<field 
			name="asset_id" 
			type="hidden"
			filter="unset"
		/>

		<field 
			name="rules" 
			type="rules"
			label="JFIELD_RULES_LABEL"
			translate_label="false"
			filter="rules"
			component="com_modules"
			section="module"
			validate="rules"
		/>
	</fieldset>
</form>
forms/moduleadmin.xml000060400000006375152456151500010725 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset>
		<field 
			name="id" 
			type="number"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			default="0"
			readonly="true"
		/>

		<field 
			name="title" 
			type="text"
			label="JGLOBAL_TITLE"
			description="COM_MODULES_FIELD_TITLE_DESC"
			class="input-xxlarge input-large-text"
			size="40"
			maxlength="100"
			required="true"
		/>

		<field 
			name="note" 
			type="text"
			label="COM_MODULES_FIELD_NOTE_LABEL"
			description="COM_MODULES_FIELD_NOTE_DESC"
			maxlength="255"
			size="40"
			class="span12"
		/>

		<field 
			name="module" 
			type="hidden"
			label="COM_MODULES_FIELD_MODULE_LABEL"
			description="COM_MODULES_FIELD_MODULE_DESC"
			readonly="readonly"
			size="20"
		/>

		<field 
			name="showtitle" 
			type="radio"
			label="COM_MODULES_FIELD_SHOWTITLE_LABEL"
			description="COM_MODULES_FIELD_SHOWTITLE_DESC"
			class="btn-group btn-group-yesno"
			default="1"
			size="1"
			>
			<option value="1">JSHOW</option>
			<option value="0">JHIDE</option>
		</field>

		<field 
			name="published" 
			type="list"
			label="JSTATUS"
			description="COM_MODULES_FIELD_PUBLISHED_DESC"
			class="chzn-color-state"
			default="1"
			size="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="-2">JTRASHED</option>
		</field>

		<field
			name="publish_up"
			type="calendar"
			label="COM_MODULES_FIELD_PUBLISH_UP_LABEL"
			description="COM_MODULES_FIELD_PUBLISH_UP_DESC"
			filter="user_utc"
			translateformat="true"
			showtime="true"
			size="22"
		/>

		<field
			name="publish_down"
			type="calendar"
			label="COM_MODULES_FIELD_PUBLISH_DOWN_LABEL"
			description="COM_MODULES_FIELD_PUBLISH_DOWN_DESC"
			filter="user_utc"
			translateformat="true"
			showtime="true"
			size="22"
		/>

		<field 
			name="client_id" 
			type="hidden"
			label="COM_MODULES_FIELD_CLIENT_ID_LABEL"
			description="COM_MODULES_FIELD_CLIENT_ID_DESC"
			readonly="true"
			size="1"
		/>

		<field 
			name="position" 
			type="moduleposition"
			label="COM_MODULES_FIELD_POSITION_LABEL"
			description="COM_MODULES_FIELD_POSITION_DESC"
			default=""
			maxlength="50"
		/>

		<field 
			name="access" 
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="JFIELD_ACCESS_DESC"
			size="1"
		/>

		<field 
			name="ordering" 
			type="moduleorder"
			label="JFIELD_ORDERING_LABEL"
			description="JFIELD_ORDERING_DESC"
			linked="position"
		/>

		<field
			name="language"
			type="language"
			label="JFIELD_LANGUAGE_LABEL"
			description="JFIELD_MODULE_LANGUAGE_DESC"
			default="*"
			client="administrator"
			>
			<option value="*">JALL</option>
		</field>

		<field 
			name="content" 
			type="editor"
			label="COM_MODULES_FIELD_CONTENT_LABEL"
			description="COM_MODULES_FIELD_CONTENT_DESC"
			buttons="true"
			filter="JComponentHelper::filterText"
			hide="readmore,pagebreak,module"
		/>

		<field name="assignment" type="hidden" />

		<field name="assigned" type="hidden" />

		<field name="asset_id" type="hidden"
			filter="unset"
		/>

		<field 
			name="rules" 
			type="rules"
			label="JFIELD_RULES_LABEL"
			translate_label="false"
			filter="rules"
			component="com_modules"
			section="module"
			validate="rules"
		/>
	</fieldset>
</form>
forms/filter_modulesadmin.xml000060400000006601152456151500012445 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_modules/models/fields" />

	<field
		name="client_id"
		type="list"
		label=""
		filtermode="selector"
		layout="default"
		onchange="jQuery('#filter_position, #filter_module, #filter_language').val('');this.form.submit();"
		>
		<option value="0">JSITE</option>
		<option value="1">JADMINISTRATOR</option>
	</field>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_MODULES_MODULES_FILTER_SEARCH_LABEL"
			description="COM_MODULES_MODULES_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
			noresults="COM_MODULES_MSG_MANAGE_NO_MODULES"
		/>
		<field
			name="state"
			type="status"
			label="JSTATUS"
			filter="*,-2,0,1"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>
		<field
			name="position"
			type="modulesposition"
			label="COM_MODULES_FIELD_POSITION_LABEL"
			onchange="this.form.submit();"
			>
			<option value="">COM_MODULES_OPTION_SELECT_POSITION</option>
		</field>
		<field
			name="module"
			type="ModulesModule"
			label="COM_MODULES_OPTION_SELECT_MODULE"
			onchange="this.form.submit();"
			>
			<option value="">COM_MODULES_OPTION_SELECT_MODULE</option>
		</field>
		<field
			name="access"
			type="accesslevel"
			label="JOPTION_FILTER_ACCESS"
			description="JOPTION_FILTER_ACCESS_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_ACCESS</option>
		</field>
		<field
			name="language"
			type="language"
			label="JOPTION_FILTER_LANGUAGE"
			description="JOPTION_FILTER_LANGUAGE_DESC"
			client="administrator"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_LANGUAGE</option>
			<option value="*">JALL</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			statuses="*,0,1,-2"
			onchange="this.form.submit();"
			default="a.position ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.ordering ASC">JGRID_HEADING_ORDERING_ASC</option>
			<option value="a.ordering DESC">JGRID_HEADING_ORDERING_DESC</option>
			<option value="a.published ASC">JSTATUS_ASC</option>
			<option value="a.published DESC">JSTATUS_DESC</option>
			<option value="a.title ASC">JGLOBAL_TITLE_ASC</option>
			<option value="a.title DESC">JGLOBAL_TITLE_DESC</option>
			<option value="a.position ASC">COM_MODULES_HEADING_POSITION_ASC</option>
			<option value="a.position DESC">COM_MODULES_HEADING_POSITION_DESC</option>
			<option value="name ASC">COM_MODULES_HEADING_MODULE_ASC</option>
			<option value="name DESC">COM_MODULES_HEADING_MODULE_DESC</option>
			<option value="ag.title ASC">JGRID_HEADING_ACCESS_ASC</option>
			<option value="ag.title DESC">JGRID_HEADING_ACCESS_DESC</option>
			<option value="a.language ASC" requires="adminlanguage">JGRID_HEADING_LANGUAGE_ASC</option>
			<option value="a.language DESC" requires="adminlanguage">JGRID_HEADING_LANGUAGE_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="COM_MODULES_LIST_LIMIT"
			description="JFIELD_PLG_SEARCH_SEARCHLIMIT_DESC"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
module.php000060400000066721152456151500006556 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_modules
 *
 * @copyright   (C) 2007 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;

/**
 * Module model.
 *
 * @since  1.6
 */
class ModulesModelModule extends JModelAdmin
{
	/**
	 * The type alias for this content type.
	 *
	 * @var      string
	 * @since    3.4
	 */
	public $typeAlias = 'com_modules.module';

	/**
	 * @var    string  The prefix to use with controller messages.
	 * @since  1.6
	 */
	protected $text_prefix = 'COM_MODULES';

	/**
	 * @var    string  The help screen key for the module.
	 * @since  1.6
	 */
	protected $helpKey = 'JHELP_EXTENSIONS_MODULE_MANAGER_EDIT';

	/**
	 * @var    string  The help screen base URL for the module.
	 * @since  1.6
	 */
	protected $helpURL;

	/**
	 * Batch copy/move command. If set to false,
	 * the batch copy/move command is not supported
	 *
	 * @var string
	 */
	protected $batch_copymove = 'position_id';

	/**
	 * Allowed batch commands
	 *
	 * @var array
	 */
	protected $batch_commands = array(
		'assetgroup_id' => 'batchAccess',
		'language_id' => 'batchLanguage',
	);

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 */
	public function __construct($config = array())
	{
		$config = array_merge(
			array(
				'event_after_delete'  => 'onExtensionAfterDelete',
				'event_after_save'    => 'onExtensionAfterSave',
				'event_before_delete' => 'onExtensionBeforeDelete',
				'event_before_save'   => 'onExtensionBeforeSave',
				'events_map'          => array(
					'save'   => 'extension',
					'delete' => 'extension'
				)
			), $config
		);

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication('administrator');

		// Load the User state.
		$pk = $app->input->getInt('id');

		if (!$pk)
		{
			if ($extensionId = (int) $app->getUserState('com_modules.add.module.extension_id'))
			{
				$this->setState('extension.id', $extensionId);
			}
		}

		$this->setState('module.id', $pk);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_modules');
		$this->setState('params', $params);
	}

	/**
	 * Batch copy modules to a new position or current.
	 *
	 * @param   integer  $value     The new value matching a module position.
	 * @param   array    $pks       An array of row IDs.
	 * @param   array    $contexts  An array of item contexts.
	 *
	 * @return  boolean  True if successful, false otherwise and internal error is set.
	 *
	 * @since   2.5
	 */
	protected function batchCopy($value, $pks, $contexts)
	{
		// Set the variables
		$user = JFactory::getUser();
		$table = $this->getTable();
		$newIds = array();

		foreach ($pks as $pk)
		{
			if ($user->authorise('core.create', 'com_modules'))
			{
				$table->reset();
				$table->load($pk);

				// Set the new position
				if ($value == 'noposition')
				{
					$position = '';
				}
				elseif ($value == 'nochange')
				{
					$position = $table->position;
				}
				else
				{
					$position = $value;
				}

				$table->position = $position;

				// Copy of the Asset ID
				$oldAssetId = $table->asset_id;

				// Alter the title if necessary
				$data = $this->generateNewTitle(0, $table->title, $table->position);
				$table->title = $data['0'];

				// Reset the ID because we are making a copy
				$table->id = 0;

				// Unpublish the new module
				$table->published = 0;

				if (!$table->store())
				{
					$this->setError($table->getError());

					return false;
				}

				// Get the new item ID
				$newId = $table->get('id');

				// Add the new ID to the array
				$newIds[$pk] = $newId;

				// Now we need to handle the module assignments
				$db = $this->getDbo();
				$query = $db->getQuery(true)
					->select($db->quoteName('menuid'))
					->from($db->quoteName('#__modules_menu'))
					->where($db->quoteName('moduleid') . ' = ' . $pk);
				$db->setQuery($query);
				$menus = $db->loadColumn();

				// Insert the new records into the table
				foreach ($menus as $menu)
				{
					$query->clear()
						->insert($db->quoteName('#__modules_menu'))
						->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid')))
						->values($newId . ', ' . $menu);
					$db->setQuery($query);
					$db->execute();
				}

				// Copy rules
				$query->clear()
					->update($db->quoteName('#__assets', 't'))
					->join('INNER', $db->quoteName('#__assets', 's') .
						' ON ' . $db->quoteName('s.id') . ' = ' . $oldAssetId
					)
					->set($db->quoteName('t.rules') . ' = ' . $db->quoteName('s.rules'))
					->where($db->quoteName('t.id') . ' = ' . $table->asset_id);

				$db->setQuery($query)->execute();
			}
			else
			{
				$this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_CREATE'));

				return false;
			}
		}

		// Clean the cache
		$this->cleanCache();

		return $newIds;
	}

	/**
	 * Batch move modules to a new position or current.
	 *
	 * @param   integer  $value     The new value matching a module position.
	 * @param   array    $pks       An array of row IDs.
	 * @param   array    $contexts  An array of item contexts.
	 *
	 * @return  boolean  True if successful, false otherwise and internal error is set.
	 *
	 * @since   2.5
	 */
	protected function batchMove($value, $pks, $contexts)
	{
		// Set the variables
		$user = JFactory::getUser();
		$table = $this->getTable();

		foreach ($pks as $pk)
		{
			if ($user->authorise('core.edit', 'com_modules'))
			{
				$table->reset();
				$table->load($pk);

				// Set the new position
				if ($value == 'noposition')
				{
					$position = '';
				}
				elseif ($value == 'nochange')
				{
					$position = $table->position;
				}
				else
				{
					$position = $value;
				}

				$table->position = $position;

				if (!$table->store())
				{
					$this->setError($table->getError());

					return false;
				}
			}
			else
			{
				$this->setError(JText::_('JLIB_APPLICATION_ERROR_BATCH_CANNOT_EDIT'));

				return false;
			}
		}

		// Clean the cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to test whether a record can have its state edited.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission set in the component.
	 *
	 * @since   3.2
	 */
	protected function canEditState($record)
	{
		// Check for existing module.
		if (!empty($record->id))
		{
			return JFactory::getUser()->authorise('core.edit.state', 'com_modules.module.' . (int) $record->id);
		}

		// Default to component settings if module not known.
		return parent::canEditState($record);
	}

	/**
	 * Method to delete rows.
	 *
	 * @param   array  &$pks  An array of item ids.
	 *
	 * @return  boolean  Returns true on success, false on failure.
	 *
	 * @since   1.6
	 * @throws  Exception
	 */
	public function delete(&$pks)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$pks        = (array) $pks;
		$user       = JFactory::getUser();
		$table      = $this->getTable();
		$context    = $this->option . '.' . $this->name;

		// Include the plugins for the on delete events.
		JPluginHelper::importPlugin($this->events_map['delete']);

		// Iterate the items to delete each one.
		foreach ($pks as $pk)
		{
			if ($table->load($pk))
			{
				// Access checks.
				if (!$user->authorise('core.delete', 'com_modules.module.' . (int) $pk) || $table->published != -2)
				{
					JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));

					return;
				}

				// Trigger the before delete event.
				$result = $dispatcher->trigger($this->event_before_delete, array($context, $table));

				if (in_array(false, $result, true) || !$table->delete($pk))
				{
					throw new Exception($table->getError());
				}
				else
				{
					// Delete the menu assignments
					$db    = $this->getDbo();
					$query = $db->getQuery(true)
						->delete('#__modules_menu')
						->where('moduleid=' . (int) $pk);
					$db->setQuery($query);
					$db->execute();

					// Trigger the after delete event.
					$dispatcher->trigger($this->event_after_delete, array($context, $table));
				}

				// Clear module cache
				parent::cleanCache($table->module, $table->client_id);
			}
			else
			{
				throw new Exception($table->getError());
			}
		}

		// Clear modules cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to duplicate modules.
	 *
	 * @param   array  &$pks  An array of primary key IDs.
	 *
	 * @return  boolean|JException  Boolean true on success, JException instance on error
	 *
	 * @since   1.6
	 * @throws  Exception
	 */
	public function duplicate(&$pks)
	{
		$user = JFactory::getUser();
		$db   = $this->getDbo();

		// Access checks.
		if (!$user->authorise('core.create', 'com_modules'))
		{
			throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
		}

		$table = $this->getTable();

		foreach ($pks as $pk)
		{
			if ($table->load($pk, true))
			{
				// Reset the id to create a new record.
				$table->id = 0;

				// Alter the title.
				$m = null;

				if (preg_match('#\((\d+)\)$#', $table->title, $m))
				{
					$table->title = preg_replace('#\(\d+\)$#', '(' . ($m[1] + 1) . ')', $table->title);
				}

				$data = $this->generateNewTitle(0, $table->title, $table->position);
				$table->title = $data[0];

				// Unpublish duplicate module
				$table->published = 0;

				if (!$table->check() || !$table->store())
				{
					throw new Exception($table->getError());
				}

				$query = $db->getQuery(true)
					->select($db->quoteName('menuid'))
					->from($db->quoteName('#__modules_menu'))
					->where($db->quoteName('moduleid') . ' = ' . (int) $pk);

				$db->setQuery($query);
				$rows = $db->loadColumn();

				foreach ($rows as $menuid)
				{
					$tuples[] = (int) $table->id . ',' . (int) $menuid;
				}
			}
			else
			{
				throw new Exception($table->getError());
			}
		}

		if (!empty($tuples))
		{
			// Module-Menu Mapping: Do it in one query
			$query = $db->getQuery(true)
				->insert($db->quoteName('#__modules_menu'))
				->columns($db->quoteName(array('moduleid', 'menuid')))
				->values($tuples);

			$db->setQuery($query);

			try
			{
				$db->execute();
			}
			catch (RuntimeException $e)
			{
				return JError::raiseWarning(500, $e->getMessage());
			}
		}

		// Clear modules cache
		$this->cleanCache();

		return true;
	}

	/**
	 * Method to change the title.
	 *
	 * @param   integer  $categoryId  The id of the category. Not used here.
	 * @param   string   $title       The title.
	 * @param   string   $position    The position.
	 *
	 * @return  array  Contains the modified title.
	 *
	 * @since   2.5
	 */
	protected function generateNewTitle($categoryId, $title, $position)
	{
		// Alter the title & alias
		$table = $this->getTable();

		while ($table->load(array('position' => $position, 'title' => $title)))
		{
			$title = StringHelper::increment($title);
		}

		return array($title);
	}

	/**
	 * Method to get the client object
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function &getClient()
	{
		return $this->_client;
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  JForm  A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// The folder and element vars are passed when saving the form.
		if (empty($data))
		{
			$item     = $this->getItem();
			$clientId = $item->client_id;
			$module   = $item->module;
			$id       = $item->id;
		}
		else
		{
			$clientId = ArrayHelper::getValue($data, 'client_id');
			$module   = ArrayHelper::getValue($data, 'module');
			$id       = ArrayHelper::getValue($data, 'id');
		}

		// Add the default fields directory
		$baseFolder = $clientId ? JPATH_ADMINISTRATOR : JPATH_SITE;
		JForm::addFieldPath($baseFolder . '/modules' . '/' . $module . '/field');

		// These variables are used to add data from the plugin XML files.
		$this->setState('item.client_id', $clientId);
		$this->setState('item.module', $module);

		// Get the form.
		if ($clientId == 1)
		{
			$form = $this->loadForm('com_modules.module.admin', 'moduleadmin', array('control' => 'jform', 'load_data' => $loadData), true);

			// Display language field to filter admin custom menus per language
			if (!JModuleHelper::isAdminMultilang())
			{
				$form->setFieldAttribute('language', 'type', 'hidden');
			}
		}
		else
		{
			$form = $this->loadForm('com_modules.module', 'module', array('control' => 'jform', 'load_data' => $loadData), true);
		}

		if (empty($form))
		{
			return false;
		}

		$form->setFieldAttribute('position', 'client', $this->getState('item.client_id') == 0 ? 'site' : 'administrator');

		$user = JFactory::getUser();

		/**
		 * Check for existing module
		 * Modify the form based on Edit State access controls.
		 */
		if ($id != 0 && (!$user->authorise('core.edit.state', 'com_modules.module.' . (int) $id))
			|| ($id == 0 && !$user->authorise('core.edit.state', 'com_modules'))		)
		{
			// Disable fields for display.
			$form->setFieldAttribute('ordering', 'disabled', 'true');
			$form->setFieldAttribute('published', 'disabled', 'true');
			$form->setFieldAttribute('publish_up', 'disabled', 'true');
			$form->setFieldAttribute('publish_down', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is a record you can edit.
			$form->setFieldAttribute('ordering', 'filter', 'unset');
			$form->setFieldAttribute('published', 'filter', 'unset');
			$form->setFieldAttribute('publish_up', 'filter', 'unset');
			$form->setFieldAttribute('publish_down', 'filter', 'unset');
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		$app = JFactory::getApplication();

		// Check the session for previously entered form data.
		$data = $app->getUserState('com_modules.edit.module.data', array());

		if (empty($data))
		{
			$data = $this->getItem();

			// Pre-select some filters (Status, Module Position, Language, Access Level) in edit form if those have been selected in Module Manager
			if (!$data->id)
			{
				$filters = (array) $app->getUserState('com_modules.modules.filter');
				$data->set('published', $app->input->getInt('published', ((isset($filters['state']) && $filters['state'] !== '') ? $filters['state'] : null)));
				$data->set('position', $app->input->getInt('position', (!empty($filters['position']) ? $filters['position'] : null)));
				$data->set('language', $app->input->getString('language', (!empty($filters['language']) ? $filters['language'] : null)));
				$data->set('access', $app->input->getInt('access', (!empty($filters['access']) ? $filters['access'] : JFactory::getConfig()->get('access'))));
			}

			// Avoid to delete params of a second module opened in a new browser tab while new one is not saved yet.
			if (empty($data->params))
			{
				// This allows us to inject parameter settings into a new module.
				$params = $app->getUserState('com_modules.add.module.params');

				if (is_array($params))
				{
					$data->set('params', $params);
				}
			}
		}

		$this->preprocessData('com_modules.module', $data);

		return $data;
	}

	/**
	 * Method to get a single record.
	 *
	 * @param   integer  $pk  The id of the primary key.
	 *
	 * @return  mixed  Object on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function getItem($pk = null)
	{
		$pk = (!empty($pk)) ? (int) $pk : (int) $this->getState('module.id');
		$db = $this->getDbo();

		if (!isset($this->_cache[$pk]))
		{
			// Get a row instance.
			$table = $this->getTable();

			// Attempt to load the row.
			$return = $table->load($pk);

			// Check for a table object error.
			if ($return === false && $error = $table->getError())
			{
				$this->setError($error);

				return false;
			}

			// Check if we are creating a new extension.
			if (empty($pk))
			{
				if ($extensionId = (int) $this->getState('extension.id'))
				{
					$query = $db->getQuery(true)
						->select('element, client_id')
						->from('#__extensions')
						->where('extension_id = ' . $extensionId)
						->where('type = ' . $db->quote('module'));
					$db->setQuery($query);

					try
					{
						$extension = $db->loadObject();
					}
					catch (RuntimeException $e)
					{
						$this->setError($e->getMessage());

						return false;
					}

					if (empty($extension))
					{
						$this->setError('COM_MODULES_ERROR_CANNOT_FIND_MODULE');

						return false;
					}

					// Extension found, prime some module values.
					$table->module    = $extension->element;
					$table->client_id = $extension->client_id;
				}
				else
				{
					JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_modules&view=modules', false));

					return false;
				}
			}

			// Convert to the JObject before adding other data.
			$properties        = $table->getProperties(1);
			$this->_cache[$pk] = ArrayHelper::toObject($properties, 'JObject');

			// Convert the params field to an array.
			$registry = new Registry($table->params);
			$this->_cache[$pk]->params = $registry->toArray();

			// Determine the page assignment mode.
			$query = $db->getQuery(true)
				->select($db->quoteName('menuid'))
				->from($db->quoteName('#__modules_menu'))
				->where($db->quoteName('moduleid') . ' = ' . (int) $pk);
			$db->setQuery($query);
			$assigned = $db->loadColumn();

			if (empty($pk))
			{
				// If this is a new module, assign to all pages.
				$assignment = 0;
			}
			elseif (empty($assigned))
			{
				// For an existing module it is assigned to none.
				$assignment = '-';
			}
			else
			{
				if ($assigned[0] > 0)
				{
					$assignment = 1;
				}
				elseif ($assigned[0] < 0)
				{
					$assignment = -1;
				}
				else
				{
					$assignment = 0;
				}
			}

			$this->_cache[$pk]->assigned   = $assigned;
			$this->_cache[$pk]->assignment = $assignment;

			// Get the module XML.
			$client = JApplicationHelper::getClientInfo($table->client_id);
			$path   = JPath::clean($client->path . '/modules/' . $table->module . '/' . $table->module . '.xml');

			if (file_exists($path))
			{
				$this->_cache[$pk]->xml = simplexml_load_file($path);
			}
			else
			{
				$this->_cache[$pk]->xml = null;
			}
		}

		return $this->_cache[$pk];
	}

	/**
	 * Get the necessary data to load an item help screen.
	 *
	 * @return  object  An object with key, url, and local properties for loading the item help screen.
	 *
	 * @since   1.6
	 */
	public function getHelp()
	{
		return (object) array('key' => $this->helpKey, 'url' => $this->helpURL);
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param   string  $type    The table type to instantiate
	 * @param   string  $prefix  A prefix for the table class name. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A database object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'Module', $prefix = 'JTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 *
	 * @param   JTable  $table  The database object
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function prepareTable($table)
	{
		$table->title    = htmlspecialchars_decode($table->title, ENT_QUOTES);
		$table->position = trim($table->position);
	}

	/**
	 * Method to preprocess the form
	 *
	 * @param   JForm   $form   A form object.
	 * @param   mixed   $data   The data expected for the form.
	 * @param   string  $group  The name of the plugin group to import (defaults to "content").
	 *
	 * @return  void
	 *
	 * @since   1.6
	 * @throws  Exception if there is an error loading the form.
	 */
	protected function preprocessForm(JForm $form, $data, $group = 'content')
	{
		jimport('joomla.filesystem.path');

		$lang     = JFactory::getLanguage();
		$clientId = $this->getState('item.client_id');
		$module   = $this->getState('item.module');

		$client   = JApplicationHelper::getClientInfo($clientId);
		$formFile = JPath::clean($client->path . '/modules/' . $module . '/' . $module . '.xml');

		// Load the core and/or local language file(s).
		$lang->load($module, $client->path, null, false, true)
		||	$lang->load($module, $client->path . '/modules/' . $module, null, false, true);

		if (file_exists($formFile))
		{
			// Get the module form.
			if (!$form->loadFile($formFile, false, '//config'))
			{
				throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
			}

			// Attempt to load the xml file.
			if (!$xml = simplexml_load_file($formFile))
			{
				throw new Exception(JText::_('JERROR_LOADFILE_FAILED'));
			}

			// Get the help data from the XML file if present.
			$help = $xml->xpath('/extension/help');

			if (!empty($help))
			{
				$helpKey = trim((string) $help[0]['key']);
				$helpURL = trim((string) $help[0]['url']);

				$this->helpKey = $helpKey ?: $this->helpKey;
				$this->helpURL = $helpURL ?: $this->helpURL;
			}
		}

		// Load the default advanced params
		JForm::addFormPath(JPATH_ADMINISTRATOR . '/components/com_modules/models/forms');
		$form->loadFile('advanced', false);

		// Trigger the default form events.
		parent::preprocessForm($form, $data, $group);
	}

	/**
	 * Loads ContentHelper for filters before validating data.
	 *
	 * @param   object  $form   The form to validate against.
	 * @param   array   $data   The data to validate.
	 * @param   string  $group  The name of the group(defaults to null).
	 *
	 * @return  mixed  Array of filtered data if valid, false otherwise.
	 *
	 * @since   1.1
	 */
	public function validate($form, $data, $group = null)
	{
		JLoader::register('ContentHelper', JPATH_ADMINISTRATOR . '/components/com_content/helpers/content.php');

		if (!JFactory::getUser()->authorise('core.admin', 'com_modules'))
		{
			if (isset($data['rules']))
			{
				unset($data['rules']);
			}
		}

		return parent::validate($form, $data, $group);
	}

	/**
	 * Method to save the form data.
	 *
	 * @param   array  $data  The form data.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   1.6
	 */
	public function save($data)
	{
		$dispatcher = JEventDispatcher::getInstance();
		$input      = JFactory::getApplication()->input;
		$table      = $this->getTable();
		$pk         = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('module.id');
		$isNew      = true;
		$context    = $this->option . '.' . $this->name;

		// Include the plugins for the save event.
		JPluginHelper::importPlugin($this->events_map['save']);

		// Load the row if saving an existing record.
		if ($pk > 0)
		{
			$table->load($pk);
			$isNew = false;
		}

		// Alter the title and published state for Save as Copy
		if ($input->get('task') == 'save2copy')
		{
			$orig_table = clone $this->getTable();
			$orig_table->load((int) $input->getInt('id'));
			$data['published'] = 0;

			if ($data['title'] == $orig_table->title)
			{
				$data['title'] = StringHelper::increment($data['title']);
			}
		}

		// Bind the data.
		if (!$table->bind($data))
		{
			$this->setError($table->getError());

			return false;
		}

		// Prepare the row for saving
		$this->prepareTable($table);

		// Check the data.
		if (!$table->check())
		{
			$this->setError($table->getError());

			return false;
		}

		// Trigger the before save event.
		$result = $dispatcher->trigger($this->event_before_save, array($context, &$table, $isNew));

		if (in_array(false, $result, true))
		{
			$this->setError($table->getError());

			return false;
		}

		// Store the data.
		if (!$table->store())
		{
			$this->setError($table->getError());

			return false;
		}

		// Process the menu link mappings.
		$assignment = isset($data['assignment']) ? $data['assignment'] : 0;

		// Delete old module to menu item associations
		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->delete('#__modules_menu')
			->where('moduleid = ' . (int) $table->id);
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		// If the assignment is numeric, then something is selected (otherwise it's none).
		if (is_numeric($assignment))
		{
			// Variable is numeric, but could be a string.
			$assignment = (int) $assignment;

			// Logic check: if no module excluded then convert to display on all.
			if ($assignment == -1 && empty($data['assigned']))
			{
				$assignment = 0;
			}

			// Check needed to stop a module being assigned to `All`
			// and other menu items resulting in a module being displayed twice.
			if ($assignment === 0)
			{
				// Assign new module to `all` menu item associations.
				$query->clear()
					->insert('#__modules_menu')
					->columns(array($db->quoteName('moduleid'), $db->quoteName('menuid')))
					->values((int) $table->id . ', 0');
				$db->setQuery($query);

				try
				{
					$db->execute();
				}
				catch (RuntimeException $e)
				{
					$this->setError($e->getMessage());

					return false;
				}
			}
			elseif (!empty($data['assigned']))
			{
				// Get the sign of the number.
				$sign = $assignment < 0 ? -1 : 1;

				$query->clear()
					->insert($db->quoteName('#__modules_menu'))
					->columns($db->quoteName(array('moduleid', 'menuid')));

				foreach ($data['assigned'] as &$pk)
				{
					$query->values((int) $table->id . ',' . (int) $pk * $sign);
				}

				$db->setQuery($query);

				try
				{
					$db->execute();
				}
				catch (RuntimeException $e)
				{
					$this->setError($e->getMessage());

					return false;
				}
			}
		}

		// Trigger the after save event.
		$dispatcher->trigger($this->event_after_save, array($context, &$table, $isNew));

		// Compute the extension id of this module in case the controller wants it.
		$query->clear()
			->select($db->quoteName('extension_id'))
			->from($db->quoteName('#__extensions', 'e'))
			->join(
				'LEFT',
				$db->quoteName('#__modules', 'm') . ' ON ' . $db->quoteName('e.client_id') . ' = ' . (int) $table->client_id .
				' AND ' . $db->quoteName('e.element') . ' = ' . $db->quoteName('m.module')
			)
			->where($db->quoteName('m.id') . ' = ' . (int) $table->id);
		$db->setQuery($query);

		try
		{
			$extensionId = $db->loadResult();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $e->getMessage());

			return false;
		}

		$this->setState('module.extension_id', $extensionId);
		$this->setState('module.id', $table->id);

		// Clear modules cache
		$this->cleanCache();

		// Clean module cache
		parent::cleanCache($table->module, $table->client_id);

		return true;
	}

	/**
	 * A protected method to get a set of ordering conditions.
	 *
	 * @param   object  $table  A record object.
	 *
	 * @return  array  An array of conditions to add to add to ordering queries.
	 *
	 * @since   1.6
	 */
	protected function getReorderConditions($table)
	{
		$condition = array();
		$condition[] = 'client_id = ' . (int) $table->client_id;
		$condition[] = 'position = ' . $this->_db->quote($table->position);

		return $condition;
	}

	/**
	 * Custom clean cache method for different clients
	 *
	 * @param   string   $group     The name of the plugin group to import (defaults to null).
	 * @param   integer  $clientId  The client ID. [optional]
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function cleanCache($group = null, $clientId = 0)
	{
		parent::cleanCache('com_modules', $this->getClient());
	}
}
modules.php000060400000032241152456151500006727 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_modules
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;

/**
 * Modules Component Module Model
 *
 * @since  1.5
 */
class ModulesModelModules extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'title', 'a.title',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'published', 'a.published', 'state',
				'access', 'a.access',
				'ag.title', 'access_level',
				'ordering', 'a.ordering',
				'module', 'a.module',
				'language', 'a.language',
				'l.title', 'language_title',
				'publish_up', 'a.publish_up',
				'publish_down', 'a.publish_down',
				'client_id', 'a.client_id',
				'position', 'a.position',
				'pages',
				'name', 'e.name',
				'menuitem',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'a.position', $direction = 'asc')
	{
		$app = JFactory::getApplication();

		$layout = $app->input->get('layout', '', 'cmd');

		// Adjust the context to support modal layouts.
		if ($layout)
		{
			$this->context .= '.' . $layout;
		}

		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.position', $this->getUserStateFromRequest($this->context . '.filter.position', 'filter_position', '', 'string'));
		$this->setState('filter.module', $this->getUserStateFromRequest($this->context . '.filter.module', 'filter_module', '', 'string'));
		$this->setState('filter.menuitem', $this->getUserStateFromRequest($this->context . '.filter.menuitem', 'filter_menuitem', '', 'cmd'));
		$this->setState('filter.access', $this->getUserStateFromRequest($this->context . '.filter.access', 'filter_access', '', 'cmd'));

		// If in modal layout on the frontend, state and language are always forced.
		if ($app->isClient('site') && $layout === 'modal')
		{
			$this->setState('filter.language', 'current');
			$this->setState('filter.state', 1);
		}
		// If in backend (modal or not) we get the same fields from the user request.
		else
		{
			$this->setState('filter.language', $this->getUserStateFromRequest($this->context . '.filter.language', 'filter_language', '', 'string'));
			$this->setState('filter.state', $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'string'));
		}

		// Special case for the client id.
		if ($app->isClient('site') || $layout === 'modal')
		{
			$this->setState('client_id', 0);
			$clientId = 0;
		}
		else
		{
			$clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int');
			$clientId = (!in_array($clientId, array (0, 1))) ? 0 : $clientId;
			$this->setState('client_id', $clientId);
		}

		// Use a different filter file when client is administrator
		if ($clientId == 1)
		{
			$this->filterFormName = 'filter_modulesadmin';
		}

		// Load the parameters.
		$params = JComponentHelper::getParams('com_modules');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string    A store id.
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('client_id');
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.state');
		$id .= ':' . $this->getState('filter.position');
		$id .= ':' . $this->getState('filter.module');
		$id .= ':' . $this->getState('filter.menuitem');
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.language');

		return parent::getStoreId($id);
	}

	/**
	 * Returns an object list
	 *
	 * @param   string  $query       The query
	 * @param   int     $limitstart  Offset
	 * @param   int     $limit       The number of records
	 *
	 * @return  array
	 */
	protected function _getList($query, $limitstart = 0, $limit = 0)
	{
		$listOrder = $this->getState('list.ordering', 'a.position');
		$listDirn  = $this->getState('list.direction', 'asc');

		// If ordering by fields that need translate we need to sort the array of objects after translating them.
		if (in_array($listOrder, array('pages', 'name')))
		{
			// Fetch the results.
			$this->_db->setQuery($query);
			$result = $this->_db->loadObjectList();

			// Translate the results.
			$this->translate($result);

			// Sort the array of translated objects.
			$result = ArrayHelper::sortObjects($result, $listOrder, strtolower($listDirn) == 'desc' ? -1 : 1, true, true);

			// Process pagination.
			$total = count($result);
			$this->cache[$this->getStoreId('getTotal')] = $total;

			if ($total < $limitstart)
			{
				$limitstart = 0;
				$this->setState('list.start', 0);
			}

			return array_slice($result, $limitstart, $limit ?: null);
		}

		// If ordering by fields that doesn't need translate just order the query.
		if ($listOrder === 'a.ordering')
		{
			$query->order($this->_db->quoteName('a.position') . ' ASC')
				->order($this->_db->quoteName($listOrder) . ' ' . $this->_db->escape($listDirn));
		}
		elseif ($listOrder === 'a.position')
		{
			$query->order($this->_db->quoteName($listOrder) . ' ' . $this->_db->escape($listDirn))
				->order($this->_db->quoteName('a.ordering') . ' ASC');
		}
		else
		{
			$query->order($this->_db->quoteName($listOrder) . ' ' . $this->_db->escape($listDirn));
		}

		// Process pagination.
		$result = parent::_getList($query, $limitstart, $limit);

		// Translate the results.
		$this->translate($result);

		return $result;
	}

	/**
	 * Translate a list of objects
	 *
	 * @param   array  &$items  The array of objects
	 *
	 * @return  array The array of translated objects
	 */
	protected function translate(&$items)
	{
		$lang = JFactory::getLanguage();
		$clientPath = $this->getState('client_id') ? JPATH_ADMINISTRATOR : JPATH_SITE;

		foreach ($items as $item)
		{
			$extension = $item->module;
			$source = $clientPath . "/modules/$extension";
			$lang->load("$extension.sys", $clientPath, null, false, true)
				|| $lang->load("$extension.sys", $source, null, false, true);
			$item->name = JText::_($item->name);

			if (is_null($item->pages))
			{
				$item->pages = JText::_('JNONE');
			}
			elseif ($item->pages < 0)
			{
				$item->pages = JText::_('COM_MODULES_ASSIGNED_VARIES_EXCEPT');
			}
			elseif ($item->pages > 0)
			{
				$item->pages = JText::_('COM_MODULES_ASSIGNED_VARIES_ONLY');
			}
			else
			{
				$item->pages = JText::_('JALL');
			}
		}
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 */
	protected function getListQuery()
	{
		$app = JFactory::getApplication();

		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields.
		$query->select(
			$this->getState(
				'list.select',
				'a.id, a.title, a.note, a.position, a.module, a.language,' .
					'a.checked_out, a.checked_out_time, a.published AS published, e.enabled AS enabled, a.access, a.ordering, a.publish_up, a.publish_down'
			)
		);

		// From modules table.
		$query->from($db->quoteName('#__modules', 'a'));

		// Join over the language
		$query->select($db->quoteName('l.title', 'language_title'))
			->select($db->quoteName('l.image', 'language_image'))
			->join('LEFT', $db->quoteName('#__languages', 'l') . ' ON ' . $db->quoteName('l.lang_code') . ' = ' . $db->quoteName('a.language'));

		// Join over the users for the checked out user.
		$query->select($db->quoteName('uc.name', 'editor'))
			->join('LEFT', $db->quoteName('#__users', 'uc') . ' ON ' . $db->quoteName('uc.id') . ' = ' . $db->quoteName('a.checked_out'));

		// Join over the asset groups.
		$query->select($db->quoteName('ag.title', 'access_level'))
			->join('LEFT', $db->quoteName('#__viewlevels', 'ag') . ' ON ' . $db->quoteName('ag.id') . ' = ' . $db->quoteName('a.access'));

		// Join over the module menus
		$query->select('MIN(mm.menuid) AS pages')
			->join('LEFT', $db->quoteName('#__modules_menu', 'mm') . ' ON ' . $db->quoteName('mm.moduleid') . ' = ' . $db->quoteName('a.id'));

		// Join over the extensions
		$query->select($db->quoteName('e.name', 'name'))
			->join('LEFT', $db->quoteName('#__extensions', 'e') . ' ON ' . $db->quoteName('e.element') . ' = ' . $db->quoteName('a.module'));

		// Group (careful with PostgreSQL)
		$query->group(
			'a.id, a.title, a.note, a.position, a.module, a.language, a.checked_out, '
			. 'a.checked_out_time, a.published, a.access, a.ordering, l.title, l.image, uc.name, ag.title, e.name, '
			. 'l.lang_code, uc.id, ag.id, mm.moduleid, e.element, a.publish_up, a.publish_down, e.enabled'
		);

		// Filter by client.
		$clientId = $this->getState('client_id');
		$query->where($db->quoteName('a.client_id') . ' = ' . (int) $clientId . ' AND ' . $db->quoteName('e.client_id') . ' = ' . (int) $clientId);

		// Filter by current user access level.
		$user = JFactory::getUser();

		// Get the current user for authorisation checks
		if ($user->authorise('core.admin') !== true)
		{
			$groups = implode(',', $user->getAuthorisedViewLevels());
			$query->where('a.access IN (' . $groups . ')');
		}

		// Filter by access level.
		if ($access = $this->getState('filter.access'))
		{
			$query->where($db->quoteName('a.access') . ' = ' . (int) $access);
		}

		// Filter by published state.
		$state = $this->getState('filter.state');

		if (is_numeric($state))
		{
			$query->where($db->quoteName('a.published') . ' = ' . (int) $state);
		}
		elseif ($state === '')
		{
			$query->where($db->quoteName('a.published') . ' IN (0, 1)');
		}

		// Filter by position.
		if ($position = $this->getState('filter.position'))
		{
			$query->where($db->quoteName('a.position') . ' = ' . $db->quote(($position === 'none') ? '' : $position));
		}

		// Filter by module.
		if ($module = $this->getState('filter.module'))
		{
			$query->where($db->quoteName('a.module') . ' = ' . $db->quote($module));
		}

		// Filter by menuitem id (only for site client).
		if ((int) $clientId === 0 && $menuItemId = $this->getState('filter.menuitem'))
		{
			// If user selected the modules not assigned to any page (menu item).
			if ((int) $menuItemId === -1)
			{
				$query->having('MIN(' . $db->quoteName('mm.menuid') . ') IS NULL');
			}
			// If user selected the modules assigned to some particular page (menu item).
			else
			{
				// Modules in "All" pages.
				$subQuery1 = $db->getQuery(true);
				$subQuery1->select('MIN(' . $db->quoteName('menuid') . ')')
					->from($db->quoteName('#__modules_menu'))
					->where($db->quoteName('moduleid') . ' = ' . $db->quoteName('a.id'));

				// Modules in "Selected" pages that have the chosen menu item id.
				$subQuery2 = $db->getQuery(true);
				$subQuery2->select($db->quoteName('moduleid'))
					->from($db->quoteName('#__modules_menu'))
					->where($db->quoteName('menuid') . ' = ' . (int) $menuItemId);

				// Modules in "All except selected" pages that doesn't have the chosen menu item id.
				$subQuery3 = $db->getQuery(true);
				$subQuery3->select($db->quoteName('moduleid'))
					->from($db->quoteName('#__modules_menu'))
					->where($db->quoteName('menuid') . ' = -' . (int) $menuItemId);

				// Filter by modules assigned to the selected menu item.
				$query->where('(
					(' . $subQuery1 . ') = 0
					OR ((' . $subQuery1 . ') > 0 AND ' . $db->quoteName('a.id') . ' IN (' . $subQuery2 . '))
					OR ((' . $subQuery1 . ') < 0 AND ' . $db->quoteName('a.id') . ' NOT IN (' . $subQuery3 . '))
					)'
				);
			}
		}

		// Filter by search in title or note or id:.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->quoteName('a.id') . ' = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . StringHelper::strtolower($search) . '%');
				$query->where('(LOWER(a.title) LIKE ' . $search . ' OR LOWER(a.note) LIKE ' . $search . ')');
			}
		}

		// Filter on the language.
		if ($language = $this->getState('filter.language'))
		{
			if ($language === 'current')
			{
				$query->where($db->quoteName('a.language') . ' IN (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
			}
			else
			{
				$query->where($db->quoteName('a.language') . ' = ' . $db->quote($language));
			}
		}

		return $query;
	}
}
fields/modulesposition.php000060400000001711152456151500011760 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_modules
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('ModulesHelper', JPATH_ADMINISTRATOR . '/components/com_modules/helpers/modules.php');

JFormHelper::loadFieldClass('list');

/**
 * Modules Position field.
 *
 * @since  3.4.2
 */
class JFormFieldModulesPosition extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.4.2
	 */
	protected $type = 'ModulesPosition';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.4.2
	 */
	public function getOptions()
	{
		$options = ModulesHelper::getPositions(JFactory::getApplication()->getUserState('com_modules.modules.client_id', 0));

		return array_merge(parent::getOptions(), $options);
	}
}
fields/modulesmodule.php000060400000001701152456151500011400 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_modules
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('ModulesHelper', JPATH_ADMINISTRATOR . '/components/com_modules/helpers/modules.php');

JFormHelper::loadFieldClass('list');

/**
 * Modules Module field.
 *
 * @since  3.4.2
 */
class JFormFieldModulesModule extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.4.2
	 */
	protected $type = 'ModulesModule';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.4.2
	 */
	public function getOptions()
	{
		$options = ModulesHelper::getModules(JFactory::getApplication()->getUserState('com_modules.modules.client_id', 0));

		return array_merge(parent::getOptions(), $options);
	}
}
positions.php000060400000014256152456151500007314 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_modules
 *
 * @copyright   (C) 2010 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Modules Component Positions Model
 *
 * @since  1.6
 */
class ModulesModelPositions extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'value',
				'templates',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'value', $direction = 'asc')
	{
		$app = JFactory::getApplication('administrator');

		// Load the filter state.
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$state = $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'string');
		$this->setState('filter.state', $state);

		$template = $this->getUserStateFromRequest($this->context . '.filter.template', 'filter_template', '', 'string');
		$this->setState('filter.template', $template);

		$type = $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'string');
		$this->setState('filter.type', $type);

		// Special case for the client id.
		$clientId = (int) $this->getUserStateFromRequest($this->context . '.client_id', 'client_id', 0, 'int');
		$clientId = (!in_array((int) $clientId, array (0, 1))) ? 0 : (int) $clientId;
		$this->setState('client_id', $clientId);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_modules');
		$this->setState('params', $params);

		// List state information.
		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get an array of data items.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   1.6
	 */
	public function getItems()
	{
		if (!isset($this->items))
		{
			$lang            = JFactory::getLanguage();
			$search          = $this->getState('filter.search');
			$state           = $this->getState('filter.state');
			$clientId        = $this->getState('client_id');
			$filter_template = $this->getState('filter.template');
			$type            = $this->getState('filter.type');
			$ordering        = $this->getState('list.ordering');
			$direction       = $this->getState('list.direction');
			$limitstart      = $this->getState('list.start');
			$limit           = $this->getState('list.limit');
			$client          = JApplicationHelper::getClientInfo($clientId);

			if ($type != 'template')
			{
				// Get the database object and a new query object.
				$query = $this->_db->getQuery(true)
					->select('DISTINCT(position) as value')
					->from('#__modules')
					->where($this->_db->quoteName('client_id') . ' = ' . (int) $clientId);

				if ($search)
				{
					$search = $this->_db->quote('%' . str_replace(' ', '%', $this->_db->escape(trim($search), true) . '%'));
					$query->where('position LIKE ' . $search);
				}

				$this->_db->setQuery($query);

				try
				{
					$positions = $this->_db->loadObjectList('value');
				}
				catch (RuntimeException $e)
				{
					$this->setError($e->getMessage());

					return false;
				}

				foreach ($positions as $value => $position)
				{
					$positions[$value] = array();
				}
			}
			else
			{
				$positions = array();
			}

			// Load the positions from the installed templates.
			foreach (ModulesHelper::getTemplates($clientId) as $template)
			{
				$path = JPath::clean($client->path . '/templates/' . $template->element . '/templateDetails.xml');

				if (file_exists($path))
				{
					$xml = simplexml_load_file($path);

					if (isset($xml->positions[0]))
					{
						$lang->load('tpl_' . $template->element . '.sys', $client->path, null, false, true)
						|| $lang->load('tpl_' . $template->element . '.sys', $client->path . '/templates/' . $template->element, null, false, true);

						foreach ($xml->positions[0] as $position)
						{
							$value = (string) $position['value'];
							$label = (string) $position;

							if (!$value)
							{
								$value = $label;
								$label = preg_replace('/[^a-zA-Z0-9_\-]/', '_', 'TPL_' . $template->element . '_POSITION_' . $value);
								$altlabel = preg_replace('/[^a-zA-Z0-9_\-]/', '_', 'COM_MODULES_POSITION_' . $value);

								if (!$lang->hasKey($label) && $lang->hasKey($altlabel))
								{
									$label = $altlabel;
								}
							}

							if ($type == 'user' || ($state != '' && $state != $template->enabled))
							{
								unset($positions[$value]);
							}
							elseif (preg_match(chr(1) . $search . chr(1) . 'i', $value) && ($filter_template == '' || $filter_template == $template->element))
							{
								if (!isset($positions[$value]))
								{
									$positions[$value] = array();
								}

								$positions[$value][$template->name] = $label;
							}
						}
					}
				}
			}

			$this->total = count($positions);

			if ($limitstart >= $this->total)
			{
				$limitstart = $limitstart < $limit ? 0 : $limitstart - $limit;
				$this->setState('list.start', $limitstart);
			}

			if ($ordering == 'value')
			{
				if ($direction == 'asc')
				{
					ksort($positions);
				}
				else
				{
					krsort($positions);
				}
			}
			else
			{
				if ($direction == 'asc')
				{
					asort($positions);
				}
				else
				{
					arsort($positions);
				}
			}

			$this->items = array_slice($positions, $limitstart, $limit ?: null);
		}

		return $this->items;
	}

	/**
	 * Method to get the total number of items.
	 *
	 * @return  integer  The total number of items.
	 *
	 * @since   1.6
	 */
	public function getTotal()
	{
		if (!isset($this->total))
		{
			$this->getItems();
		}

		return $this->total;
	}
}
select.php000060400000007674152456151500006552 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_modules
 *
 * @copyright   (C) 2009 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Module model.
 *
 * @since  1.6
 */
class ModulesModelSelect extends JModelList
{
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		$app = JFactory::getApplication('administrator');

		// Load the filter state.
		$clientId = $app->getUserState('com_modules.modules.client_id', 0);
		$this->setState('client_id', (int) $clientId);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_modules');
		$this->setState('params', $params);

		// Manually set limits to get all modules.
		$this->setState('list.limit', 0);
		$this->setState('list.start', 0);
		$this->setState('list.ordering', 'a.name');
		$this->setState('list.direction', 'ASC');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string    A store id.
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('client_id');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.extension_id, a.name, a.element AS module'
			)
		);
		$query->from($db->quoteName('#__extensions') . ' AS a');

		// Filter by module
		$query->where('a.type = ' . $db->quote('module'));

		// Filter by client.
		$clientId = $this->getState('client_id');
		$query->where('a.client_id = ' . (int) $clientId);

		// Filter by enabled
		$query->where('a.enabled = 1');

		// Add the list ordering clause.
		$query->order($db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}

	/**
	 * Method to get a list of items.
	 *
	 * @return  mixed  An array of objects on success, false on failure.
	 */
	public function getItems()
	{
		// Get the list of items from the database.
		$items = parent::getItems();

		$client = JApplicationHelper::getClientInfo($this->getState('client_id', 0));
		$lang = JFactory::getLanguage();

		// Loop through the results to add the XML metadata,
		// and load language support.
		foreach ($items as &$item)
		{
			$path = JPath::clean($client->path . '/modules/' . $item->module . '/' . $item->module . '.xml');

			if (file_exists($path))
			{
				$item->xml = simplexml_load_file($path);
			}
			else
			{
				$item->xml = null;
			}

			// 1.5 Format; Core files or language packs then
			// 1.6 3PD Extension Support
			$lang->load($item->module . '.sys', $client->path, null, false, true)
				|| $lang->load($item->module . '.sys', $client->path . '/modules/' . $item->module, null, false, true);
			$item->name = JText::_($item->name);

			if (isset($item->xml) && $text = trim($item->xml->description))
			{
				$item->desc = JText::_($text);
			}
			else
			{
				$item->desc = JText::_('COM_MODULES_NODESCRIPTION');
			}
		}

		$items = ArrayHelper::sortObjects($items, 'name', 1, true, true);

		// TODO: Use the cached XML from the extensions table?

		return $items;
	}
}
submit.php000060400000100601152456167330006566 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.10 2015-08-25
 * @since       3.2.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport('joomla.application.component.modelitem');
jimport('joomla.form.form');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');

/**
 * iCagenda Submit Event Model
 */
class iCagendaModelSubmit extends JModelItem
{
	protected $data;

	protected $msg;

	function getForm()
	{
	    $form = JForm::getInstance('submit', JPATH_COMPONENT . '/models/forms/submit.xml');

		if (empty($form))
		{
			return false;
		}

	    return $form;
	}

	public function test_input($data)
	{
		$this->data = trim($data);
		$this->data = stripslashes($this->data);

		return $this->data;
	}

	public function getData()
	{
		$app		= JFactory::getApplication();
		$user		= JFactory::getUser();
		$lang		= JFactory::getLanguage();
		$session	= JFactory::getSession();

		jimport( 'joomla.filter.output' );

		$eventTimeZone = null;
		$error_messages = array();

		// Get Params
		$params = $app->getParams();

		$submitAccess = $params->get('submitAccess', '');
		$approvalGroups = $params->get('approvalGroups', array("8"));

		// Get User Groups
		// Joomla 3.x/2.5 SWITCH
		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$userGroups = $user->groups;
		}
		else
		{
			$userGroups = $user->getAuthorisedGroups();
		}

		$user_id		= $user->get('id');

		// logged-in Users: Name/User Name Option
		$nameJoomlaUser	= $params->get('nameJoomlaUser', 1);
		$u_name			= ($nameJoomlaUser == 1) ? $user->get('name') : $user->get('username');

		// Redirection settings
		$baseURL		= JURI::base();
		$subpathURL		= JURI::base(true);

		$baseURL		= str_replace('/administrator', '', $baseURL);
		$subpathURL		= str_replace('/administrator', '', $subpathURL);

		$urlsend		= str_replace('&amp;','&', JRoute::_('index.php?option=com_icagenda&view=submit&layout=send'));

		// Sub Path filtering
		$subpathURL		= ltrim($subpathURL, '/');

		// URL List filtering
		$urlsend		= ltrim($urlsend, '/');

		if (substr($urlsend, 0, strlen($subpathURL)+1) == "$subpathURL/")
		{
			$urlsend = substr($urlsend, strlen($subpathURL)+1);
		}

		$urlsend		= rtrim($baseURL, '/') . '/' . ltrim($urlsend, '/');

		// Get return params
		$submit_return			= $params->get('submitReturn', '');
		$submit_return_article	= $params->get('submitReturn_Article', $urlsend);
		$submit_return_url		= $params->get('submitReturn_Url', $urlsend);

		if (($submit_return == 1) && is_numeric($submit_return_article))
		{
			$url_return = JURI::root().'index.php?option=com_content&view=article&id=' . $submit_return_article;
		}
		elseif ($submit_return == 2)
		{
			$url_return = $submit_return_url;
		}
		else
		{
			$url_return = $urlsend;
		}

		// Set alert messages
		$alert_title			= $params->get('alert_title', '');
		$alert_body				= $params->get('alert_body', '');
		$url_redirect			= isset($urlsend_custom) ? $urlsend_custom : $urlsend; // Url custom not yet available.
		$alert_title_redirect	= $alert_title ? $alert_title : JText::_( 'COM_ICAGENDA_EVENT_SUBMISSION' );
		$alert_body_redirect	= $alert_body ? $alert_body : JText::_( 'COM_ICAGENDA_EVENT_SUBMISSION_CONFIRMATION' );

		// Set post data
		$this->data						= new stdClass();
		$this->data->id					= null;
		$this->data->asset_id			= JRequest::getVar('asset_id', '', 'post');
		$this->data->ordering			= 0;
		$this->data->state				= 1;


		// Control: if Manager
		jimport( 'joomla.access.access' );
		$adminUsersArray = array();

		foreach ($approvalGroups AS $ag)
		{
			$adminUsers			= JAccess::getUsersByGroup($ag, False);
			$adminUsersArray	= array_merge($adminUsersArray, $adminUsers);
		}

		$this->data->approval			= (in_array($user_id, $adminUsersArray)) ? '0' : '1';
		$this->data->access				= 1 ;
		$this->data->language			= '*';
//		$menuID 						= JRequest::getVar('menuID', '', 'post');


		// USER NAME
		$this->data->username 			= JRequest::getVar('username', '', 'post');

		if ( ! $this->data->username)
		{
			$error_messages[] = JText::sprintf('COM_ICAGENDA_FORM_VALIDATE_FIELD_REQUIRED_NAME', JText::_('COM_ICAGENDA_SUBMIT_FORM_USER_NAME'));
		}

		// USER EMAIL
		$this->data->created_by_email	= JRequest::getVar('created_by_email', '', 'post');

		if ( ! $this->data->created_by_email)
		{
			$error_messages[] = JText::sprintf('COM_ICAGENDA_FORM_VALIDATE_FIELD_REQUIRED_NAME', JText::_('COM_ICAGENDA_SUBMIT_FORM_USER_EMAIL'));
		}


		// EVENT TITLE
		$this->data->title 				= JRequest::getVar('title', '', 'post');

		if ( ! $this->data->title)
		{
			$error_messages[] = JText::sprintf('COM_ICAGENDA_FORM_VALIDATE_FIELD_REQUIRED_NAME', JText::_('COM_ICAGENDA_FORM_LBL_EVENT_TITLE'));
		}


		// EVENT CATEGORY
		$this->data->catid 				= JRequest::getVar('catid', '', 'post');

		if ( ! $this->data->catid)
		{
			$error_messages[] = JText::sprintf('COM_ICAGENDA_FORM_VALIDATE_FIELD_REQUIRED_NAME', JText::_('COM_ICAGENDA_FORM_LBL_EVENT_CATID'));
		}


		// EVENT IMAGE - Get and Upload Image
		$image							= JRequest::getVar('image', null, 'files', 'array');
		$image_session					= JRequest::getVar('image_session', '', 'post');

		if ($image_session && empty($image))
		{
			$this->data->image = $image_session;
		}
		else
		{
			$this->data->image = $image;

			// Process upload of files
			$this->data->image = $this->frontendImageUpload($this->data->image);
		}

		$noDateTime			= '0000-00-00 00:00:00';
		$noDateTimeShort	= '0000-00-00 00:00';


		// Get Single Dates
		$single_dates 					= JRequest::getVar('dates', '', 'post');

//		$dates = iCString::isSerialized($single_dates) ? unserialize($single_dates) : $this->getDates($single_dates);
        if (iCString::isSerialized($single_dates))
		{
			$dates = unserialize($single_dates);
		}
		else
		{
			$dates = $this->getDates($single_dates);

			if ($lang->getTag() == 'fa-IR'
				&& $dates != array('0000-00-00 00:00')
				&& $dates != array('')
				)
			{
				$dates_to_sql = array();

				foreach ($dates AS $date)
				{
					if (iCDate::isDate($date))
					{
						$year		= date('Y', strtotime($date));
						$month		= date('m', strtotime($date));
						$day		= date('d', strtotime($date));
						$time		= date('H:i', strtotime($date));

						$converted_date = iCGlobalizeConvert::jalaliToGregorian($year, $month, $day, true) . ' ' . $time;
						$dates_to_sql[] = date('Y-m-d H:i', strtotime($converted_date));
					}
				}

				$dates = $dates_to_sql;
			}
		}

//		$dates = !empty($dates[0]) ? $dates : array($noDateTime);
		rsort($dates);

		$datesall = iCDate::isDate($dates[0]) ? $dates[0] : $noDateTimeShort;

		if ($datesall != $noDateTimeShort)
		{
			$this->data->dates 			= serialize($dates);
		}
		else
		{
			$no_date_array				= array($noDateTimeShort);
			$this->data->dates 			= serialize($no_date_array);
		}


		// Set Next Date from Single Dates
		$dates_array = unserialize($this->data->dates);

		$today	= JHtml::date('now', 'Y-m-d H:i:s', $eventTimeZone);
		$next	= JHtml::date($this->data->dates[0], 'Y-m-d H:i:s', $eventTimeZone);

		rsort($dates_array);

		$nextDate = $next;

		if ($next <= $today)
		{
			foreach ($dates_array as $date)
			{
				$single_date = JHtml::date($date, 'Y-m-d H:i:s', $eventTimeZone);

				if ($single_date >= $today)
				{
					$nextDate = $single_date;
				}
			}
		}

		$single_dates_next = $nextDate;


		// PERIOD DATES
		$this->data->startdate			= JRequest::getVar('startdate', '', 'post');
		$this->data->enddate			= JRequest::getVar('enddate', '', 'post');

		$isDate_startdate	= iCDate::isDate($this->data->startdate);
		$isDate_enddate		= iCDate::isDate($this->data->enddate);

		$this->data->startdate	= $isDate_startdate ? $this->data->startdate : $noDateTime;
		$this->data->enddate	= $isDate_enddate ? $this->data->enddate : $noDateTime;

		// Dates from the period
		if ($isDate_startdate && $isDate_enddate)
		{
			$startdate	= $this->data->startdate;
			$enddate	= $this->data->enddate;

			if ($startdate == $noDateTime
				&& $enddate != $noDateTime)
			{
				$enddate = $noDateTime;
			}

			$startcontrol	= JHtml::date($startdate, 'Y-m-d H:i', $eventTimeZone);
			$endcontrol		= JHtml::date($enddate, 'Y-m-d H:i', $eventTimeZone);

			$errorperiod = '';

			if ($startcontrol > $endcontrol)
			{
				$errorperiod = '1';
			}
			else
			{
				$period_all_dates_array	= iCDatePeriod::listDates($startdate, $enddate);
			}

			// Serialize Dates of the Period
			if ($isDate_startdate && $isDate_enddate)
			{
				if ($errorperiod != '1')
				{
					$this->data->period = serialize($period_all_dates_array);
					$ctrl = unserialize($this->data->period);

					if (is_array($ctrl))
					{
						$period = unserialize($this->data->period);
					}
					else
					{
						$period = $this->getPeriod($this->data->period);
					}

					if ($lang->getTag() == 'fa-IR')
					{
						$period_to_sql = array();

						foreach ($period AS $date)
						{
							if (iCDate::isDate($date))
							{
								$year		= date('Y', strtotime($date));
								$month		= date('m', strtotime($date));
								$day		= date('d', strtotime($date));
								$time		= date('H:i', strtotime($date));

								$converted_date = iCGlobalizeConvert::jalaliToGregorian($year, $month, $day, true) . ' ' . $time;
								$period_to_sql[] = date('Y-m-d H:i', strtotime($converted_date));
							}
						}

						$period = $period_to_sql;
					}

					rsort($period);

					$this->data->period = serialize($period);
				}
				else
				{
					$this->data->period = '';
				}
			}

			$period_dates_next = $this->data->startdate;

			$dates_next		= JHtml::date($single_dates_next, 'Y-m-d H:i:s', $eventTimeZone);
			$period_next	= JHtml::date($period_dates_next, 'Y-m-d H:i:s', $eventTimeZone);

			if ($dates_next < $period_next)
			{
				$this->data->next = $period_next;
			}
			else
			{
				$this->data->next = $dates_next;
			}
		}
		else
		{
			$this->data->period	= '';
			$this->data->next	= $single_dates_next;
		}

		// Period and Single Dates not displayed
		if ( (in_array($noDateTime, $dates_array) || in_array($noDateTimeShort, $dates_array))
			&& ( ! $isDate_startdate || ! $isDate_enddate) )
		{
			$this->data->state	= '0';
			$this->data->next	= $today;

			// Error message if no valid dates
			$error_messages[] = JText::sprintf('COM_ICAGENDA_FORM_WARNING', JText::_('COM_ICAGENDA_FORM_ERROR_NO_DATES'));
		}


		// WEEK DAYS
		$this->data->weekdays 			= JRequest::getVar('weekdays', '', 'post');

		if (!isset($this->data->weekdays)
			&& !is_array($this->data->weekdays))
		{
			$this->data->weekdays = '';
		}

		if (isset($this->data->weekdays)
			&& is_array($this->data->weekdays))
		{
			$this->data->weekdays = implode(",", $this->data->weekdays);
		}

		// Joomla 3.x/2.5 SWITCH
		if (version_compare(JVERSION, '3.0', 'ge'))
		{
			$this->data->desc 			= JFactory::getApplication()->input->get('desc', '', 'RAW');
		}
		else
		{
			$this->data->desc 			= JRequest::getVar('desc', '', 'post', 'string', JREQUEST_ALLOWHTML);
		}

		$this->data->shortdesc 			= JRequest::getVar('shortdesc', '', 'post');
		$this->data->metadesc 			= JRequest::getVar('metadesc', '', 'post');
		$this->data->place 				= JRequest::getVar('place', '', 'post');
		$this->data->email 				= JRequest::getVar('email', '', 'post');
		$this->data->phone 				= JRequest::getVar('phone', '', 'post');
		$this->data->website 			= JRequest::getVar('website', '', 'post');

		// ATTACHMENT FILE
		$file							= JRequest::getVar('file', null, 'files', 'array');
		$file_session					= JRequest::getVar('file_session', '', 'post');

		if ($file_session && empty($file))
		{
			$this->data->file = $file_session;
		}
		else
		{
			$this->data->file = $file;

			// Process upload of files
			$this->data->file = $this->frontendFileUpload($this->data->file);
		}



		$this->data->address 			= JRequest::getVar('address', '', 'post');
		$this->data->city 				= JRequest::getVar('city', '', 'post');
		$this->data->country 			= JRequest::getVar('country', '', 'post');
		$this->data->lat 				= JRequest::getVar('lat', '', 'post');
		$this->data->lng 				= JRequest::getVar('lng', '', 'post');

		$this->data->created_by			= $user_id;
		$this->data->created_by_alias	= JRequest::getVar('created_by_alias', '', 'post');
		$this->data->created			= JHtml::Date( 'now', 'Y-m-d H:i:s' );
		$this->data->checked_out		= JRequest::getVar('checked_out', '', 'post');
		$this->data->checked_out_time 	= JRequest::getVar('checked_out_time', '', 'post');

		$this->data->params				= JRequest::getVar('params', '', 'post');
		$this->data->site_itemid		= JRequest::getVar('site_itemid', '0', 'post');
		$site_menu_title				= JRequest::getVar('site_menu_title', '', 'post');


		// Generate Alias
		$this->data->alias				= JFilterOutput::stringURLSafe($this->data->title);

		// Alias is not generated if non-latin characters, so we fix it by using created date, or title if unicode is activated, as alias
		if ($this->data->alias == null)
		{
			if (JFactory::getConfig()->get('unicodeslugs') == 1)
			{
				$this->data->alias = JFilterOutput::stringURLUnicodeSlug($this->data->title);
			}
			else
			{
				$this->data->alias = JFilterOutput::stringURLSafe($this->data->created);
			}
		}

		// Convert the params field to a string.
		if ( isset($this->data->params)
			&& is_array($this->data->params) )
		{
			$parameter = new JRegistry;
			$parameter->loadArray($this->data->params);
			$this->data->params = (string)$parameter;
		}

		$this->data->asset_id = null;

		$custom_fields		= JRequest::getVar('custom_fields', '', 'post');

		// Check if Custom Fields required not empty
		$customfields_list = icagendaCustomfields::getListCustomFields(2, 1);

		if ($customfields_list)
		{
			foreach ($customfields_list AS $cf)
			{
				if (isset($custom_fields[$cf->cf_slug])
					&& $cf->cf_required == 1
					&& $custom_fields[$cf->cf_slug] == '')
				{

					$options_required = array('list', 'radio');

					// If type is list or radio, should have options
					if ((in_array($cf->cf_type, $options_required) && $cf->cf_options)
						|| ! in_array($cf->cf_type, $options_required))
					{
						$error_messages[] = JText::_( 'COM_ICAGENDA_FORM_VALIDATE_FIELD_REQUIRED' ) . ' ' . $cf->cf_title;
					}
				}
			}
		}

		$address_session	= JRequest::getVar('address_session', '', 'post');
		$submit_tos			= JRequest::getVar('submit_tos', '', 'post');

		// Set Form Data to Session
		$session->set('ic_submit', $this->data);
		$session->set('custom_fields', $custom_fields);

		$session->set('ic_submit_dates', $this->data->dates);
		$session->set('ic_submit_catid', $this->data->catid);
		$session->set('ic_submit_shortdesc', $this->data->shortdesc);
		$session->set('ic_submit_metadesc', $this->data->metadesc);
		$session->set('ic_submit_city', $this->data->city);
		$session->set('ic_submit_country', $this->data->country);
		$session->set('ic_submit_lat', $this->data->lat);
		$session->set('ic_submit_lng', $this->data->lng);
		$session->set('ic_submit_address', $this->data->address);
		$session->set('ic_submit_tos', $submit_tos);

		// Captcha Control
		$captcha			= JRequest::getVar('recaptcha_response_field', '', 'post');
		$captcha_plugin		= $params->get('captcha') ? $params->get('captcha') : $app->getCfg('captcha');
		$submit_captcha		= $params->get('submit_captcha', 1);

		if ($captcha_plugin && $submit_captcha != '0')
		{
			JPluginHelper::importPlugin('captcha');

			// JOOMLA 3.x/2.5 SWITCH
			if (version_compare(JVERSION, '3.0', 'ge'))
			{
				$dispatcher = JEventDispatcher::getInstance();
			}
			else
			{
				$dispatcher = JDispatcher::getInstance();
			}

			$res = $dispatcher->trigger('onCheckAnswer', $captcha);

			if (!$res[0])
			{
				// message if captcha is invalid
				$error_messages[] = JText::sprintf('COM_ICAGENDA_FORM_ERROR', JText::_('COM_ICAGENDA_FORM_ERROR_INCORRECT_CAPTCHA_SOL'));
			}
		}

		// Get the message queue
		if (count($error_messages))
		{
			$app->enqueueMessage('<strong>' . JText::_( 'COM_ICAGENDA_FORM_NC' ) . '</strong>', 'error');

			foreach ($error_messages AS $msg)
			{
				$app->enqueueMessage($msg, 'error');
			}

			return false;
		}

		// clear the data so we don't process it again
		$session->clear('ic_submit');
		$session->clear('custom_fields');
		$session->clear('ic_submit_dates');
		$session->clear('ic_submit_catid');
		$session->clear('ic_submit_shortdesc');
		$session->clear('ic_submit_metadesc');
		$session->clear('ic_submit_city');
		$session->clear('ic_submit_country');
		$session->clear('ic_submit_lat');
		$session->clear('ic_submit_lat');
		$session->clear('ic_submit_address');
		$session->clear('ic_submit_tos');

		// insert Event in Database
		$db = JFactory::getDbo();

		if (($this->data->username != NULL)
			&& ($this->data->title != NULL)
			&& ($this->data->created_by_email != NULL))
		{
			$db->insertObject('#__icagenda_events', $this->data, id);
		}
		else
		{
			JError::raiseError(500, implode('<br />', $errors));

			return false;
		}

		// Save Custom Fields to database
		if (isset($custom_fields) && is_array($custom_fields))
		{
			icagendaCustomfields::saveToData($custom_fields, $this->data->id, 2);
		}


		if ((isset($this->data->id)) AND ($this->data->id != '0') AND ($this->data->username != NULL) AND ($this->data->title != NULL))
		{
			self::notificationManagerEmail($this->data, $site_menu_title, $user_id);

			if ( !in_array($user_id, $adminUsersArray ))
			{
				self::notificationUserEmail($this->data, $urlsend);
			}
		}
		else
		{
			JError::raiseError(500, implode('<br />', $errors));

			return false;
		}

		// Redirect after successful submission
		if ($submit_return != 2)
		{
			$app->enqueueMessage($alert_body_redirect, $alert_title_redirect);
			$app->redirect(htmlspecialchars_decode($url_return));
		}
		else
		{
			$url_return = iCUrl::urlParsed($url_return, 'scheme');
			$app->redirect($url_return);
		}
	}


	protected function notificationManagerEmail($data, $site_menu_title, $user_id)
	{
		$event_id			= $data->id;
		$event_title		= $data->title;
		$event_site_itemid	= $data->site_itemid;
		$event_username		= $data->username;
		$event_user_email	= $data->created_by_email;
		$event_ref			= JHtml::date('now', 'Ymd') . $data->id;

		// Load iCagenda Global Options
		$iCparams = JComponentHelper::getParams('com_icagenda');

		// Load Joomla Application
		$app	= JFactory::getApplication();

		// Load Joomla Config Mail Options
		$sitename	= $app->getCfg('sitename');
		$mailfrom	= $app->getCfg('mailfrom');
		$fromname	= $app->getCfg('fromname');

		$siteURL = JURI::base();
		$siteURL = rtrim($siteURL,'/');

		// Itemid Request (automatic detection of the first iCagenda menu-link, by menuID, and depending of current language)
		$menu_items		= icagendaMenus::iClistMenuItems();
		$itemid_array	= array();

		foreach ($menu_items as $l)
		{
			array_push($itemid_array, $l->id);
		}

		sort($itemid_array);

		$itemID = $itemid_array[0];

		// Set Notification Email to each User groups allowed to approve event submitted
		$groupid = $iCparams->get('approvalGroups', array("8"));

		// Load Global Option for Autologin
		$autologin = $iCparams->get('auto_login', 1);

		jimport( 'joomla.access.access' );
		$adminUsersArray = array();

		foreach ($groupid AS $gp)
		{
			$adminUsers			= JAccess::getUsersByGroup($gp, False);
			$adminUsersArray	= array_merge($adminUsersArray, $adminUsers);
		}

        $db = JFactory::getDbo();
		$query = $db->getQuery(true);

		if ($user_id == NULL)
		{
			$user_id = 0;
		}

		if (!in_array($user_id, $adminUsersArray))
		{
			$matches = implode(',', $adminUsersArray);
			$query->select('ui.username AS username, ui.email AS email, ui.password AS passw, ui.block AS block, ui.activation AS activation')->from('#__users AS ui')->where( "ui.id IN ($matches) ");
		}
		else
		{
			$matches = $user_id;
			$query->select('ui.username AS username, ui.email AS email, ui.password AS passw, ui.block AS block, ui.activation AS activation')->from('#__users AS ui')->where( "ui.id = $matches ");
		}

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

        foreach ($managers AS $manager)
        {
			// Mail Replacements
			$replacements = array(
				"\\n"				=> "\n",
				'[SITENAME]'		=> $sitename,
				'[USERNAME]'		=> $event_username,
				'[EMAIL]'			=> $event_user_email,
				'[EVENT_TITLE]'		=> $event_title,
				'[EVENT_REF]'		=> $event_ref,
				'&nbsp;'			=> ' ',
			);

			if (!in_array($user_id, $adminUsersArray))
			{
				$type = 'approval';
			}
			else
			{
				$type = 'confirmation';
			}

			// Create Admin Mailer
			$adminmailer = JFactory::getMailer();

			// Set Sender of Notification Email
			$adminmailer->setSender(array( $mailfrom, $fromname ));

        	$username	= $manager->username;
        	$passw		= $manager->passw;
        	$email		= $manager->email;

			// Set Recipient of Notification Email
			$adminrecipient = $email;
			$adminmailer->addRecipient($adminrecipient);

			// Set Subject of Admin Notification Email
			if ( ! in_array($user_id, $adminUsersArray))
			{
				$adminsubject = JText::sprintf('COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_SUBJECT', $event_username, $sitename);
			}
			else
			{
				$adminsubject = JText::sprintf('COM_ICAGENDA_LEGEND_NEW_EVENT').': '.$event_title;
			}

			// Set Url to preview and checking of event submitted
			$baseURL = JURI::base();
			$subpathURL = JURI::base(true);

			$baseURL = str_replace('/administrator', '', $baseURL);
			$subpathURL = str_replace('/administrator', '', $subpathURL);

			if ($autologin == 1)
			{
				$urlpreview = str_replace('&amp;', '&', JRoute::_('index.php?option=com_icagenda&view=list&layout=event&id='.(int)$event_id.'&Itemid='.(int)$itemID.'&icu='.$username.'&icp='.$passw));
//				$urlcheck = str_replace('&amp;', '&', JRoute::_('administrator/index.php?option=com_icagenda&view=events&Itemid='.(int)$itemID).'&icu='.$username.'&icp='.$passw.'&filter_search='.$event_id);
			}
			else
			{
				$urlpreview = str_replace('&amp;', '&', JRoute::_('index.php?option=com_icagenda&view=list&layout=event&id='.(int)$event_id.'&Itemid='.(int)$itemID));
//				$urlcheck = str_replace('&amp;', '&', JRoute::_('administrator/index.php?option=com_icagenda&view=events&Itemid='.(int)$itemID).'&filter_search='.$event_id);
			}

//			$urlpreview = str_replace('&amp;', '&', $siteURL.'/index.php?option=com_icagenda&view=list&layout=event&id='.(int)$event_id.'&Itemid='.(int)$itemID.'&icu='.$username.'&icp='.$passw);
			$urlpreviewshort = str_replace('&amp;', '&', JRoute::_('index.php?option=com_icagenda&view=list&layout=event&id='.(int)$event_id.'&Itemid='.(int)$itemID));

//			$urlcheckshort = str_replace('&amp;', '&', $siteURL . '/administrator/index.php?option=com_icagenda&view=events');

			// Sub Path filtering
			$subpathURL = ltrim($subpathURL, '/');

			// URL Event Preview filtering
			$urlpreview			= ltrim($urlpreview, '/');
			$urlpreviewshort	= ltrim($urlpreviewshort, '/');

			if (substr($urlpreview, 0, strlen($subpathURL)+1) == "$subpathURL/")
			{
				$urlpreview = substr($urlpreview, strlen($subpathURL)+1);
			}

			if (substr($urlpreviewshort, 0, strlen($subpathURL)+1) == "$subpathURL/")
			{
				$urlpreviewshort = substr($urlpreviewshort, strlen($subpathURL)+1);
			}

			$urlpreview			= rtrim($baseURL, '/') . '/' . ltrim($urlpreview, '/');
			$urlpreviewshort	= rtrim($baseURL, '/') . '/' . ltrim($urlpreviewshort, '/');

			// URL Event Check filtering
//			$urlcheck = ltrim($urlcheck, '/');

//			if (substr($urlcheck, 0, strlen($subpathURL)+1) == "$subpathURL/")
//			{
//				$urlcheck = substr($urlcheck, strlen($subpathURL)+1);
//			}

//			$urlcheck = rtrim($baseURL, '/') . '/' . ltrim($urlcheck, '/');

			// Set Body of User Notification Email
			$adminbodycontent = JText::sprintf( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_HELLO', $username) . ',<br /><br />';

			if ($type == 'approval')
			{
				$adminbodycontent.= JText::_( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_NEW_EVENT' ).'<br /><br />';
				$adminbodycontent.= JText::sprintf( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_APPROVE_INFO', $sitename).'<br /><br />';
				$adminbodycontent.= JText::_( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_APPROVE_LINK' ).': <a href="'.$urlpreview.'">'.$urlpreviewshort.'</a><br /><br />';
			}

			if ($type == 'confirmation')
			{
				$adminbodycontent.= JText::_( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_APPROVED_REVIEW' ).'<br /><br />';
				$adminbodycontent.= '<a href="' . $urlpreview . '">' . $urlpreviewshort . '</a><br /><br />';
			}

			$user_email_mailto = '<a href="mailto:' . $event_user_email . '">' . $event_user_email . '</a>';

			$adminbodycontent.= JText::sprintf( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_SITE_MENUID', $event_site_itemid, $site_menu_title).'<br />';
			$adminbodycontent.= JText::sprintf( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_USER_INFO', $event_username, $user_email_mailto).'<br /><br />';

			if ($autologin == 1)
			{
				$adminbodycontent.= '<hr><small>'.JText::sprintf( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_FOOTER', $sitename).'<small>';
			}
			else
			{
				$adminbodycontent.= '<hr><small>'.JText::sprintf( 'COM_ICAGENDA_SUBMISSION_ADMIN_EMAIL_FOOTER_NO_AUTOLOGIN', $sitename).'<small>';
			}

			$adminbody = rtrim($adminbodycontent);

			// Apply Replacements
			foreach ($replacements as $key => $value)
			{
				$adminsubject	= str_replace($key, $value, $adminsubject);
				$adminbody		= str_replace($key, $value, $adminbody);
			}

			$adminmailer->isHTML(true);
			$adminmailer->Encoding = 'base64';

			// Set Subject
			$adminmailer->setSubject($adminsubject);

			// Set Body
			$adminmailer->setBody($adminbody);

			// Send User Notification Email
			if (isset($email))
			{
				if ($manager->block == '0' && empty($manager->activation))
				{
					$send = $adminmailer->Send();
				}
			}
		}
	}

	protected function notificationUserEmail ($data, $url)
	{
		$email			= $data->created_by_email;
		$username		= $data->username;
		$event_title	= $data->title;
		$event_ref		= JHtml::date( 'now', 'Ymd' ) . $data->id;

		// Load Joomla Application
		$app	= JFactory::getApplication();

		// Create User Mailer
		$mailer = JFactory::getMailer();

		// Load Joomla Config Mail Options
		$sitename	= $app->getCfg('sitename');
		$mailfrom	= $app->getCfg('mailfrom');
		$fromname	= $app->getCfg('fromname');

		// Set Sender of Notification Email
		$mailer->setSender(array( $mailfrom, $fromname ));

		// Set Recipient of User Notification Email
		$userrecipient = $data->created_by_email;
		$mailer->addRecipient($userrecipient);

		// MAIL
		$replacements = array(
			"\\n"				=> "\n",
			'[SITENAME]'		=> $sitename,
			'[EMAIL]'			=> $email,
			'[EVENT_TITLE]'		=> $event_title,
			'[EVENT_REF]'		=> $event_ref,
			'&nbsp;'			=> ' ',
		);

		// Set Body of Notification Email
		$user_submit_body = JText::sprintf( 'COM_ICAGENDA_USER_EMAIL_HELLO', $username ) . ',<br /><br />';
		$user_submit_body.= JText::sprintf( 'COM_ICAGENDA_EVENT_SUBMISSION_THANK_YOU', $sitename ) . '<br />';
		$user_submit_body.= JText::_( 'COM_ICAGENDA_EVENT_SUBMISSION_EDITOR_REVIEW' ) . '<br />';
		$user_submit_body.= JText::_( 'COM_ICAGENDA_EVENT_SUBMISSION_CONFIRMATION_EMAIL' ) . '<br /><br />';
		$user_submit_body.= JText::sprintf( 'COM_ICAGENDA_USER_EMAIL_EVENT_TITLE_AND_REF_NO', $event_title, $event_ref ) . '<br /><br />';
		$user_submit_body.= JText::_( 'COM_ICAGENDA_USER_EMAIL_BEST_REGARDS' ) . '<br />';

		$user_submit_body = rtrim($user_submit_body);

		foreach ($replacements as $key => $value)
		{
			$subject = str_replace($key, $value, $subject);
			$user_submit_body = str_replace($key, $value, $user_submit_body);
		}

		$mailer->isHTML(true);
		$mailer->Encoding = 'base64';

		// Set Subject of User Notification Email
		$subject = JText::sprintf( 'COM_ICAGENDA_EVENT_SUBMISSION_THANK_YOU', $sitename );
		$mailer->setSubject($subject);

		// Set Body of User Notification Email
		$mailer->setBody($user_submit_body);

		// Send User Notification Email
		if (isset($email))
		{
			$send = $mailer->Send();
		}
	}


	protected function getDates($dates)
	{
		$dates		= str_replace('d=', '', $dates);
		$dates		= str_replace('+', ' ', $dates);
		$dates		= str_replace('%3A', ':', $dates);
		$ex_dates	= explode('&', $dates);

		return $ex_dates;
	}

	protected function getPeriod($period)
	{
		$period		= str_replace('d=', '', $period);
		$period		= str_replace('+', ' ', $period);
		$period		= str_replace('%3A', ':', $period);
		$ex_period	= explode('&', $period);

		return $ex_period;
	}


	protected function frontendImageUpload ($image)
	{
		// Get Joomla Images PATH set
		$params		= JComponentHelper::getParams('com_media');
		$image_path	= $params->get('image_path');

		// Clean up filename
		$imagename	= JFile::makeSafe($image['name']);

		// Process filename
		while (JFile::exists(JPATH_ROOT . '/' . $image_path . '/icagenda/frontend/images/' . $imagename))
		{
			$src	= $image['tmp_name'];

			// Get Image title and extension type
			$decomposition = explode( '/' , $imagename );

			// in each parent
			$i = 0;
			while ( isset($decomposition[$i]) )
				$i++;
			$i--;
			$imgname		= $decomposition[$i];
			$fichier		= explode('.', $decomposition[$i]);
			$imgtitle		= $fichier[0];
			$imgextension	= isset($fichier[1]) ? $fichier[1] : '';

			// Increment filename if already exists
			$imagename		= iCString::increment($imgtitle, 'dash') . '.' . $imgextension;

			// Controls image mimetype, and fixes file extension if missing in filename
			$allowed_mimetypes	= array('jpg', 'jpeg', 'png', 'gif');

			if ( ! in_array($imgextension, $allowed_mimetypes))
			{
				$fileinfos		= getimagesize($src);
				$mimeType		= $fileinfos['mime'];
				$ex_mimeType	= explode('/', $mimeType);
				$file_extension	= $ex_mimeType[1];

				$imagename		= $imagename . '.' . $file_extension;
			}
		}

		if ($imagename != '')
		{
			//Set up the source and destination of the file
			$src	= $image['tmp_name'];
			$dest	=  JPATH_SITE . '/images/icagenda/frontend/images/' . $imagename;

			// Create Folder iCagenda in ROOT/IMAGES_PATH/icagenda and sub-folders if do not exist
			$folder[0][0]	=	'icagenda/frontend/' ;
			$folder[0][1]	= 	JPATH_ROOT . '/' . $image_path . '/' . $folder[0][0];
			$folder[1][0]	=	'icagenda/frontend/images/';
			$folder[1][1]	= 	JPATH_ROOT . '/' . $image_path . '/' . $folder[1][0];
			$error	 = array();

			foreach ($folder as $key => $value)
			{
				if (!JFolder::exists( $value[1]))
				{
					if (JFolder::create( $value[1], 0755 ))
					{
						$this->data = "<html>\n<body bgcolor=\"#FFFFFF\">\n</body>\n</html>";
						JFile::write($value[1]."/index.html", $this->data);
						$error[] = 0;
					}
					else
					{
						$error[] = 1;
					}
				}
				else //Folder exist
				{
					$error[] = 0;
				}
			}

			if ( JFile::upload($src, $dest, false) )
			{
				return 'images/icagenda/frontend/images/' . $imagename;
			}
		}
	}

	protected function frontendFileUpload ($file)
	{
		//Clean up filename to get rid of strange characters like spaces etc
		$filename = JFile::makeSafe($file['name']);

		if ($filename != '')
		{
			//Set up the source and destination of the file
			$src = $file['tmp_name'];
			$dest =  JPATH_SITE.'/images/icagenda/frontend/attachments/'.$filename;

			// Get Joomla Images PATH setting
			$params = JComponentHelper::getParams('com_media');
			$image_path = $params->get('image_path');

			// Create Folder iCagenda in ROOT/IMAGES_PATH/icagenda and sub-folders if do not exist
			$folder[0][0]	=	'icagenda/frontend/' ;
			$folder[0][1]	= 	JPATH_ROOT.'/'.$image_path.'/'.$folder[0][0];
			$folder[1][0]	=	'icagenda/frontend/attachments/';
			$folder[1][1]	= 	JPATH_ROOT.'/'.$image_path.'/'.$folder[1][0];
			$error	 = array();

			foreach ($folder as $key => $value)
			{
				if (!JFolder::exists( $value[1]))
				{
					if (JFolder::create( $value[1], 0755 ))
					{
						$this->data = "<html>\n<body bgcolor=\"#FFFFFF\">\n</body>\n</html>";
						JFile::write($value[1]."/index.html", $this->data);
						$error[] = 0;
					}
					else
					{
						$error[] = 1;
					}
				}
				else //Folder exist
				{
					$error[] = 0;
				}
			}

			if ( JFile::upload($src, $dest, false) )
			{
				return 'images/icagenda/frontend/attachments/' . $filename;
			}

		}
	}


	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since   1.6
	 *
	 * @return void
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication('site');

		// Load the parameters.
		$params = $app->getParams();
		$this->setState('params', $params);
	}
}
forms/submit.xml000060400000025210152456167330007727 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_icagenda/models/fields" >
		<field
			name="id"
			type="text"
			label="JGLOBAL_FIELD_ID_LABEL"
			description="JGLOBAL_FIELD_ID_DESC"
			class="readonly"
			size="10"
			default="0"
			readonly="true"
			labelclass="control-label"
			/>
		<field
			name="asset_id"
			type="hidden"
			filter="unset"
			/>
		<field
			name="title"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_TITLE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_TITLE"
			class="input-xxlarge"
			size="30"
			required="true"
			labelclass="control-label"
			/>
		<field
			name="alias"
			type="text"
			label="JFIELD_ALIAS_LABEL"
			description="JFIELD_ALIAS_DESC"
			labelclass="control-label"
			/>
		<field
			name="state"
			type="list"
			label="JSTATUS"
			description="JFIELD_PUBLISHED_DESC"
			class="span12 small"
			filter="intval"
			size="1"
			default="1"
			>
			<option value="1">JPUBLISHED</option>
			<option value="0">JUNPUBLISHED</option>
			<option value="2">JARCHIVED</option>
			<option value="-2">JTRASHED</option>
		</field>
		<field
			name="access"
			type="accesslevel"
			label="JFIELD_ACCESS_LABEL"
			description="COM_ICAGENDA_ACCESS_DESC"
			class="span12 small"
			size="1"
			/>
		<field
			name="language"
			type="contentlanguage"
			label="JFIELD_LANGUAGE_LABEL"
			description="COM_ICAGENDA_FORM_DESC_LANGUAGE"
			class="span12 small"
			>
			<option value="*">JALL</option>
		</field>
		<field
			name="created"
			type="calendar"
			label="JGLOBAL_FIELD_CREATED_LABEL"
			description="JGLOBAL_FIELD_CREATED_DESC"
			format="%Y-%m-%d %H:%M:%S"
			filter="user_utc"
			labelclass="control-label"
			/>
		<field
			name="created_by"
			type="user"
			label="JGLOBAL_FIELD_CREATED_BY_LABEL"
			description="JGLOBAL_FIELD_CREATED_BY_DESC"
			labelclass="control-label"
			/>
		<field
			name="created_by_alias"
			type="text"
			label="JGLOBAL_FIELD_CREATED_BY_ALIAS_LABEL"
			description="JGLOBAL_FIELD_CREATED_BY_ALIAS_DESC"
			labelclass="control-label"
			/>
		<field
			name="username"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_USERNAME"
			description="COM_ICAGENDA_FORM_DESC_EVENT_USERNAME"
			size="40"
			required="true"
			class="inputbox"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="modified"
			type="calendar"
			label="JGLOBAL_FIELD_MODIFIED_LABEL"
			description="COM_CONTENT_FIELD_MODIFIED_DESC"
			class="readonly"
			size="22"
			readonly="true"
			format="%Y-%m-%d %H:%M:%S"
			filter="user_utc"
			labelclass="control-label"
			/>
		<field
			name="modified_by"
			type="user"
			label="JGLOBAL_FIELD_MODIFIED_BY_LABEL"
			class="readonly"
			readonly="true"
			filter="unset"
			labelclass="control-label"
			/>
		<field name="checked_out" type="hidden" filter="unset" />
		<field name="checked_out_time" type="hidden" filter="unset" />
		<field
			name="catid"
			type="modal_cat"
			label="COM_ICAGENDA_FORM_LBL_EVENT_CATID"
			description="COM_ICAGENDA_FORM_DESC_EVENT_CATID"
			class="inputbox"
			required="true"
			labelclass="control-label"
			/>
		<field
			name="image"
			type="file"
			label="COM_ICAGENDA_FORM_LBL_EVENT_IMAGE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_IMAGE"
			accept="image/*"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="file"
			type="file"
			label="COM_ICAGENDA_FORM_LBL_EVENT_FILE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_FILE"
			class="inputbox"
			id="upload_file"
			labelclass="control-label"
			/>
		<field
			name="displaytime"
			type="radio"
			label="COM_ICAGENDA_DISPLAY_TIME_LABEL"
			description="COM_ICAGENDA_DISPLAY_TIME_DESC"
			class="btn-group"
			default="1"
			labelclass="control-label"
			>
			<option value="0" class="ic-btn">JHIDE</option>
			<option value="1" class="ic-btn">JSHOW</option>
		</field>
		<field
			name="dates"
			type="modal_date"
			label="COM_ICAGENDA_FORM_LBL_EVENT_DATES"
			description="COM_ICAGENDA_FORM_DESC_EVENT_DATES"
			class="inputbox"
			default="0000-00-00 00:00:00"
			/>
		<field
			name="time"
			type="modal_time"
			label="COM_ICAGENDA_FORM_LBL_EVENT_TIME"
			description="COM_ICAGENDA_FORM_DESC_EVENT_TIME"
			size="40"
			class="inputbox"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="startdate"
			type="modal_startdate"
			label="COM_ICAGENDA_FORM_LBL_EVENTPERIOD_START"
			description="COM_ICAGENDA_FORM_DESC_EVENTPERIOD_START"
			class="inputbox"
			default="0000-00-00 00:00:00"
			/>
		<field
			name="enddate"
			type="modal_enddate"
			label="COM_ICAGENDA_FORM_LBL_EVENTPERIOD_END"
			description="COM_ICAGENDA_FORM_DESC_EVENTPERIOD_END"
			class="inputbox"
			default="0000-00-00 00:00:00"
			/>
		<field
			name="weekdays"
			type="list"
			label="COM_ICAGENDA_FORM_LBL_WEEK_DAYS"
			description=""
			multiple="true"
			default=""
			labelclass="control-label"
			>
			<option value="0">SUNDAY</option>
			<option value="1">MONDAY</option>
			<option value="2">TUESDAY</option>
			<option value="3">WEDNESDAY</option>
			<option value="4">THURSDAY</option>
			<option value="5">FRIDAY</option>
			<option value="6">SATURDAY</option>
		</field>
		<field
			name="shortdesc"
			type="modal_ictextarea_counter"
			label="COM_ICAGENDA_SUBMIT_AN_EVENT_SHORT_DESCRIPTION_LBL"
			description="COM_ICAGENDA_SUBMIT_AN_EVENT_SHORT_DESCRIPTION_DESC"
			class="ic-submit-shortdesc"
			row="3"
			cols="80"
			/>
		<field
			name="desc"
			type="editor"
			label="COM_ICAGENDA_FORM_LBL_EVENT_DESC"
			description="COM_ICAGENDA_SUBMIT_AN_EVENT_DESCRIPTION_DESC"
			buttons="false"
			labelclass="control-label"
			filter="safehtml"
			/>
		<field
			name="metadesc"
			type="modal_ictextarea_counter"
			label="COM_ICAGENDA_FORM_EVENT_METADESC_LBL"
			description="COM_ICAGENDA_SUBMIT_AN_EVENT_METADESC_DESC"
			class="ic-submit-metadesc"
			row="3"
			cols="80"
			/>
		<field
			name="next"
			type="hidden"
			label="COM_ICAGENDA_FORM_LBL_EVENT_NEXT"
			description="COM_ICAGENDA_FORM_DESC_EVENT_NEXT"
			class="inputbox"
			default="0000-00-00 00:00:00"
			labelclass="control-label"
			/>
		<field
			name="email"
			type="email"
			label="COM_ICAGENDA_FORM_LBL_EVENT_EMAIL"
			description="COM_ICAGENDA_FORM_DESC_EVENT_EMAIL"
			size="40"
			class="input-xlarge"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="phone"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_PHONE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_PHONE"
			size="30"
			class="input-large"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="website"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_WEBSITE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_WEBSITE"
			size="30"
			class="input-large"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="place"
			type="text"
			label="COM_ICAGENDA_FORM_LBL_EVENT_PLACE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_PLACE"
			size="30"
			class="input-large"
			id="place"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="coordinate"
			type="modal_coordinate"
			label="COM_ICAGENDA_FORM_LBL_EVENT_MAP"
			description="COM_ICAGENDA_FORM_DESC_EVENT_MAP"
			class="inputbox"
			labelclass="control-label"
			/>
		<field
			name="address"
			type="text"
			label="COM_ICAGENDA_GOOGLE_MAPS_ADDRESS_LBL"
			description="COM_ICAGENDA_FORM_DESC_EVENT_LOCATION"
			class="input-xlarge"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="city"
			type="icmap_city"
			label="COM_ICAGENDA_FORM_LBL_EVENT_CITY"
			description="COM_ICAGENDA_FORM_DESC_EVENT_CITY"
			class="input-large icmap-input"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="country"
			type="icmap_country"
			label="COM_ICAGENDA_FORM_LBL_EVENT_COUNTRY"
			description="COM_ICAGENDA_FORM_DESC_EVENT_COUNTRY"
			class="input-large icmap-input"
			filter="safehtml"
			labelclass="control-label"
			/>
		<field
			name="lat"
			type="icmap_lat"
			label="LATITUDE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_MAP"
			class="input-large icmap-input"
			labelclass="control-label"
			/>
		<field
			name="lng"
			type="icmap_lng"
			label="LONGITUDE"
			description="COM_ICAGENDA_FORM_DESC_EVENT_MAP"
			class="input-large icmap-input"
			labelclass="control-label"
			/>
		<field
			name="custom_fields"
			type="hidden"
			class="input-large"
			default=""
			/>
		<field
			name="site_itemid"
			type="hidden"
			label="COM_ICAGENDA_FORM_FRONTEND_SUBMIT_ITEMID_LBL"
			description="COM_ICAGENDA_FORM_FRONTEND_SUBMIT_ITEMID_DESC"
			size="3"
			class="inputbox"
			default="0"
			/>
		<field
			name="captcha"
			type="captcha"
			label="COM_ICAGENDA_CAPTCHA_LABEL"
			description="COM_ICAGENDA_CAPTCHA_DESC"
			validate="captcha"
			namespace="submit"
		/>
	</fieldset>

	<fields name="params">
		<fieldset name="registrations" label="COM_ICAGENDA_REGISTRATION_OPTIONS"
			addfieldpath="/administrator/components/com_icagenda/assets/elements">
			<!--field
				name="statutReg"
				type="radio"
				label="COM_ICAGENDA_REGISTRATION_LABEL"
				description="COM_ICAGENDA_REGISTRATION_DESC"
				class="btn-group ic-btn-group"
				labelclass="control-label"
				default="0"
				>
				<option value="0" class="ic-btn">JOFF</option>
				<option value="1" class="ic-btn">JON</option>
			</field-->
			<field
				name="typeReg"
				type="list"
				label="COM_ICAGENDA_TYPE_REG_LABEL"
				description="COM_ICAGENDA_TYPE_REG_DESC"
				default="1"
				>
				<option value="1">COM_ICAGENDA_REG_BY_INDIVIDUAL_DATE</option>
				<option value="2">COM_ICAGENDA_REG_FOR_ALL_DATES</option>
			</field>
			<field
				name="accessReg"
				type="hidden"
				label="JFIELD_ACCESS_LABEL"
				description="JFIELD_ACCESS_DESC"
				size="1"
				class="inputbox"
				labelclass="control-label"
				default=""
				/>
			<!--field
				name="maxReg"
				type="text"
				label="COM_ICAGENDA_MAX_REGISTRATIONS_LABEL"
				description="COM_ICAGENDA_MAX_REGISTRATIONS_DESC"
				size="3"
				default=""
				labelclass="control-label"
				/-->
			<field
				name="maxRlistGlobal"
				class="btn-group"
				type="hidden"
				default=""
				label="COM_ICAGENDA_MAX_PER_REGISTRATION_LABEL"
				description="COM_ICAGENDA_MAX_PER_REGISTRATION_DESC"
				labelclass="control-label"
				>
				<option value="">JGLOBAL_USE_GLOBAL</option>
				<option value="2">COM_ICAGENDA_LBL_CUSTOM_VALUE</option>
			</field>
			<field
				name="maxRlist"
				type="hidden"
				label=" "
				description="COM_ICAGENDA_DESC_CUSTOM_VALUE"
				size="2"
				default=""
				labelclass="control-label"
				/>
		</fieldset>
		<!--fieldset name="captcha">
			<field
				name="captcha"
				type="captcha"
				label="COM_ICAGENDA_CAPTCHA_LABEL"
				description="COM_ICAGENDA_CAPTCHA_DESC"
				validate="captcha"
				namespace="submit"
			/>
		</fieldset-->
	</fields>
</form>
list.php000060400000037054152456167330006251 0ustar00<?php
/**
 *------------------------------------------------------------------------------
 *  iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x
 *------------------------------------------------------------------------------
 * @package     com_icagenda
 * @copyright   Copyright (c)2012-2015 Cyril Rezé, Jooml!C - All rights reserved
 *
 * @license     GNU General Public License version 3 or later; see LICENSE.txt
 * @author      Cyril Rezé (Lyr!C)
 * @link        http://www.joomlic.com
 *
 * @version     3.5.4 2015-04-10
 * @since       1.0
 *------------------------------------------------------------------------------
*/

// No direct access to this file
defined('_JEXEC') or die();

jimport( 'joomla.filesystem.path' );

// Load file helpers

if (!class_exists('iCModelItem')) require(JPATH_COMPONENT . '/helpers/icmodel.php');
if (!class_exists('iCModeliChelper')) require(JPATH_COMPONENT . '/helpers/ichelper.php');


/**
 * icagenda Model
 */
class icagendaModelList extends iCModelItem
{
	/**
	 * Get Form - Registration
	 *
	 * @since	3.4.1
	 */
	public function getForm()
	{
	    $form = JForm::getInstance('submit', JPATH_COMPONENT . '/models/forms/registration.xml');

		if (empty($form))
		{
			return false;
		}

	    return $form;
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	3.6
	 */
	protected function populateState()
	{
		// Initialise variables.
		$app		= JFactory::getApplication();
		$context	= $app->input->get('option') . '.' . $app->input->get('view');

		// Load the filter state.
		$search = $app->getUserStateFromRequest($context.'.filter.search', 'filter_search');
		//Omit double (white-)spaces and set state
		$this->setState('filter.search', preg_replace('/\s+/',' ', $search));

		//Filter (dropdown) state
		$state = $app->getUserStateFromRequest($context.'.filter.state', 'filter_state', '', 'string');
		$this->setState('filter.state', $state);

		//Filter (dropdown) company
		$category = $app->getUserStateFromRequest($context.'.filter.category', 'filter_category', '', 'string');
		$this->setState('filter.category', $category);
	}

	/**
	 * Get Params
	 *
	 * @since	1.0
	 */
	public function getData()
	{
		$this->startiCModel();

		// Import params
		$app = JFactory::getApplication();
		$icpar = $app->getParams();

		// Get Current Layout
		$jlayout		= $app->input->getCmd('layout', '');
//		$layouts_array	= array('event', 'registration', 'actions');
//		$layout			= in_array($jlayout, $layouts_array) ? $jlayout : '';

		$user	= JFactory::getUser();
		$userid	= $user->get('id');

		// Get Registration Post Data // TO BE REMOVED WHEN NEW REGISTRATION VIEW
		$regpost = JRequest::get('post');

		// Process registration function to save data (icmodel.php) // TO BE REMOVED WHEN NEW REGISTRATION VIEW
		if ($app->input->get('event'))
		{
			$this->registration($regpost);
		}

		// filters
		$this->addFilter('state', 1);

		$id = JRequest::getInt('id');

//		if ( $jlayout
//			&& ( ! $id) || ( ! preg_match("/^[0-9]+$/", $id)))
//		{
//			JError::raiseError('404',JTEXT::_('JERROR_LAYOUT_PAGE_NOT_FOUND'));

//			return false;
//		}

		$Itemid = JRequest::getInt('Itemid');

		if ($id)
		{
			$this->addFilter('id', $id);
		}
		else
		{
			if(JRequest::getVar('key', '', 'post')) $this->addFilter('key', JRequest::getVar('key', '','post'));
			if($icpar->get('mcatid')) $this->addFilter('e.catid', $icpar->get('mcatid'));
			if($icpar->get('place')) $this->addFilter('e.place', $icpar->get('place'));
			if($icpar->get('address')) $this->addFilter('e.address', $icpar->get('address'));
			if($icpar->get('time')) $this->addFilter('next', $icpar->get('time'));
		}

		$this->addOption('Itemid', $icpar->get('itemid', $Itemid));

		// Get Option Menu and Global for Type of Display for List of Events (all dates, or only next date, for each event)
		$this->addOption('datesDisplay', $icpar->get('datesDisplay', 1));

		$this->addOption('filterTime', $icpar->get('time', 1));

		// Menu Options
		$this->addOption('number', $icpar->get('number', 5));

		// App Options
		$this->addOption('orderby', $icpar->get('orderby', 2));
		$this->addOption('mcatid', $icpar->get('mcatid', array('0')));
//		$this->addOption('format', $icpar->get('format', 0));

		// Global Options
		$this->addOption('addthis', $icpar->get('addthis', ''));
		$this->addOption('atevent', $icpar->get('atevent', 1));
		$this->addOption('atfloat', $icpar->get('atfloat', ''));
		$this->addOption('aticon', $icpar->get('aticon', ''));
		$this->addOption('emailRequired', $icpar->get('emailRequired', 0));
		$this->addOption('limit', $icpar->get('limit', 100));
		$this->addOption('limitGlobal', $icpar->get('limitGlobal', 0));
		$this->addOption('maxRlist', $icpar->get('maxRlist', ''));
		$this->addOption('participantList', $icpar->get('participantList', ''));
		$this->addOption('participantSlide', $icpar->get('participantSlide', ''));
		$this->addOption('phoneRequired', $icpar->get('phoneRequired', 0));
		$this->addOption('RegButtonText', $icpar->get('RegButtonText', ''));
		$this->addOption('statutReg', $icpar->get('statutReg', ''));
		$this->addOption('timeformat', $icpar->get('timeformat', 1));
		$this->addOption('m_width', $icpar->get('m_width', '100%'));
		$this->addOption('m_height', $icpar->get('m_height', '300px'));
//		$this->addOption('date_format', $icpar->get('date_format', ''));
//		$this->addOption('date_separator', $icpar->get('date_separator', ' '));

		if($icpar->get('participantDisplay')) $this->addOption('participantDisplay', $icpar->get('participantDisplay'));
		if($icpar->get('fullListColumns')) $this->addOption('fullListColumns', $icpar->get('fullListColumns'));
		if($icpar->get('targetLink')) $this->addOption('targetLink', $icpar->get('targetLink'));
		if($icpar->get('arrowtext')) $this->addOption('arrowtext', $icpar->get('arrowtext'));
		if($icpar->get('accessReg')) $this->addOption('accessReg', $icpar->get('accessReg'));
		if($icpar->get('limitRegEmail')) $this->addOption('limitRegEmail', $icpar->get('limitRegEmail'));
		if($icpar->get('limitRegDate')) $this->addOption('limitRegDate', $icpar->get('limitRegDate'));
		if($icpar->get('maxReg')) $this->addOption('maxReg', $icpar->get('maxReg'));
		if($icpar->get('regEmailUser')) $this->addOption('regEmailUser', $icpar->get('regEmailUser'));
		if($icpar->get('emailUserSubjectPeriod')) $this->addOption('emailUserSubjectPeriod', $icpar->get('emailUserSubjectPeriod'));
		if($icpar->get('emailUserBodyPeriod')) $this->addOption('emailUserBodyPeriod', $icpar->get('emailUserBodyPeriod'));
		if($icpar->get('emailUserSubjectDate')) $this->addOption('emailUserSubjectDate', $icpar->get('emailUserSubjectDate'));
		if($icpar->get('emailUserBodyDate')) $this->addOption('emailUserBodyDate', $icpar->get('emailUserBodyDate'));
		if($icpar->get('headerList')) $this->addOption('headerList', $icpar->get('headerList'));


		// Struture
		$structure = array(
//			'container'=>array(
//				'header'=>'',
//				'navigator'=>'',
//			),
			'items' => array(
				'item' => array(
					'accessReg'=>'',
					'approval'=>'',
					'eventAllDates'=>'',
					'eventHasPeriod'=>'',
					'evtParams'=>'',
					'infoDetails'=>'',
					'statutReg'=>'',
					'titleFormat'=>'',

					'BackArrow'=>'',
					'BackURL'=>'',
					'id'=>'',
					'Itemid'=>'',
					'metaTitle'=>'',
					'metaDesc'=>'',
					'metaAsShortDesc'=>'',
					'state'=>'',
					'weekday'=>'',
					'weekdayShort'=>'',
					'timeformat'=>'',
					'participantList'=>'',
					'participantSlide'=>'',
					'participantDisplay'=>'',
					'fullListColumns'=>'',
					'participantListTitle'=>'',
					'arrowtext'=>'',
					'navposition'=>'',
					'headerList'=>'',
					'title'=>'',
					'titlebar'=>'',
					'ManagerIcons'=>'',
					'url'=>NULL,
					'Event_Link'=>'',
					'cat_id'=>'',
					'cat_title'=>'',
					'cat_color'=>'',
					'fontColor'=>'',
					'cat_desc'=>'',
					'shortdesc'=>'',
					'desc'=>'',
					'shortDescription'=>'',
					'description'=>'',
					'descShort'=>'',
					'image'=>'',
					'imageTag'=>'',
					'file'=>'',
					'fileTag'=>'',

					'displaytime'=>'',
					'next'=>'',
					'nextDate'=>'',
					'period'=>'',
					'startdatetime'=>'',
					'enddatetime'=>'',
					'nextControl'=>'',

					'start_datetime'=>'',
					'end_datetime'=>'',
					'dates'=>'',

					'startDate'=>'',
					'startDay'=>'',

					'endDate'=>'',
					'endDay'=>'',
					'endMonth'=>'',
					'endMonthNum'=>'',
					'endYear'=>'',

					'startTime'=>'',
					'endTime'=>'',

					'periodDates'=>'',
					'dateText'=>'',
					'periodDisplay'=>'',
					'periodControl'=>'',
					'weekdays'=>'',
					'day'=>'',
					'maxNbTickets'=>'',
					'ticketsCouldBeBooked'=>'',
					'registeredForThisDate'=>'',
					'maxReg'=>'',
					'maxRlist'=>'',
					'emailRequired'=>'',
					'phoneRequired'=>'',

					'month'=>'',
					'monthNum'=>'',

					'year'=>'',
					'yearShort'=>'',
					'evenTime'=>'',
					'dateFormat'=>'',
					'datelistMkt'=>'',
					'datelist'=>'',
					'datelistUl'=>'',
					'time'=>'',
					'address'=>'',
					'name'=>'',
					'email'=>'',
					'contact_name'=>'',
					'contact_email'=>'',
					'emailLink'=>'',
					'phone'=>'',
					'website'=>'',
					'websiteLink'=>'',
					'targetLink'=>'',
					'place_name'=>'',
					'place_desc'=>'',
					'city'=>'',
					'country'=>'',
					'coordinate'=>'',
					'lat'=>'',
					'lng'=>'',
					'map'=>'',
					'share'=>'',
					'share_event'=>'',
					'limitRegEmail'=>'',
					'limitRegDate'=>'',

					'gcalendarUrl'=>'',
					'yahoocalendarUrl'=>'',
					'wlivecalendarUrl'=>'',

					'registrations'=>'',

					'registered'=>'',
					'totalRegistered'=>'',
					'registeredUsers'=>'',
					'reg'=>'',
					'regUrl'=>'',
					'iCagendaRegForm'=>'',
					'typeReg'=>'',
					'regEmailUser'=>'',
					'emailUserSubjectPeriod'=>'',
					'emailUserBodyPeriod'=>'',
					'emailUserSubjectDate'=>'',
					'emailUserBodyDate'=>'',
					'language'=>'',
					'params'=>'',

					'gcalendarLink'=>'',
					'loadEventCustomFields'=>'',
					'features'=>'',

					'periodTest'=>'', // DEPRECATED
					'titleLink'=>'', // DEPRECATED
// REMOVED 3.5.3	'placeLeft'=>'',
				)
			)
		);

		return $this->getItems($structure);
	}

	/**
	 * Get Records.
	 *
	 * @return	object list.
	 * @since	3.3.8
	 */
	public function getRecords()
	{
		// Get the current user for authorisation checks
		$user	= JFactory::getUser();

		// Get Params for current view
		$app	= JFactory::getApplication();
		$params	= $app->getParams();

		// Select the required fields from the table.
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);

		$query->select('e.*')
			->from($db->qn('#__icagenda_events') . ' AS e');

		// Join over the language
		$query->select('l.title AS language_title')
			->join('LEFT', $db->quoteName('#__languages') . ' AS l ON l.lang_code = e.language');

		// Join over the users for the checked out user.
//		$query->select('uc.name AS editor');
//		$query->join('LEFT', '#__users AS uc ON uc.id=e.checked_out');

		// Join over the asset groups.
		$query->select('ag.title AS access_level')
			->join('LEFT', '#__viewlevels AS ag ON ag.id = e.access');

		// Join the category
		$query->select('c.title AS category, c.color AS catcolor');
		$query->join('LEFT', '#__icagenda_category AS c ON c.id = e.catid');
		$query->where('c.state = 1');

		// Join over the users for the author.
//		$query->select('ua.name AS author_name, ua.username AS author_username')
//			->join('LEFT', '#__users AS ua ON ua.id = e.created_by');

		// Filter by published state
		$query->where('e.state = 1');

		// Event is approved
		$query->where('e.approval <> 1');

		// Filter by access level.
		$access_levels = implode(',', $user->getAuthorisedViewLevels());

		$query->where('e.access IN (' . $db->q($access_levels) . ')');
//			->where('c.access IN (' . $db->q($access_levels) . ')'); // To be added later, when access integrated to category

		// Filter by language
		$query->where('e.language in (' . $db->q(JFactory::getLanguage()->getTag()) . ',' . $db->q('*') . ')');

		// Filter by Features
		$query->where(icagendaEventsData::getFeaturesFilter());

		// Filter by dates
		$dates_filter	= $params->get('time', 1); // Default Current and Upcoming Events

		// Get today date and datetime based on Joomla Config Timezone.
		$datetime_today	= JHtml::date('now', 'Y-m-d H:i:s');
		$date_today		= JHtml::date('now', 'Y-m-d');

		if (!empty($dates_filter))
		{
			// COM_ICAGENDA_OPTION_TODAY_AND_UPCOMING
			if ($dates_filter == '1')
			{
				$where_current_upcoming = $db->qn('e.next') . ' >= ' . $db->q($date_today);
				$where_current_upcoming.= ' OR (' . $db->qn('e.next') . ' < ' . $db->q($datetime_today) . ' AND ' . $db->qn('e.startdate') . ' <> "0000-00-00 00:00:00" AND ' . $db->qn('e.enddate') . ' > ' . $db->q($datetime_today) . ')';

				$query->where($where_current_upcoming);
			}

			// COM_ICAGENDA_OPTION_PAST
			elseif ($dates_filter == '2')
			{
				$where_past = '(';

				// Period dates with no weekdays filter
				$where_past.= $db->qn('e.next') . ' < ' . $db->q($datetime_today) . ')';
				$where_past.= ' AND (' . $db->qn('e.enddate') . ' < ' . $db->q($datetime_today);

				$where_past.= ' )';

				$query->where($where_past);
			}

			// COM_ICAGENDA_OPTION_FUTURE
			elseif ($dates_filter == '3')
			{
				$where_upcoming = '(';
				$where_upcoming.= $db->qn('e.next') . ' > ' . $db->q($datetime_today);
				$where_upcoming.= ' )';

				$query->where($where_upcoming);
			}

			// COM_ICAGENDA_OPTION_TODAY
			elseif ($dates_filter == '4')
			{
				$where_today = '( ';

				// One day dates filter
				$where_today.= ' (';
				$where_today.= ' (' . $db->qn('e.next') . ' >= ' . $db->q($datetime_today) . ')';
				$where_today.= ' AND (' . $db->qn('e.next') . ' < ' . $db->q($date_today) . ' + INTERVAL 1 DAY)';
				$where_today.= ' )';

				// Period dates with no weekdays filter
				$where_today.= ' OR ( ';
				$where_today.= ' (' . $db->qn('e.next') . ' > ' . $db->q($date_today) . ')';
				$where_today.= ' AND (' . $db->qn('e.weekdays') . ' = "")';
				$where_today.= ' AND ' . $db->qn('e.enddate') . ' <> "0000-00-00 00:00:00" AND (' . $db->qn('e.enddate') . ' >= ' . $db->q($date_today) . ')';
				$where_today.= ' AND ' . $db->qn('e.startdate') . ' <> "0000-00-00 00:00:00" AND (' . $db->qn('e.startdate') . ' < ' . $db->q($date_today) . ')';
				$where_today.= ' )';

				$where_today.= ' )';

				$query->where($where_today);
			}
		}

		// Order Next Date DESC
		$orderby	= $params->get('orderby', 2); // Default ASC
		$ordering	= ($orderby == 1) ? 'DESC' : 'ASC';

		$query->order('e.next ' . $ordering);

		// Tell the database connector what query to run.
		$db->setQuery($query);

		// Invoke the query or data retrieval helper.
		$db_list = $db->loadObjectList();

		return $db_list;
	}


   /**
    * Load Google Maps Scripts.
    *
    * @since	3.5.0
    */
	public static function loadGMapScripts()
	{
		// Google Maps api V3
		$document				= JFactory::getDocument();
		$scripts				= array_keys($document->_scripts);
		$mapsgooglescriptFound	= false;

		for ($i = 0; $i < count($scripts); $i++)
		{
    		if ( stripos($scripts[$i], 'maps.googleapis.com') !== false
    			&& stripos($scripts[$i], 'maps.gstatic.com') !== false )
			{
				$mapsgooglescriptFound = true;
			}
		}

		$doclang	= JFactory::getDocument();
		$curlang	= $doclang->language;
		$lang		= substr($curlang, 0, 2);

		if (!$mapsgooglescriptFound)
		{
			$document->addScript('https://maps.googleapis.com/maps/api/js?sensor=false&librairies=places&language=' . $lang);
		}

		JHtml::script( 'com_icagenda/icmap-front.js', false, true );
	}


   /**
    * Get the return URL.
    *
    * @return	string   The return URL.
    * @since	1.0
    */
	public function getReturnPage()
	{
		return base64_encode($this->getState('return_page'));
	}
}
actionlog.php000060400000011270152456173040007240 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_actionlogs
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Layout\FileLayout;
use Joomla\Utilities\IpHelper;

JLoader::register('ActionlogsHelper', JPATH_ADMINISTRATOR . '/components/com_actionlogs/helpers/actionlogs.php');

/**
 * Methods supporting a list of Actionlog records.
 *
 * @since  3.9.0
 */
class ActionlogsModelActionlog extends JModelLegacy
{
	/**
	 * Function to add logs to the database
	 * This method adds a record to #__action_logs contains (message_language_key, message, date, context, user)
	 *
	 * @param   array    $messages            The contents of the messages to be logged
	 * @param   string   $messageLanguageKey  The language key of the message
	 * @param   string   $context             The context of the content passed to the plugin
	 * @param   integer  $userId              ID of user perform the action, usually ID of current logged in user
	 *
	 * @return  void
	 *
	 * @since   3.9.0
	 */
	public function addLog($messages, $messageLanguageKey, $context, $userId = null)
	{
		$user   = Factory::getUser($userId);
		$db     = $this->getDbo();
		$date   = Factory::getDate();
		$params = ComponentHelper::getComponent('com_actionlogs')->getParams();

		if ($params->get('ip_logging', 0))
		{
			$ip = IpHelper::getIp();

			if (!filter_var($ip, FILTER_VALIDATE_IP))
			{
				$ip = 'COM_ACTIONLOGS_IP_INVALID';
			}
		}
		else
		{
			$ip = 'COM_ACTIONLOGS_DISABLED';
		}

		$loggedMessages = array();

		foreach ($messages as $message)
		{
			$logMessage                       = new stdClass;
			$logMessage->message_language_key = $messageLanguageKey;
			$logMessage->message              = json_encode($message);
			$logMessage->log_date             = (string) $date;
			$logMessage->extension            = $context;
			$logMessage->user_id              = $user->id;
			$logMessage->ip_address           = $ip;
			$logMessage->item_id              = isset($message['id']) ? (int) $message['id'] : 0;

			try
			{
				$db->insertObject('#__action_logs', $logMessage);
				$loggedMessages[] = $logMessage;
			}
			catch (RuntimeException $e)
			{
				// Ignore it
			}
		}

		// Send notification email to users who choose to be notified about the action logs
		$this->sendNotificationEmails($loggedMessages, $user->name, $context);
	}

	/**
	 * Send notification emails about the action log
	 *
	 * @param   array   $messages  The logged messages
	 * @param   string  $username  The username
	 * @param   string  $context   The Context
	 *
	 * @return  void
	 *
	 * @since   3.9.0
	 */
	protected function sendNotificationEmails($messages, $username, $context)
	{
		$db           = $this->getDbo();
		$query        = $db->getQuery(true);
		$params       = ComponentHelper::getParams('com_actionlogs');
		$showIpColumn = (bool) $params->get('ip_logging', 0);

		$query
			->select($db->quoteName(array('u.email', 'l.extensions')))
			->from($db->quoteName('#__users', 'u'))
			->where($db->quoteName('u.block') . ' = 0')
			->join(
				'INNER',
				$db->quoteName('#__action_logs_users', 'l') . ' ON ( ' . $db->quoteName('l.notify') . ' = 1 AND '
				. $db->quoteName('l.user_id') . ' = ' . $db->quoteName('u.id') . ')'
			);

		$db->setQuery($query);

		try
		{
			$users = $db->loadObjectList();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $e->getMessage());

			return;
		}

		$recipients = array();

		foreach ($users as $user)
		{
			$extensions = json_decode($user->extensions, true);

			if ($extensions && in_array(strtok($context, '.'), $extensions))
			{
				$recipients[] = $user->email;
			}
		}

		if (empty($recipients))
		{
			return;
		}

		$layout    = new FileLayout('components.com_actionlogs.layouts.logstable', JPATH_ADMINISTRATOR);
		$extension = strtok($context, '.');
		ActionlogsHelper::loadTranslationFiles($extension);

		foreach ($messages as $message)
		{
			$message->extension = Text::_($extension);
			$message->message   = ActionlogsHelper::getHumanReadableLogMessage($message);
		}

		$displayData = array(
			'messages'     => $messages,
			'username'     => $username,
			'showIpColumn' => $showIpColumn,
		);

		$body   = $layout->render($displayData);
		$mailer = Factory::getMailer();
		$mailer->addRecipient($recipients);
		$mailer->setSubject(Text::_('COM_ACTIONLOGS_EMAIL_SUBJECT'));
		$mailer->isHTML(true);
		$mailer->Encoding = 'base64';
		$mailer->setBody($body);

		if (!$mailer->Send())
		{
			JError::raiseWarning(500, Text::_('JERROR_SENDING_EMAIL'));
		}
	}
}
fields/logtype.php000060400000003213152456173040010210 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  System.actionlogs
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Application\ApplicationHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;

FormHelper::loadFieldClass('checkboxes');
JLoader::register('ActionlogsHelper', JPATH_ADMINISTRATOR . '/components/com_actionlogs/helpers/actionlogs.php');

/**
 * Field to load a list of all users that have logged actions
 *
 * @since 3.9.0
 */
class JFormFieldLogType extends JFormFieldCheckboxes
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.9.0
	 */
	protected $type = 'LogType';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.9.0
	 */
	public function getOptions()
	{
		$db = Factory::getDbo();
		$query = $db->getQuery(true)
			->select($db->quoteName('extension'))
			->from($db->quoteName('#__action_logs_extensions'));

		$extensions = $db->setQuery($query)->loadColumn();

		$options = array();
		$tmp     = array('checked' => true);

		foreach ($extensions as $extension)
		{
			ActionlogsHelper::loadTranslationFiles($extension);
			$option = HTMLHelper::_('select.option', $extension, Text::_($extension));
			$options[ApplicationHelper::stringURLSafe(Text::_($extension)) . '_' . $extension] = (object) array_merge($tmp, (array) $option);
		}

		ksort($options);

		return array_merge(parent::getOptions(), array_values($options));
	}
}
fields/plugininfo.php000060400000002702152456173040010701 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_actionlogs
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Information field.
 *
 * @since  3.9.2
 */
class JFormFieldPluginInfo extends JFormField
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.9.2
	 */
	protected $type = 'PluginInfo';

	/**
	 * Method to get the field input markup.
	 *
	 * @return  string	The field input markup.
	 *
	 * @since   3.9.2
	 */
	protected function getInput()
	{
		$db = JFactory::getDbo();
		$result = null;
		$query = $db->getQuery(true)
			->select($db->quoteName('extension_id'))
			->from($db->quoteName('#__extensions'))
			->where($db->quoteName('folder') . ' = ' . $db->quote('actionlog'))
			->where($db->quoteName('element') . ' = ' . $db->quote('joomla'));
		$db->setQuery($query);

		try
		{
			$result = (int) $db->loadResult();
		}
		catch (RuntimeException $e)
		{
			JError::raiseWarning(500, $e->getMessage());
		}

		$link = JHtml::_(
			'link',
			JRoute::_('index.php?option=com_plugins&task=plugin.edit&extension_id=' . $result),
			JText::_('PLG_SYSTEM_ACTIONLOGS_JOOMLA_ACTIONLOG_DISABLED'),
			array('class' => 'alert-link')
		);

		return '<div class="alert alert-info">'
			. JText::sprintf('PLG_SYSTEM_ACTIONLOGS_JOOMLA_ACTIONLOG_DISABLED_REDIRECT', $link)
			. '</div>';
	}
}
fields/logcreator.php000060400000003423152456173040010671 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_actionlogs
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormHelper;

FormHelper::loadFieldClass('list');

/**
 * Field to load a list of all users that have logged actions
 *
 * @since  3.9.0
 */
class JFormFieldLogCreator extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.9.0
	 */
	protected $type = 'LogCreator';

	/**
	 * Cached array of the category items.
	 *
	 * @var    array
	 * @since  3.9.0
	 */
	protected static $options = array();

	/**
	 * Method to get the options to populate list
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.9.0
	 */
	protected function getOptions()
	{
		// Accepted modifiers
		$hash = md5($this->element);

		if (!isset(static::$options[$hash]))
		{
			static::$options[$hash] = parent::getOptions();

			$options = array();

			$db = Factory::getDbo();

			// Construct the query
			$query = $db->getQuery(true)
				->select($db->quoteName('u.id', 'value'))
				->select($db->quoteName('u.username', 'text'))
				->from($db->quoteName('#__users', 'u'))
				->join('INNER', $db->quoteName('#__action_logs', 'c') . ' ON ' . $db->quoteName('c.user_id') . ' = ' . $db->quoteName('u.id'))
				->group($db->quoteName('u.id'))
				->group($db->quoteName('u.username'))
				->order($db->quoteName('u.username'));

			// Setup the query
			$db->setQuery($query);

			// Return the result
			if ($options = $db->loadObjectList())
			{
				static::$options[$hash] = array_merge(static::$options[$hash], $options);
			}
		}

		return static::$options[$hash];
	}
}
fields/extension.php000060400000003155152456173040010546 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_actionlogs
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormHelper;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Language\Text;

FormHelper::loadFieldClass('list');
JLoader::register('ActionlogsHelper', JPATH_ADMINISTRATOR . '/components/com_actionlogs/helpers/actionlogs.php');

/**
 * Field to load a list of all extensions that have logged actions
 *
 * @since  3.9.0
 */
class JFormFieldExtension extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.9.0
	 */
	protected $type = 'extension';

	/**
	 * Method to get the options to populate list
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.9.0
	 */
	public function getOptions()
	{
		$db = Factory::getDbo();
		$query = $db->getQuery(true)
			->select('DISTINCT ' . $db->quoteName('extension'))
			->from($db->quoteName('#__action_logs'))
			->order($db->quoteName('extension'));

		$db->setQuery($query);
		$context = $db->loadColumn();

		$options = array();

		if (count($context) > 0)
		{
			foreach ($context as $item)
			{
				$extensions[] = strtok($item, '.');
			}

			$extensions = array_unique($extensions);

			foreach ($extensions as $extension)
			{
				ActionlogsHelper::loadTranslationFiles($extension);
				$options[] = HTMLHelper::_('select.option', $extension, Text::_($extension));
			}
		}

		return array_merge(parent::getOptions(), $options);
	}
}
fields/logsdaterange.php000060400000002675152456173040011357 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_actionlogs
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormHelper;

FormHelper::loadFieldClass('predefinedlist');

/**
 * Field to show a list of range dates to sort with
 *
 * @since  3.9.0
 */
class JFormFieldLogsDateRange extends JFormFieldPredefinedList
{
	/**
	 * The form field type.
	 *
	 * @var     string
	 * @since   3.9.0
	 */
	protected $type = 'logsdaterange';

	/**
	 * Available options
	 *
	 * @var    array
	 * @since  3.9.0
	 */
	protected $predefinedOptions = array(
		'today'       => 'COM_ACTIONLOGS_OPTION_RANGE_TODAY',
		'past_week'   => 'COM_ACTIONLOGS_OPTION_RANGE_PAST_WEEK',
		'past_1month' => 'COM_ACTIONLOGS_OPTION_RANGE_PAST_1MONTH',
		'past_3month' => 'COM_ACTIONLOGS_OPTION_RANGE_PAST_3MONTH',
		'past_6month' => 'COM_ACTIONLOGS_OPTION_RANGE_PAST_6MONTH',
		'past_year'   => 'COM_ACTIONLOGS_OPTION_RANGE_PAST_YEAR',
	);

	/**
	 * Method to instantiate the form field object.
	 *
	 * @param   JForm  $form  The form to attach to the form field object.
	 *
	 * @since  3.9.0
	 */
	public function __construct($form = null)
	{
		parent::__construct($form);

		// Load the required language
		$lang = Factory::getLanguage();
		$lang->load('com_actionlogs', JPATH_ADMINISTRATOR);
	}
}
actionlogs.php000060400000022125152456173040007424 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_actionlogs
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Date\Date;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\Utilities\ArrayHelper;

/**
 * Methods supporting a list of article records.
 *
 * @since  3.9.0
 */
class ActionlogsModelActionlogs extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @since   3.9.0
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'a.id', 'id',
				'a.extension', 'extension',
				'a.user_id', 'user',
				'a.message', 'message',
				'a.log_date', 'log_date',
				'a.ip_address', 'ip_address',
				'dateRange',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * @return  void
	 *
	 * @since   3.9.0
	 */
	protected function populateState($ordering = 'a.id', $direction = 'desc')
	{
		$app = Factory::getApplication();

		$search = $app->getUserStateFromRequest($this->context . 'filter.search', 'filter_search', '', 'string');
		$this->setState('filter.search', $search);

		$user = $app->getUserStateFromRequest($this->context . 'filter.user', 'filter_user', '', 'string');
		$this->setState('filter.user', $user);

		$extension = $app->getUserStateFromRequest($this->context . 'filter.extension', 'filter_extension', '', 'string');
		$this->setState('filter.extension', $extension);

		$ip_address = $app->getUserStateFromRequest($this->context . 'filter.ip_address', 'filter_ip_address', '', 'string');
		$this->setState('filter.ip_address', $ip_address);

		$dateRange = $app->getUserStateFromRequest($this->context . 'filter.dateRange', 'filter_dateRange', '', 'string');
		$this->setState('filter.dateRange', $dateRange);

		parent::populateState($ordering, $direction);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   3.9.0
	 */
	protected function getListQuery()
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->select('a.*, u.name')
			->from('#__action_logs AS a')
			->leftJoin('#__users AS u ON a.user_id = u.id');

		// Get ordering
		$fullorderCol = $this->state->get('list.fullordering', 'a.id DESC');

		// Apply ordering
		if (!empty($fullorderCol))
		{
			$query->order($db->escape($fullorderCol));
		}

		// Get filter by user
		$user = $this->getState('filter.user');

		// Apply filter by user
		if (!empty($user))
		{
			$query->where($db->quoteName('a.user_id') . ' = ' . (int) $user);
		}

		// Get filter by extension
		$extension = $this->getState('filter.extension');

		// Apply filter by extension
		if (!empty($extension))
		{
			$query->where($db->quoteName('a.extension') . ' LIKE ' . $db->quote($extension . '%'));
		}

		// Get filter by date range
		$dateRange = $this->getState('filter.dateRange');

		// Apply filter by date range
		if (!empty($dateRange))
		{
			$date = $this->buildDateRange($dateRange);

			// If the chosen range is not more than a year ago
			if ($date['dNow'] != false)
			{
				$query->where(
					$db->qn('a.log_date') . ' >= ' . $db->quote($date['dStart']->format('Y-m-d H:i:s')) .
					' AND ' . $db->qn('a.log_date') . ' <= ' . $db->quote($date['dNow']->format('Y-m-d H:i:s'))
				);
			}
		}

		// Filter the items over the search string if set.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->quoteName('a.id') . ' = ' . (int) substr($search, 3));
			}
			elseif (stripos($search, 'item_id:') === 0)
			{
				$query->where($db->quoteName('a.item_id') . ' = ' . (int) substr($search, 8));
			}
			else
			{
				$search = $db->quote('%' . $db->escape($search, true) . '%');
				$query->where('(' . $db->quoteName('u.username') . ' LIKE ' . $search . ')');
			}
		}

		return $query;
	}

	/**
	 * Construct the date range to filter on.
	 *
	 * @param   string  $range  The textual range to construct the filter for.
	 *
	 * @return  array  The date range to filter on.
	 *
	 * @since   3.9.0
	 */
	private function buildDateRange($range)
	{
		// Get UTC for now.
		$dNow   = new Date;
		$dStart = clone $dNow;

		switch ($range)
		{
			case 'past_week':
				$dStart->modify('-7 day');
				break;

			case 'past_1month':
				$dStart->modify('-1 month');
				break;

			case 'past_3month':
				$dStart->modify('-3 month');
				break;

			case 'past_6month':
				$dStart->modify('-6 month');
				break;

			case 'past_year':
				$dStart->modify('-1 year');
				break;

			case 'today':
				// Ranges that need to align with local 'days' need special treatment.
				$offset = Factory::getApplication()->get('offset');

				// Reset the start time to be the beginning of today, local time.
				$dStart = new Date('now', $offset);
				$dStart->setTime(0, 0, 0);

				// Now change the timezone back to UTC.
				$tz = new DateTimeZone('GMT');
				$dStart->setTimezone($tz);
				break;
		}

		return array('dNow' => $dNow, 'dStart' => $dStart);
	}

	/**
	 * Get all log entries for an item
	 *
	 * @param   string   $extension  The extension the item belongs to
	 * @param   integer  $itemId     The item ID
	 *
	 * @return  array
	 *
	 * @since   3.9.0
	 */
	public function getLogsForItem($extension, $itemId)
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->select('a.*, u.name')
			->from('#__action_logs AS a')
			->innerJoin('#__users AS u ON a.user_id = u.id')
			->where($db->quoteName('a.extension') . ' = ' . $db->quote($extension))
			->where($db->quoteName('a.item_id') . ' = ' . (int) $itemId);

		// Get ordering
		$fullorderCol = $this->getState('list.fullordering', 'a.id DESC');

		// Apply ordering
		if (!empty($fullorderCol))
		{
			$query->order($db->escape($fullorderCol));
		}

		$db->setQuery($query);

		return $db->loadObjectList();
	}

	/**
	 * Get logs data into JTable object
	 *
	 * @param   integer[]|null  $pks  An optional array of log record IDs to load
	 *
	 * @return  array  All logs in the table
	 *
	 * @since   3.9.0
	 */
	public function getLogsData($pks = null)
	{
		$db    = $this->getDbo();
		$query = $this->getLogDataQuery($pks);

		$db->setQuery($query);

		return $db->loadObjectList();
	}

	/**
	 * Get logs data as a database iterator
	 *
	 * @param   integer[]|null  $pks  An optional array of log record IDs to load
	 *
	 * @return  JDatabaseIterator
	 *
	 * @since   3.9.0
	 */
	public function getLogDataAsIterator($pks = null)
	{
		$db    = $this->getDbo();
		$query = $this->getLogDataQuery($pks);

		$db->setQuery($query);

		return $db->getIterator();
	}

	/**
	 * Get the query for loading logs data
	 *
	 * @param   integer[]|null  $pks  An optional array of log record IDs to load
	 *
	 * @return  JDatabaseQuery
	 *
	 * @since   3.9.0
	 */
	private function getLogDataQuery($pks = null)
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->select('a.*, u.name')
			->from('#__action_logs AS a')
			->innerJoin('#__users AS u ON a.user_id = u.id');

		if (is_array($pks) && count($pks) > 0)
		{
			$query->where($db->quoteName('a.id') . ' IN (' . implode(',', ArrayHelper::toInteger($pks)) . ')');
		}

		return $query;
	}

	/**
	 * Delete logs
	 *
	 * @param   array  $pks  Primary keys of logs
	 *
	 * @return  boolean
	 *
	 * @since   3.9.0
	 */
	public function delete(&$pks)
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__action_logs'))
			->where($db->quoteName('id') . ' IN (' . implode(',', ArrayHelper::toInteger($pks)) . ')');
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (RuntimeException $e)
		{
			$this->setError($e->getMessage());

			return false;
		}

		Factory::getApplication()->triggerEvent('onAfterLogPurge', array());

		return true;
	}

	/**
	 * Removes all of logs from the table.
	 *
	 * @return  boolean result of operation
	 *
	 * @since   3.9.0
	 */
	public function purge()
	{
		try
		{
			$this->getDbo()->truncateTable('#__action_logs');
		}
		catch (Exception $e)
		{
			return false;
		}

		Factory::getApplication()->triggerEvent('onAfterLogPurge', array());

		return true;
	}

	/**
	 * Get the filter form
	 *
	 * @param   array    $data      data
	 * @param   boolean  $loadData  load current data
	 *
	 * @return  \JForm|boolean  The \JForm object or false on error
	 *
	 * @since  3.9.0
	 */
	public function getFilterForm($data = array(), $loadData = true)
	{
		$form      = parent::getFilterForm($data, $loadData);
		$params    = ComponentHelper::getParams('com_actionlogs');
		$ipLogging = (bool) $params->get('ip_logging', 0);

		// Add ip sort options to sort dropdown
		if ($form && $ipLogging)
		{
			/* @var JFormFieldList $field */
			$field = $form->getField('fullordering', 'list');
			$field->addOption(Text::_('COM_ACTIONLOGS_IP_ADDRESS_ASC'), array('value' => 'a.ip_address ASC'));
			$field->addOption(Text::_('COM_ACTIONLOGS_IP_ADDRESS_DESC'), array('value' => 'a.ip_address DESC'));
		}

		return $form;
	}
}
forms/filter_actionlogs.xml000060400000004065152456173040012133 0ustar00<?xml version="1.0" encoding="UTF-8"?>
<form>
	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			description="COM_ACTIONLOGS_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>
		<field
			name="extension"
			type="extension"
			label="COM_ACTIONLOGS_EXTENSION"
			description="COM_ACTIONLOGS_EXTENSION_FILTER_DESC"
			onchange="this.form.submit()"
			>
			<option value="">COM_ACTIONLOGS_SELECT_EXTENSION</option>
		</field>
		<field
			name="dateRange"
			type="logsdaterange"
			label="COM_ACTIONLOGS_OPTION_FILTER_DATE"
			description="COM_ACTIONLOGS_OPTION_FILTER_DATE"
			onchange="this.form.submit();"
			>
			<option value="">COM_ACTIONLOGS_OPTION_FILTER_DATE</option>
		</field>
		<field
			name="user"
			type="logcreator"
			onchange="this.form.submit();"
			>
			<option value="">COM_ACTIONLOGS_SELECT_USER</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="COM_ACTIONLOGS_LIST_FULL_ORDERING"
			description="COM_ACTIONLOGS_LIST_FULL_ORDERING_DESC"
			onchange="this.form.submit();"
			default="a.id DESC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="a.message ASC">COM_ACTIONLOGS_ACTION_ASC</option>
			<option value="a.message DESC">COM_ACTIONLOGS_ACTION_DESC</option>
			<option value="a.extension ASC">COM_ACTIONLOGS_EXTENSION_ASC</option>
			<option value="a.extension DESC">COM_ACTIONLOGS_EXTENSION_DESC</option>
			<option value="a.log_date ASC">JDATE_ASC</option>
			<option value="a.log_date DESC">JDATE_DESC</option>
			<option value="a.user_id ASC">COM_ACTIONLOGS_NAME_ASC</option>
			<option value="a.user_id DESC">COM_ACTIONLOGS_NAME_DESC</option>
			<option value="a.id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="a.id DESC">JGRID_HEADING_ID_DESC</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="limit"
			type="limitbox"
			label="COM_ACTIONLOGS_LIST_LIMIT"
			description="COM_ACTIONLOGS_LIST_LIMIT_DESC"
			class="input-mini"
			onchange="this.form.submit();"
			default="25"
		/>
	</fields>
</form>
updatesites.php000060400000035444152456173470007633 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2014 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('InstallerModel', __DIR__ . '/extension.php');

/**
 * Installer Update Sites Model
 *
 * @since  3.4
 */
class InstallerModelUpdatesites extends InstallerModel
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   3.4
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'update_site_name',
				'name',
				'client_id',
				'client', 'client_translated',
				'status',
				'type', 'type_translated',
				'folder', 'folder_translated',
				'update_site_id',
				'enabled',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   3.4
	 */
	protected function populateState($ordering = 'name', $direction = 'asc')
	{
		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.client_id', $this->getUserStateFromRequest($this->context . '.filter.client_id', 'filter_client_id', null, 'int'));
		$this->setState('filter.enabled', $this->getUserStateFromRequest($this->context . '.filter.enabled', 'filter_enabled', '', 'string'));
		$this->setState('filter.type', $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'string'));
		$this->setState('filter.folder', $this->getUserStateFromRequest($this->context . '.filter.folder', 'filter_folder', '', 'string'));

		parent::populateState($ordering, $direction);
	}

	/**
	 * Enable/Disable an extension.
	 *
	 * @param   array  $eid    Extension ids to un/publish
	 * @param   int    $value  Publish value
	 *
	 * @return  boolean  True on success
	 *
	 * @since   3.4
	 *
	 * @throws  Exception on ACL error
	 */
	public function publish(&$eid = array(), $value = 1)
	{
		if (!JFactory::getUser()->authorise('core.edit.state', 'com_installer'))
		{
			throw new Exception(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), 403);
		}

		$result = true;

		// Ensure eid is an array of extension ids
		if (!is_array($eid))
		{
			$eid = array($eid);
		}

		// Get a table object for the extension type
		$table = JTable::getInstance('Updatesite');

		// Enable the update site in the table and store it in the database
		foreach ($eid as $i => $id)
		{
			$table->load($id);
			$table->enabled = $value;

			if (!$table->store())
			{
				$this->setError($table->getError());
				$result = false;
			}
		}

		return $result;
	}

	/**
	 * Deletes an update site.
	 *
	 * @param   array  $ids  Extension ids to delete.
	 *
	 * @return  void
	 *
	 * @since   3.6
	 *
	 * @throws  Exception on ACL error
	 */
	public function delete($ids = array())
	{
		if (!JFactory::getUser()->authorise('core.delete', 'com_installer'))
		{
			throw new Exception(JText::_('JLIB_APPLICATION_ERROR_DELETE_NOT_PERMITTED'), 403);
		}

		// Ensure eid is an array of extension ids
		if (!is_array($ids))
		{
			$ids = array($ids);
		}

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

		$count = 0;

		// Gets the update site names.
		$query = $db->getQuery(true)
			->select($db->qn(array('update_site_id', 'name')))
			->from($db->qn('#__update_sites'))
			->where($db->qn('update_site_id') . ' IN (' . implode(', ', $ids) . ')');
		$db->setQuery($query);
		$updateSitesNames = $db->loadObjectList('update_site_id');

		// Gets Joomla core update sites Ids.
		$joomlaUpdateSitesIds = $this->getJoomlaUpdateSitesIds(0);

		// Enable the update site in the table and store it in the database
		foreach ($ids as $i => $id)
		{
			// Don't allow to delete Joomla Core update sites.
			if (in_array((int) $id, $joomlaUpdateSitesIds))
			{
				$app->enqueueMessage(JText::sprintf('COM_INSTALLER_MSG_UPDATESITES_DELETE_CANNOT_DELETE', $updateSitesNames[$id]->name), 'error');
				continue;
			}

			// Delete the update site from all tables.
			try
			{
				$query = $db->getQuery(true)
					->delete($db->qn('#__update_sites'))
					->where($db->qn('update_site_id') . ' = ' . (int) $id);
				$db->setQuery($query);
				$db->execute();

				$query = $db->getQuery(true)
					->delete($db->qn('#__update_sites_extensions'))
					->where($db->qn('update_site_id') . ' = ' . (int) $id);
				$db->setQuery($query);
				$db->execute();

				$query = $db->getQuery(true)
					->delete($db->qn('#__updates'))
					->where($db->qn('update_site_id') . ' = ' . (int) $id);
				$db->setQuery($query);
				$db->execute();

				$count++;
			}
			catch (RuntimeException $e)
			{
				$app->enqueueMessage(JText::sprintf('COM_INSTALLER_MSG_UPDATESITES_DELETE_ERROR', $updateSitesNames[$id]->name, $e->getMessage()), 'error');
			}
		}

		if ($count > 0)
		{
			$app->enqueueMessage(JText::plural('COM_INSTALLER_MSG_UPDATESITES_N_DELETE_UPDATESITES_DELETED', $count), 'message');
		}
	}

	/**
	 * Rebuild update sites tables.
	 *
	 * @return  void
	 *
	 * @since   3.6
	 *
	 * @throws  Exception on ACL error
	 */
	public function rebuild()
	{
		if (!JFactory::getUser()->authorise('core.admin', 'com_installer'))
		{
			throw new Exception(JText::_('COM_INSTALLER_MSG_UPDATESITES_REBUILD_NOT_PERMITTED'), 403);
		}

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

		// Check if Joomla Extension plugin is enabled.
		if (!JPluginHelper::isEnabled('extension', 'joomla'))
		{
			$query = $db->getQuery(true)
				->select($db->quoteName('extension_id'))
				->from($db->quoteName('#__extensions'))
				->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
				->where($db->quoteName('element') . ' = ' . $db->quote('joomla'))
				->where($db->quoteName('folder') . ' = ' . $db->quote('extension'));
			$db->setQuery($query);

			$pluginId = (int) $db->loadResult();

			$link = JRoute::_('index.php?option=com_plugins&task=plugin.edit&extension_id=' . $pluginId);
			$app->enqueueMessage(JText::sprintf('COM_INSTALLER_MSG_UPDATESITES_REBUILD_EXTENSION_PLUGIN_NOT_ENABLED', $link), 'error');

			return;
		}

		$clients               = array(JPATH_SITE, JPATH_ADMINISTRATOR);
		$extensionGroupFolders = array('components', 'modules', 'plugins', 'templates', 'language', 'manifests');

		$pathsToSearch = array();

		// Identifies which folders to search for manifest files.
		foreach ($clients as $clientPath)
		{
			foreach ($extensionGroupFolders as $extensionGroupFolderName)
			{
				// Components, modules, plugins, templates, languages and manifest (files, libraries, etc)
				if ($extensionGroupFolderName != 'plugins')
				{
					foreach (glob($clientPath . '/' . $extensionGroupFolderName . '/*', GLOB_NOSORT | GLOB_ONLYDIR) as $extensionFolderPath)
					{
						$pathsToSearch[] = $extensionFolderPath;
					}
				}

				// Plugins (another directory level is needed)
				else
				{
					foreach (glob($clientPath . '/' . $extensionGroupFolderName . '/*', GLOB_NOSORT | GLOB_ONLYDIR) as $pluginGroupFolderPath)
					{
						foreach (glob($pluginGroupFolderPath . '/*', GLOB_NOSORT | GLOB_ONLYDIR) as $extensionFolderPath)
						{
							$pathsToSearch[] = $extensionFolderPath;
						}
					}
				}
			}
		}

		// Gets Joomla core update sites Ids.
		$joomlaUpdateSitesIds = implode(', ', $this->getJoomlaUpdateSitesIds(0));

		// First backup any custom extra_query for the sites
		$query = $db->getQuery(true)
			->select('TRIM(' . $db->quoteName('location') . ') AS ' . $db->quoteName('location') . ', ' . $db->quoteName('extra_query'))
			->from($db->quoteName('#__update_sites'));
		$db->setQuery($query);
		$backupExtraQuerys = $db->loadAssocList('location');

		// Delete from all tables (except joomla core update sites).
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__update_sites'))
			->where($db->quoteName('update_site_id') . ' NOT IN (' . $joomlaUpdateSitesIds . ')');
		$db->setQuery($query);
		$db->execute();

		$query = $db->getQuery(true)
			->delete($db->quoteName('#__update_sites_extensions'))
			->where($db->quoteName('update_site_id') . ' NOT IN (' . $joomlaUpdateSitesIds . ')');
		$db->setQuery($query);
		$db->execute();

		$query = $db->getQuery(true)
			->delete($db->quoteName('#__updates'))
			->where($db->quoteName('update_site_id') . ' NOT IN (' . $joomlaUpdateSitesIds . ')');
		$db->setQuery($query);
		$db->execute();

		$count = 0;

		// Gets Joomla core extension Ids.
		$joomlaCoreExtensionIds = implode(', ', $this->getJoomlaUpdateSitesIds(1));

		// Search for updateservers in manifest files inside the folders to search.
		foreach ($pathsToSearch as $extensionFolderPath)
		{
			$tmpInstaller = new JInstaller;

			$tmpInstaller->setPath('source', $extensionFolderPath);

			// Main folder manifests (higher priority)
			$parentXmlfiles = JFolder::files($tmpInstaller->getPath('source'), '.xml$', false, true);

			// Search for children manifests (lower priority)
			$allXmlFiles    = JFolder::files($tmpInstaller->getPath('source'), '.xml$', 1, true);

			// Create an unique array of files ordered by priority
			$xmlfiles = array_unique(array_merge($parentXmlfiles, $allXmlFiles));

			if (!empty($xmlfiles))
			{
				foreach ($xmlfiles as $file)
				{
					// Is it a valid Joomla installation manifest file?
					$manifest = $tmpInstaller->isManifest($file);

					if (!is_null($manifest))
					{
						// Search if the extension exists in the extensions table. Excluding joomla core extensions and discovered but not yet installed extensions.
						$query = $db->getQuery(true)
							->select($db->quoteName('extension_id'))
							->from($db->quoteName('#__extensions'))
							->where('('
								. $db->quoteName('name') . ' = ' . $db->quote($manifest->name)
								. ' OR ' . $db->quoteName('name') . ' = ' . $db->quote($manifest->packagename)
								. ')' )
							->where($db->quoteName('type') . ' = ' . $db->quote($manifest['type']))
							->where($db->quoteName('extension_id') . ' NOT IN (' . $joomlaCoreExtensionIds . ')')
							->where($db->quoteName('state') . ' != -1');
						$db->setQuery($query);

						$eid = (int) $db->loadResult();

						if ($eid && $manifest->updateservers)
						{
							// Set the manifest object and path
							$tmpInstaller->manifest = $manifest;
							$tmpInstaller->setPath('manifest', $file);

							// Remove last extra_query as we are in a foreach
							$tmpInstaller->extraQuery = '';

							if ($tmpInstaller->manifest->updateservers
								&& $tmpInstaller->manifest->updateservers->server
								&& isset($backupExtraQuerys[trim((string) $tmpInstaller->manifest->updateservers->server)]))
							{
								$tmpInstaller->extraQuery = $backupExtraQuerys[trim((string) $tmpInstaller->manifest->updateservers->server)]['extra_query'];
							}

							// Load the extension plugin (if not loaded yet).
							JPluginHelper::importPlugin('extension', 'joomla');

							// Fire the onExtensionAfterUpdate
							JEventDispatcher::getInstance()->trigger('onExtensionAfterUpdate', array('installer' => $tmpInstaller, 'eid' => $eid));

							$count++;
						}
					}
				}
			}
		}

		if ($count > 0)
		{
			$app->enqueueMessage(JText::_('COM_INSTALLER_MSG_UPDATESITES_REBUILD_SUCCESS'), 'message');
		}
		else
		{
			$app->enqueueMessage(JText::_('COM_INSTALLER_MSG_UPDATESITES_REBUILD_MESSAGE'), 'message');
		}
		
		// Flush the system cache to ensure extra_query is correctly loaded next time.
		$this->cleanCache('_system', 1);
	}

	/**
	 * Fetch the Joomla update sites ids.
	 *
	 * @param   integer  $column  Column to return. 0 for update site ids, 1 for extension ids.
	 *
	 * @return  array  Array with joomla core update site ids.
	 *
	 * @since   3.6.0
	 */
	protected function getJoomlaUpdateSitesIds($column = 0)
	{
		$db  = JFactory::getDbo();

		// Fetch the Joomla core update sites ids and their extension ids. We search for all except the core joomla extension with update sites.
		$query = $db->getQuery(true)
			->select($db->quoteName(array('use.update_site_id', 'e.extension_id')))
			->from($db->quoteName('#__update_sites_extensions', 'use'))
			->join('LEFT', $db->quoteName('#__update_sites', 'us') . ' ON ' . $db->qn('us.update_site_id') . ' = ' . $db->qn('use.update_site_id'))
			->join('LEFT', $db->quoteName('#__extensions', 'e') . ' ON ' . $db->qn('e.extension_id') . ' = ' . $db->qn('use.extension_id'))
			->where('('
				. '(' . $db->qn('e.type') . ' = ' . $db->quote('file') . ' AND ' . $db->qn('e.element') . ' = ' . $db->quote('joomla') . ')'
				. ' OR (' . $db->qn('e.type') . ' = ' . $db->quote('package') . ' AND ' . $db->qn('e.element') . ' = ' . $db->quote('pkg_en-GB') . ')'
				. ' OR (' . $db->qn('e.type') . ' = ' . $db->quote('component') . ' AND ' . $db->qn('e.element') . ' = ' . $db->quote('com_joomlaupdate') . ')'
				. ')'
			);

		$db->setQuery($query);

		return $db->loadColumn($column);
	}

	/**
	 * Method to get the database query
	 *
	 * @return  JDatabaseQuery  The database query
	 *
	 * @since   3.4
	 */
	protected function getListQuery()
	{
		$query = JFactory::getDbo()->getQuery(true)
			->select(
				array(
					's.update_site_id',
					's.name AS update_site_name',
					's.type AS update_site_type',
					's.location',
					's.enabled',
					's.extra_query',
					'e.extension_id',
					'e.name',
					'e.type',
					'e.element',
					'e.folder',
					'e.client_id',
					'e.state',
					'e.manifest_cache',
				)
			)
			->from('#__update_sites AS s')
			->innerJoin('#__update_sites_extensions AS se ON (se.update_site_id = s.update_site_id)')
			->innerJoin('#__extensions AS e ON (e.extension_id = se.extension_id)')
			->where('state = 0');

		// Process select filters.
		$enabled  = $this->getState('filter.enabled');
		$type     = $this->getState('filter.type');
		$clientId = $this->getState('filter.client_id');
		$folder   = $this->getState('filter.folder');

		if ($enabled != '')
		{
			$query->where('s.enabled = ' . (int) $enabled);
		}

		if ($type)
		{
			$query->where('e.type = ' . $this->_db->quote($type));
		}

		if ($clientId != '')
		{
			$query->where('e.client_id = ' . (int) $clientId);
		}

		if ($folder != '' && in_array($type, array('plugin', 'library', '')))
		{
			$query->where('e.folder = ' . $this->_db->quote($folder == '*' ? '' : $folder));
		}

		// Process search filter (update site id).
		$search = $this->getState('filter.search');

		if (!empty($search) && stripos($search, 'id:') === 0)
		{
			$query->where('s.update_site_id = ' . (int) substr($search, 3));
		}

		// Note: The search for name, ordering and pagination are processed by the parent InstallerModel class (in extension.php).

		return $query;
	}
}
warnings.php000060400000010006152456173470007114 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Installer Warnings Model
 *
 * @since  1.6
 */
class InstallerModelWarnings extends JModelList
{
	/**
	 * Extension Type
	 * @var	string
	 */
	public $type = 'warnings';

	/**
	 * Return the byte value of a particular string.
	 *
	 * @param   string  $val  String optionally with G, M or K suffix
	 *
	 * @return  integer   size in bytes
	 *
	 * @since 1.6
	 */
	public function return_bytes($val)
	{
		if (empty($val))
		{
			return 0;
		}

		$val = trim($val);

		preg_match('#([0-9]+)[\s]*([a-z]+)#i', $val, $matches);

		$last = '';

		if (isset($matches[2]))
		{
			$last = $matches[2];
		}

		if (isset($matches[1]))
		{
			$val = (int) $matches[1];
		}

		switch (strtolower($last))
		{
			case 'g':
			case 'gb':
				$val *= 1024;
			case 'm':
			case 'mb':
				$val *= 1024;
			case 'k':
			case 'kb':
				$val *= 1024;
		}

		return (int) $val;
	}

	/**
	 * Load the data.
	 *
	 * @return  array  Messages
	 *
	 * @since   1.6
	 */
	public function getItems()
	{
		static $messages;

		if ($messages)
		{
			return $messages;
		}

		$messages = array();
		$file_uploads = ini_get('file_uploads');

		if (!$file_uploads)
		{
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_FILEUPLOADSDISABLED'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_FILEUPLOADISDISABLEDDESC'));
		}

		$upload_dir = ini_get('upload_tmp_dir');

		if (!$upload_dir)
		{
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTSET'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTSETDESC'));
		}
		else
		{
			if (!is_writeable($upload_dir))
			{
				$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTWRITEABLE'),
						'description' => JText::sprintf('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTWRITEABLEDESC', $upload_dir));
			}
		}

		$config = JFactory::getConfig();
		$tmp_path = $config->get('tmp_path');

		if (!$tmp_path)
		{
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTSET'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTSETDESC'));
		}
		else
		{
			if (!is_writeable($tmp_path))
			{
				$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTWRITEABLE'),
						'description' => JText::sprintf('COM_INSTALLER_MSG_WARNINGS_JOOMLATMPNOTWRITEABLEDESC', $tmp_path));
			}
		}

		$memory_limit = $this->return_bytes(ini_get('memory_limit'));

		if ($memory_limit < (8 * 1024 * 1024) && $memory_limit != -1)
		{
			// 8MB
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_LOWMEMORYWARN'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_LOWMEMORYDESC'));
		}
		elseif ($memory_limit < (16 * 1024 * 1024) && $memory_limit != -1)
		{
			// 16MB
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_MEDMEMORYWARN'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_MEDMEMORYDESC'));
		}

		$post_max_size = $this->return_bytes(ini_get('post_max_size'));
		$upload_max_filesize = $this->return_bytes(ini_get('upload_max_filesize'));

		if ($post_max_size < $upload_max_filesize)
		{
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_UPLOADBIGGERTHANPOST'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_UPLOADBIGGERTHANPOSTDESC'));
		}

		if ($post_max_size < (8 * 1024 * 1024)) // 8MB
		{
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLPOSTSIZE'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLPOSTSIZEDESC'));
		}

		if ($upload_max_filesize < (8 * 1024 * 1024)) // 8MB
		{
			$messages[] = array('message' => JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLUPLOADSIZE'),
					'description' => JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLUPLOADSIZEDESC'));
		}

		return $messages;
	}
}
fields/location.php000060400000001557152456173470010355 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('InstallerHelper', JPATH_ADMINISTRATOR . '/components/com_installer/helpers/installer.php');

JFormHelper::loadFieldClass('list');

/**
 * Location field.
 *
 * @since  3.5
 */
class JFormFieldLocation extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var	   string
	 * @since  3.5
	 */
	protected $type = 'Location';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.5
	 */
	public function getOptions()
	{
		$options = InstallerHelper::getClientOptions();

		return array_merge(parent::getOptions(), $options);
	}
}
fields/folder.php000060400000001554152456173470010015 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('InstallerHelper', JPATH_ADMINISTRATOR . '/components/com_installer/helpers/installer.php');

JFormHelper::loadFieldClass('list');

/**
 * Folder field.
 *
 * @since  3.5
 */
class JFormFieldFolder extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.5
	 */
	protected $type = 'Folder';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.5
	 */
	public function getOptions()
	{
		$options = InstallerHelper::getExtensionGroupes();

		return array_merge(parent::getOptions(), $options);
	}
}
fields/extensionstatus.php000060400000001604152456173470012016 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2015 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('InstallerHelper', JPATH_ADMINISTRATOR . '/components/com_installer/helpers/installer.php');

JFormHelper::loadFieldClass('list');

/**
 * Extension Status field.
 *
 * @since  3.5
 */
class JFormFieldExtensionStatus extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.5
	 */
	protected $type = 'ExtensionStatus';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.5
	 */
	public function getOptions()
	{
		$options = InstallerHelper::getStateOptions();

		return array_merge(parent::getOptions(), $options);
	}
}
fields/type.php000060400000001602152456173470007515 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2010 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('InstallerHelper', JPATH_ADMINISTRATOR . '/components/com_installer/helpers/installer.php');

JFormHelper::loadFieldClass('list');

/**
 * Form field for a list of extension types.
 *
 * @since  3.5
 */
class JFormFieldType extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var	   string
	 * @since  3.5
	 */
	protected $type = 'Type';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.5
	 */
	public function getOptions()
	{
		$options = InstallerHelper::getExtensionTypes();

		return array_merge(parent::getOptions(), $options);
	}
}
database.php000060400000017170152456173470007041 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2011 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Registry\Registry;

JLoader::register('InstallerModel', __DIR__ . '/extension.php');
JLoader::register('JoomlaInstallerScript', JPATH_ADMINISTRATOR . '/components/com_admin/script.php');

/**
 * Installer Database Model
 *
 * @since  1.6
 */
class InstallerModelDatabase extends InstallerModel
{
	protected $_context = 'com_installer.discover';

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'name', $direction = 'asc')
	{
		$app = JFactory::getApplication();
		$this->setState('message', $app->getUserState('com_installer.message'));
		$this->setState('extension_message', $app->getUserState('com_installer.extension_message'));
		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		// Prepare the utf8mb4 conversion check table
		$this->prepareUtf8mb4StatusTable();

		parent::populateState($ordering, $direction);
	}

	/**
	 * Fixes database problems.
	 *
	 * @return  void
	 */
	public function fix()
	{
		if (!$changeSet = $this->getItems())
		{
			return false;
		}

		$changeSet->fix();
		$this->fixSchemaVersion($changeSet);
		$this->fixUpdateVersion();
		$installer = new JoomlaInstallerScript;
		$installer->deleteUnexistingFiles();
		$this->fixDefaultTextFilters();

		/*
		 * Finally, if the schema updates succeeded, make sure the database is
		 * converted to utf8mb4 or, if not supported by the server, compatible to it.
		 */
		$statusArray = $changeSet->getStatus();

		if (count($statusArray['error']) == 0)
		{
			$installer->convertTablesToUtf8mb4(false);
		}
	}

	/**
	 * Gets the changeset object.
	 *
	 * @return  JSchemaChangeset
	 */
	public function getItems()
	{
		$folder = JPATH_ADMINISTRATOR . '/components/com_admin/sql/updates/';

		try
		{
			$changeSet = JSchemaChangeset::getInstance($this->getDbo(), $folder);
		}
		catch (RuntimeException $e)
		{
			JFactory::getApplication()->enqueueMessage($e->getMessage(), 'warning');

			return false;
		}

		return $changeSet;
	}

	/**
	 * Method to get a JPagination object for the data set.
	 *
	 * @return  boolean
	 *
	 * @since   3.0.1
	 */
	public function getPagination()
	{
		return true;
	}

	/**
	 * Get version from #__schemas table.
	 *
	 * @return  mixed  the return value from the query, or null if the query fails.
	 *
	 * @throws Exception
	 */
	public function getSchemaVersion()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('version_id')
			->from($db->quoteName('#__schemas'))
			->where('extension_id = 700');
		$db->setQuery($query);
		$result = $db->loadResult();

		return $result;
	}

	/**
	 * Fix schema version if wrong.
	 *
	 * @param   JSchemaChangeSet  $changeSet  Schema change set.
	 *
	 * @return   mixed  string schema version if success, false if fail.
	 */
	public function fixSchemaVersion($changeSet)
	{
		// Get correct schema version -- last file in array.
		$schema = $changeSet->getSchema();

		// Check value. If ok, don't do update.
		if ($schema == $this->getSchemaVersion())
		{
			return $schema;
		}

		// Delete old row.
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__schemas'))
			->where($db->quoteName('extension_id') . ' = 700');
		$db->setQuery($query);
		$db->execute();

		// Add new row.
		$query->clear()
			->insert($db->quoteName('#__schemas'))
			->columns($db->quoteName('extension_id') . ',' . $db->quoteName('version_id'))
			->values('700, ' . $db->quote($schema));
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (JDatabaseExceptionExecuting $e)
		{
			return false;
		}

		return $schema;
	}

	/**
	 * Get current version from #__extensions table.
	 *
	 * @return  mixed   version if successful, false if fail.
	 */
	public function getUpdateVersion()
	{
		$table = JTable::getInstance('Extension');
		$table->load('700');
		$cache = new Registry($table->manifest_cache);

		return $cache->get('version');
	}

	/**
	 * Fix Joomla version in #__extensions table if wrong (doesn't equal JVersion short version).
	 *
	 * @return   mixed  string update version if success, false if fail.
	 */
	public function fixUpdateVersion()
	{
		$table = JTable::getInstance('Extension');
		$table->load('700');
		$cache = new Registry($table->manifest_cache);
		$updateVersion = $cache->get('version');
		$cmsVersion = new JVersion;

		if ($updateVersion == $cmsVersion->getShortVersion())
		{
			return $updateVersion;
		}

		$cache->set('version', $cmsVersion->getShortVersion());
		$table->manifest_cache = $cache->toString();

		if ($table->store())
		{
			return $cmsVersion->getShortVersion();
		}

		return false;
	}

	/**
	 * For version 2.5.x only
	 * Check if com_config parameters are blank.
	 *
	 * @return  string  default text filters (if any).
	 */
	public function getDefaultTextFilters()
	{
		$table = JTable::getInstance('Extension');
		$table->load($table->find(array('name' => 'com_config')));

		return $table->params;
	}

	/**
	 * For version 2.5.x only
	 * Check if com_config parameters are blank. If so, populate with com_content text filters.
	 *
	 * @return  mixed  boolean true if params are updated, null otherwise.
	 */
	public function fixDefaultTextFilters()
	{
		$table = JTable::getInstance('Extension');
		$table->load($table->find(array('name' => 'com_config')));

		// Check for empty $config and non-empty content filters.
		if (!$table->params)
		{
			// Get filters from com_content and store if you find them.
			$contentParams = JComponentHelper::getParams('com_content');

			if ($contentParams->get('filters'))
			{
				$newParams = new Registry;
				$newParams->set('filters', $contentParams->get('filters'));
				$table->params = (string) $newParams;
				$table->store();

				return true;
			}
		}
	}

	/**
	 * Prepare the table to save the status of utf8mb4 conversion
	 * Make sure it contains 1 initialized record if there is not
	 * already exactly 1 record.
	 *
	 * @return  void
	 *
	 * @since   3.5
	 */
	private function prepareUtf8mb4StatusTable()
	{
		$db = JFactory::getDbo();

		$serverType = $db->getServerType();

		if ($serverType != 'mysql')
		{
			return;
		}

		$creaTabSql = 'CREATE TABLE IF NOT EXISTS ' . $db->quoteName('#__utf8_conversion')
			. ' (' . $db->quoteName('converted') . ' tinyint NOT NULL DEFAULT 0'
			. ') ENGINE=InnoDB';

		if ($db->hasUTF8mb4Support())
		{
			$creaTabSql = $creaTabSql
				. ' DEFAULT CHARSET=utf8mb4 DEFAULT COLLATE=utf8mb4_unicode_ci;';
		}
		else
		{
			$creaTabSql = $creaTabSql
				. ' DEFAULT CHARSET=utf8 DEFAULT COLLATE=utf8_unicode_ci;';
		}

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

		$db->setQuery('SELECT COUNT(*) FROM ' . $db->quoteName('#__utf8_conversion') . ';');

		$count = $db->loadResult();

		if ($count > 1)
		{
			// Table messed up somehow, clear it
			$db->setQuery('DELETE FROM ' . $db->quoteName('#__utf8_conversion') . ';')
				->execute();
			$db->setQuery('INSERT INTO ' . $db->quoteName('#__utf8_conversion')
				. ' (' . $db->quoteName('converted') . ') VALUES (0);'
			)->execute();
		}
		elseif ($count == 0)
		{
			// Record missing somehow, fix this
			$db->setQuery('INSERT INTO ' . $db->quoteName('#__utf8_conversion')
				. ' (' . $db->quoteName('converted') . ') VALUES (0);'
			)->execute();
		}
	}
}
manage.php000060400000021502152456173470006517 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

JLoader::register('InstallerModel', __DIR__ . '/extension.php');

/**
 * Installer Manage Model
 *
 * @since  1.5
 */
class InstallerModelManage extends InstallerModel
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'status',
				'name',
				'client_id',
				'client', 'client_translated',
				'type', 'type_translated',
				'folder', 'folder_translated',
				'package_id',
				'extension_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'name', $direction = 'asc')
	{
		$app = JFactory::getApplication();

		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.client_id', $this->getUserStateFromRequest($this->context . '.filter.client_id', 'filter_client_id', null, 'int'));
		$this->setState('filter.status', $this->getUserStateFromRequest($this->context . '.filter.status', 'filter_status', '', 'string'));
		$this->setState('filter.type', $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'string'));
		$this->setState('filter.folder', $this->getUserStateFromRequest($this->context . '.filter.folder', 'filter_folder', '', 'string'));

		$this->setState('message', $app->getUserState('com_installer.message'));
		$this->setState('extension_message', $app->getUserState('com_installer.extension_message'));
		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		parent::populateState($ordering, $direction);
	}

	/**
	 * Enable/Disable an extension.
	 *
	 * @param   array  $eid    Extension ids to un/publish
	 * @param   int    $value  Publish value
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.5
	 */
	public function publish(&$eid = array(), $value = 1)
	{
		$user = JFactory::getUser();

		if (!$user->authorise('core.edit.state', 'com_installer'))
		{
			JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));

			return false;
		}

		$result = true;

		/*
		 * Ensure eid is an array of extension ids
		 * TODO: If it isn't an array do we want to set an error and fail?
		 */
		if (!is_array($eid))
		{
			$eid = array($eid);
		}

		// Get a table object for the extension type
		$table = JTable::getInstance('Extension');
		JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_templates/tables');

		// Enable the extension in the table and store it in the database
		foreach ($eid as $i => $id)
		{
			$table->load($id);

			if ($table->type == 'template')
			{
				$style = JTable::getInstance('Style', 'TemplatesTable');

				if ($style->load(array('template' => $table->element, 'client_id' => $table->client_id, 'home' => 1)))
				{
					JError::raiseNotice(403, JText::_('COM_INSTALLER_ERROR_DISABLE_DEFAULT_TEMPLATE_NOT_PERMITTED'));
					unset($eid[$i]);
					continue;
				}
			}

			if ($table->protected == 1)
			{
				$result = false;
				JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'));
			}
			else
			{
				$table->enabled = $value;
			}
		
			$context = $this->option . '.' . $this->name;
			JPluginHelper::importPlugin('extension');
			JEventDispatcher::getInstance()->trigger('onExtensionChangeState', array($context, $eid, $value));

			if (!$table->store())
			{
				$this->setError($table->getError());
				$result = false;
			}
		}

		// Clear the cached extension data and menu cache
		$this->cleanCache('_system', 0);
		$this->cleanCache('_system', 1);
		$this->cleanCache('com_modules', 0);
		$this->cleanCache('com_modules', 1);
		$this->cleanCache('mod_menu', 0);
		$this->cleanCache('mod_menu', 1);

		return $result;
	}

	/**
	 * Refreshes the cached manifest information for an extension.
	 *
	 * @param   int  $eid  extension identifier (key in #__extensions)
	 *
	 * @return  boolean  result of refresh
	 *
	 * @since   1.6
	 */
	public function refresh($eid)
	{
		if (!is_array($eid))
		{
			$eid = array($eid => 0);
		}

		// Get an installer object for the extension type
		$installer = JInstaller::getInstance();
		$result = 0;

		// Uninstall the chosen extensions
		foreach ($eid as $id)
		{
			$result |= $installer->refreshManifestCache($id);
		}

		return $result;
	}

	/**
	 * Remove (uninstall) an extension
	 *
	 * @param   array  $eid  An array of identifiers
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.5
	 */
	public function remove($eid = array())
	{
		$user = JFactory::getUser();

		if (!$user->authorise('core.delete', 'com_installer'))
		{
			JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));

			return false;
		}

		/*
		 * Ensure eid is an array of extension ids in the form id => client_id
		 * TODO: If it isn't an array do we want to set an error and fail?
		 */
		if (!is_array($eid))
		{
			$eid = array($eid => 0);
		}

		// Get an installer object for the extension type
		$installer = JInstaller::getInstance();
		$row = JTable::getInstance('extension');

		// Uninstall the chosen extensions
		$msgs = array();
		$result = false;

		foreach ($eid as $id)
		{
			$id = trim($id);
			$row->load($id);
			$result = false;

			$langstring = 'COM_INSTALLER_TYPE_TYPE_' . strtoupper($row->type);
			$rowtype = JText::_($langstring);

			if (strpos($rowtype, $langstring) !== false)
			{
				$rowtype = $row->type;
			}

			if ($row->type)
			{
				$result = $installer->uninstall($row->type, $id);

				// Build an array of extensions that failed to uninstall
				if ($result === false)
				{
					// There was an error in uninstalling the package
					$msgs[] = JText::sprintf('COM_INSTALLER_UNINSTALL_ERROR', $rowtype);

					continue;
				}

				// Package uninstalled successfully
				$msgs[] = JText::sprintf('COM_INSTALLER_UNINSTALL_SUCCESS', $rowtype);
				$result = true;

				continue;
			}

			// There was an error in uninstalling the package
			$msgs[] = JText::sprintf('COM_INSTALLER_UNINSTALL_ERROR', $rowtype);
		}

		$msg = implode('<br />', $msgs);
		$app = JFactory::getApplication();
		$app->enqueueMessage($msg);
		$this->setState('action', 'remove');
		$this->setState('name', $installer->get('name'));
		$app->setUserState('com_installer.message', $installer->message);
		$app->setUserState('com_installer.extension_message', $installer->get('extension_message'));

		// Clear the cached extension data and menu cache
		$this->cleanCache('_system', 0);
		$this->cleanCache('_system', 1);
		$this->cleanCache('com_modules', 0);
		$this->cleanCache('com_modules', 1);
		$this->cleanCache('com_plugins', 0);
		$this->cleanCache('com_plugins', 1);
		$this->cleanCache('mod_menu', 0);
		$this->cleanCache('mod_menu', 1);

		return $result;
	}

	/**
	 * Method to get the database query
	 *
	 * @return  JDatabaseQuery  The database query
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		$query = $this->getDbo()->getQuery(true)
			->select('*')
			->select('2*protected+(1-protected)*enabled AS status')
			->from('#__extensions')
			->where('state = 0');

		// Process select filters.
		$status   = $this->getState('filter.status');
		$type     = $this->getState('filter.type');
		$clientId = $this->getState('filter.client_id');
		$folder   = $this->getState('filter.folder');

		if ($status != '')
		{
			if ($status == '2')
			{
				$query->where('protected = 1');
			}
			elseif ($status == '3')
			{
				$query->where('protected = 0');
			}
			else
			{
				$query->where('protected = 0')
					->where('enabled = ' . (int) $status);
			}
		}

		if ($type)
		{
			$query->where('type = ' . $this->_db->quote($type));
		}

		if ($clientId != '')
		{
			$query->where('client_id = ' . (int) $clientId);
		}

		if ($folder != '')
		{
			$query->where('folder = ' . $this->_db->quote($folder == '*' ? '' : $folder));
		}

		// Process search filter (extension id).
		$search = $this->getState('filter.search');

		if (!empty($search) && stripos($search, 'id:') === 0)
		{
			$query->where('extension_id = ' . (int) substr($search, 3));
		}

		// Note: The search for name, ordering and pagination are processed by the parent InstallerModel class (in extension.php).

		return $query;
	}
}
discover.php000060400000014550152456173470007112 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

JLoader::register('InstallerModel', __DIR__ . '/extension.php');

/**
 * Installer Discover Model
 *
 * @since  1.6
 */
class InstallerModelDiscover extends InstallerModel
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   3.5
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'name',
				'client_id',
				'client', 'client_translated',
				'type', 'type_translated',
				'folder', 'folder_translated',
				'extension_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   3.1
	 */
	protected function populateState($ordering = 'name', $direction = 'asc')
	{
		$app = JFactory::getApplication();

		// Load the filter state.
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.client_id', $this->getUserStateFromRequest($this->context . '.filter.client_id', 'filter_client_id', null, 'int'));
		$this->setState('filter.type', $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'string'));
		$this->setState('filter.folder', $this->getUserStateFromRequest($this->context . '.filter.folder', 'filter_folder', '', 'string'));

		$this->setState('message', $app->getUserState('com_installer.message'));
		$this->setState('extension_message', $app->getUserState('com_installer.extension_message'));

		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get the database query.
	 *
	 * @return  JDatabaseQuery  the database query
	 *
	 * @since   3.1
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select('*')
			->from($db->quoteName('#__extensions'))
			->where($db->quoteName('state') . ' = -1');

		// Process select filters.
		$type     = $this->getState('filter.type');
		$clientId = $this->getState('filter.client_id');
		$folder   = $this->getState('filter.folder');

		if ($type)
		{
			$query->where($db->quoteName('type') . ' = ' . $db->quote($type));
		}

		if ($clientId != '')
		{
			$query->where($db->quoteName('client_id') . ' = ' . (int) $clientId);
		}

		if ($folder != '' && in_array($type, array('plugin', 'library', '')))
		{
			$query->where($db->quoteName('folder') . ' = ' . $db->quote($folder == '*' ? '' : $folder));
		}

		// Process search filter.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where($db->quoteName('extension_id') . ' = ' . (int) substr($search, 3));
			}
		}

		// Note: The search for name, ordering and pagination are processed by the parent InstallerModel class (in extension.php).

		return $query;
	}

	/**
	 * Discover extensions.
	 *
	 * Finds uninstalled extensions
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function discover()
	{
		// Purge the list of discovered extensions and fetch them again.
		$this->purge();
		$results = JInstaller::getInstance()->discover();

		// Get all templates, including discovered ones
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->select($db->quoteName(array('extension_id', 'element', 'folder', 'client_id', 'type')))
			->from($db->quoteName('#__extensions'));
		$db->setQuery($query);
		$installedtmp = $db->loadObjectList();

		$extensions = array();

		foreach ($installedtmp as $install)
		{
			$key = implode(':', array($install->type, $install->element, $install->folder, $install->client_id));
			$extensions[$key] = $install;
		}

		foreach ($results as $result)
		{
			// Check if we have a match on the element
			$key = implode(':', array($result->type, $result->element, $result->folder, $result->client_id));

			if (!array_key_exists($key, $extensions))
			{
				// Put it into the table
				$result->check();
				$result->store();
			}
		}
	}

	/**
	 * Installs a discovered extension.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function discover_install()
	{
		$app   = JFactory::getApplication();
		$input = $app->input;
		$eid   = $input->get('cid', 0, 'array');

		if (is_array($eid) || $eid)
		{
			if (!is_array($eid))
			{
				$eid = array($eid);
			}

			$eid = ArrayHelper::toInteger($eid);
			$failed = false;

			foreach ($eid as $id)
			{
				$installer = new JInstaller;

				$result = $installer->discover_install($id);

				if (!$result)
				{
					$failed = true;
					$app->enqueueMessage(JText::_('COM_INSTALLER_MSG_DISCOVER_INSTALLFAILED') . ': ' . $id);
				}
			}

			// TODO - We are only receiving the message for the last JInstaller instance
			$this->setState('action', 'remove');
			$this->setState('name', $installer->get('name'));
			$app->setUserState('com_installer.message', $installer->message);
			$app->setUserState('com_installer.extension_message', $installer->get('extension_message'));

			if (!$failed)
			{
				$app->enqueueMessage(JText::_('COM_INSTALLER_MSG_DISCOVER_INSTALLSUCCESSFUL'));
			}
		}
		else
		{
			$app->enqueueMessage(JText::_('COM_INSTALLER_MSG_DISCOVER_NOEXTENSIONSELECTED'));
		}
	}

	/**
	 * Cleans out the list of discovered extensions.
	 *
	 * @return  boolean  True on success
	 *
	 * @since   1.6
	 */
	public function purge()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->delete($db->quoteName('#__extensions'))
			->where($db->quoteName('state') . ' = -1');
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (JDatabaseExceptionExecuting $e)
		{
			$this->_message = JText::_('COM_INSTALLER_MSG_DISCOVER_FAILEDTOPURGEEXTENSIONS');

			return false;
		}

		$this->_message = JText::_('COM_INSTALLER_MSG_DISCOVER_PURGEDDISCOVEREDEXTENSIONS');

		return true;
	}
}
extension.php000060400000015311152456173470007304 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Extension Manager Abstract Extension Model.
 *
 * @since  1.5
 */
class InstallerModel extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'name',
				'client_id',
				'client', 'client_translated',
				'enabled',
				'type', 'type_translated',
				'folder', 'folder_translated',
				'extension_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Returns an object list
	 *
	 * @param   string  $query       The query
	 * @param   int     $limitstart  Offset
	 * @param   int     $limit       The number of records
	 *
	 * @return  array
	 */
	protected function _getList($query, $limitstart = 0, $limit = 0)
	{
		$listOrder = $this->getState('list.ordering', 'name');
		$listDirn  = $this->getState('list.direction', 'asc');

		// Replace slashes so preg_match will work
		$search = $this->getState('filter.search');
		$search = str_replace('/', ' ', $search);
		$db     = $this->getDbo();

		// Define which fields have to be processed in a custom way because of translation.
		$customOrderFields = array('name', 'client_translated', 'type_translated', 'folder_translated');

		// Process searching, ordering and pagination for fields that need to be translated.
		if (in_array($listOrder, $customOrderFields) || (!empty($search) && stripos($search, 'id:') !== 0))
		{
			// Get results from database and translate them.
			$db->setQuery($query);
			$result = $db->loadObjectList();
			$this->translate($result);

			// Process searching.
			if (!empty($search) && stripos($search, 'id:') !== 0)
			{
				$escapedSearchString = $this->refineSearchStringToRegex($search, '/');

				// By default search only the extension name field.
				$searchFields = array('name');

				// If in update sites view search also in the update site name field.
				if ($this instanceof InstallerModelUpdatesites)
				{
					$searchFields[] = 'update_site_name';
				}

				foreach ($result as $i => $item)
				{
					// Check if search string exists in any of the fields to be searched.
					$found = 0;

					foreach ($searchFields as $key => $field)
					{
						if (!$found && preg_match('/' . $escapedSearchString . '/i', $item->{$field}))
						{
							$found = 1;
						}
					}

					// If search string was not found in any of the fields searched remove it from results array.
					if (!$found)
					{
						unset($result[$i]);
					}
				}
			}

			// Process ordering.
			// Sort array object by selected ordering and selected direction. Sort is case insensitive and using locale sorting.
			$result = ArrayHelper::sortObjects($result, $listOrder, strtolower($listDirn) == 'desc' ? -1 : 1, false, true);

			// Process pagination.
			$total = count($result);
			$this->cache[$this->getStoreId('getTotal')] = $total;

			if ($total <= $limitstart)
			{
				$limitstart = 0;
				$this->setState('list.limitstart', 0);
			}

			return array_slice($result, $limitstart, $limit ?: null);
		}

		// Process searching, ordering and pagination for regular database fields.
		$query->order($db->quoteName($listOrder) . ' ' . $db->escape($listDirn));
		$result = parent::_getList($query, $limitstart, $limit);
		$this->translate($result);

		return $result;
	}

	/**
	 * Translate a list of objects
	 *
	 * @param   array  $items  The array of objects
	 *
	 * @return  array The array of translated objects
	 */
	protected function translate(&$items)
	{
		$lang = JFactory::getLanguage();

		foreach ($items as &$item)
		{
			if (strlen($item->manifest_cache) && $data = json_decode($item->manifest_cache))
			{
				foreach ($data as $key => $value)
				{
					if ($key == 'type')
					{
						// Ignore the type field
						continue;
					}

					$item->$key = $value;
				}
			}

			$item->author_info       = @$item->authorEmail . '<br />' . @$item->authorUrl;
			$item->client            = $item->client_id ? JText::_('JADMINISTRATOR') : JText::_('JSITE');
			$item->client_translated = $item->client;
			$item->type_translated   = JText::_('COM_INSTALLER_TYPE_' . strtoupper($item->type));
			$item->folder_translated = @$item->folder ? $item->folder : JText::_('COM_INSTALLER_TYPE_NONAPPLICABLE');

			$path = $item->client_id ? JPATH_ADMINISTRATOR : JPATH_SITE;

			switch ($item->type)
			{
				case 'component':
					$extension = $item->element;
					$source = JPATH_ADMINISTRATOR . '/components/' . $extension;
						$lang->load("$extension.sys", JPATH_ADMINISTRATOR, null, false, true)
					||	$lang->load("$extension.sys", $source, null, false, true);
				break;
				case 'file':
					$extension = 'files_' . $item->element;
						$lang->load("$extension.sys", JPATH_SITE, null, false, true);
				break;
				case 'library':
					$parts = explode('/', $item->element);
					$vendor = (isset($parts[1]) ? $parts[0] : null);
					$extension = 'lib_' . ($vendor ? implode('_', $parts) : $item->element);

					if (!$lang->load("$extension.sys", $path, null, false, true))
					{
						$source = $path . '/libraries/' . ($vendor ? $vendor . '/' . $parts[1] : $item->element);
						$lang->load("$extension.sys", $source, null, false, true);
					}
				break;
				case 'module':
					$extension = $item->element;
					$source = $path . '/modules/' . $extension;
						$lang->load("$extension.sys", $path, null, false, true)
					||	$lang->load("$extension.sys", $source, null, false, true);
				break;
				case 'plugin':
					$extension = 'plg_' . $item->folder . '_' . $item->element;
					$source = JPATH_PLUGINS . '/' . $item->folder . '/' . $item->element;
						$lang->load("$extension.sys", JPATH_ADMINISTRATOR, null, false, true)
					||	$lang->load("$extension.sys", $source, null, false, true);
				break;
				case 'template':
					$extension = 'tpl_' . $item->element;
					$source = $path . '/templates/' . $item->element;
						$lang->load("$extension.sys", $path, null, false, true)
					||	$lang->load("$extension.sys", $source, null, false, true);
				break;
				case 'package':
				default:
					$extension = $item->element;
						$lang->load("$extension.sys", JPATH_SITE, null, false, true);
				break;
			}

			// Translate the extension name if possible
			$item->name = JText::_($item->name);

			settype($item->description, 'string');

			if (!in_array($item->type, array('language')))
			{
				$item->description = JText::_($item->description);
			}
		}
	}
}
forms/filter_manage.xml000060400000005035152456173470011226 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_installer/models/fields" />

	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_INSTALLER_MANAGE_FILTER_SEARCH_LABEL"
			description="COM_INSTALLER_MANAGE_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="status"
			type="extensionstatus"
			label="COM_PLUGINS_FILTER_PUBLISHED"
			description="COM_PLUGINS_FILTER_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
		</field>

		<field
			name="client_id"
			type="location"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_CLIENT_SELECT</option>
		</field>

		<field
			name="type"
			type="type"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_TYPE_SELECT</option>
		</field>

		<field
			name="folder"
			type="folder"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_FOLDER_SELECT</option>
		</field>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="status ASC">JSTATUS_ASC</option>
			<option value="status DESC">JSTATUS_DESC</option>
			<option value="name ASC">COM_INSTALLER_HEADING_NAME_ASC</option>
			<option value="name DESC">COM_INSTALLER_HEADING_NAME_DESC</option>
			<option value="client_translated ASC">COM_INSTALLER_HEADING_LOCATION_ASC</option>
			<option value="client_translated DESC">COM_INSTALLER_HEADING_LOCATION_DESC</option>
			<option value="type_translated ASC">COM_INSTALLER_HEADING_TYPE_ASC</option>
			<option value="type_translated DESC">COM_INSTALLER_HEADING_TYPE_DESC</option>
			<option value="folder_translated ASC">COM_INSTALLER_HEADING_FOLDER_ASC</option>
			<option value="folder_translated DESC">COM_INSTALLER_HEADING_FOLDER_DESC</option>
			<option value="package_id ASC">COM_INSTALLER_HEADING_PACKAGE_ID_ASC</option>
			<option value="package_id DESC">COM_INSTALLER_HEADING_PACKAGE_ID_DESC</option>
			<option value="extension_id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="extension_id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_update.xml000060400000003625152456173470011263 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_installer/models/fields"/>

	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_INSTALLER_UPDATE_FILTER_SEARCH_LABEL"
			description="COM_INSTALLER_UPDATE_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>
		<field
			name="client_id"
			type="location"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_CLIENT_SELECT</option>
		</field>
		<field
			name="type"
			type="type"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_TYPE_SELECT</option>
		</field>
		<field
			name="folder"
			type="folder"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_FOLDER_SELECT</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="u.name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="u.name ASC">COM_INSTALLER_HEADING_NAME_ASC</option>
			<option value="u.name DESC">COM_INSTALLER_HEADING_NAME_DESC</option>
			<option value="client_translated ASC">COM_INSTALLER_HEADING_LOCATION_ASC</option>
			<option value="client_translated DESC">COM_INSTALLER_HEADING_LOCATION_DESC</option>
			<option value="type_translated ASC">COM_INSTALLER_HEADING_TYPE_ASC</option>
			<option value="type_translated DESC">COM_INSTALLER_HEADING_TYPE_DESC</option>
			<option value="folder_translated ASC">COM_INSTALLER_HEADING_FOLDER_ASC</option>
			<option value="folder_translated DESC">COM_INSTALLER_HEADING_FOLDER_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_updatesites.xml000060400000005201152456173470012323 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_installer/models/fields"/>

	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_INSTALLER_UPDATESITES_FILTER_SEARCH_LABEL"
			description="COM_INSTALLER_UPDATESITES_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>
		<field
			name="enabled"
			type="list"
			label="COM_PLUGINS_FILTER_PUBLISHED"
			description="COM_PLUGINS_FILTER_PUBLISHED_DESC"
			onchange="this.form.submit();"
			>
			<option value="">JOPTION_SELECT_PUBLISHED</option>
			<option value="0">JDISABLED</option>
			<option value="1">JENABLED</option>
		</field>
		<field
			name="client_id"
			type="location"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_CLIENT_SELECT</option>
		</field>
		<field
			name="type"
			type="type"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_TYPE_SELECT</option>
		</field>
		<field
			name="folder"
			type="folder"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_FOLDER_SELECT</option>
		</field>
	</fields>
	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="enabled ASC">JSTATUS_ASC</option>
			<option value="enabled DESC">JSTATUS_DESC</option>
			<option value="update_site_name ASC">COM_INSTALLER_HEADING_UPDATESITE_NAME_ASC</option>
			<option value="update_site_name DESC">COM_INSTALLER_HEADING_UPDATESITE_NAME_DESC</option>
			<option value="name ASC">COM_INSTALLER_HEADING_NAME_ASC</option>
			<option value="name DESC">COM_INSTALLER_HEADING_NAME_DESC</option>
			<option value="client_translated ASC">COM_INSTALLER_HEADING_LOCATION_ASC</option>
			<option value="client_translated DESC">COM_INSTALLER_HEADING_LOCATION_DESC</option>
			<option value="type_translated ASC">COM_INSTALLER_HEADING_TYPE_ASC</option>
			<option value="type_translated DESC">COM_INSTALLER_HEADING_TYPE_DESC</option>
			<option value="folder_translated ASC">COM_INSTALLER_HEADING_FOLDER_ASC</option>
			<option value="folder_translated DESC">COM_INSTALLER_HEADING_FOLDER_DESC</option>
			<option value="update_site_id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="update_site_id DESC">JGRID_HEADING_ID_DESC</option>
		</field>
		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
forms/filter_discover.xml000060400000004036152456173470011614 0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
	<fieldset addfieldpath="/administrator/components/com_installer/models/fields"/>

	<fields name="filter">
		<field
			name="search"
			type="text"
			inputmode="search"
			label="COM_INSTALLER_DISCOVER_FILTER_SEARCH_LABEL"
			description="COM_INSTALLER_DISCOVER_FILTER_SEARCH_DESC"
			hint="JSEARCH_FILTER"
		/>

		<field
			name="client_id"
			type="location"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_CLIENT_SELECT</option>
		</field>

		<field
			name="type"
			type="type"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_TYPE_SELECT</option>
		</field>

		<field
			name="folder"
			type="folder"
			onchange="this.form.submit();"
			>
			<option value="">COM_INSTALLER_VALUE_FOLDER_SELECT</option>
		</field>
	</fields>

	<fields name="list">
		<field
			name="fullordering"
			type="list"
			label="JGLOBAL_SORT_BY"
			description="JGLOBAL_SORT_BY"
			onchange="this.form.submit();"
			default="name ASC"
			validate="options"
			>
			<option value="">JGLOBAL_SORT_BY</option>
			<option value="name ASC">COM_INSTALLER_HEADING_NAME_ASC</option>
			<option value="name DESC">COM_INSTALLER_HEADING_NAME_DESC</option>
			<option value="client_translated ASC">COM_INSTALLER_HEADING_LOCATION_ASC</option>
			<option value="client_translated DESC">COM_INSTALLER_HEADING_LOCATION_DESC</option>
			<option value="type_translated ASC">COM_INSTALLER_HEADING_TYPE_ASC</option>
			<option value="type_translated DESC">COM_INSTALLER_HEADING_TYPE_DESC</option>
			<option value="folder_translated ASC">COM_INSTALLER_HEADING_FOLDER_ASC</option>
			<option value="folder_translated DESC">COM_INSTALLER_HEADING_FOLDER_DESC</option>
			<option value="extension_id ASC">JGRID_HEADING_ID_ASC</option>
			<option value="extension_id DESC">JGRID_HEADING_ID_DESC</option>
		</field>

		<field
			name="limit"
			type="limitbox"
			label="JGLOBAL_LIMIT"
			description="JGLOBAL_LIMIT"
			class="input-mini"
			default="25"
			onchange="this.form.submit();"
		/>
	</fields>
</form>
install.php000060400000026246152456173470006747 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2006 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * Extension Manager Install Model
 *
 * @since  1.5
 */
class InstallerModelInstall extends JModelLegacy
{
	/**
	 * @var object JTable object
	 */
	protected $_table = null;

	/**
	 * @var object JTable object
	 */
	protected $_url = null;

	/**
	 * Model context string.
	 *
	 * @var		string
	 */
	protected $_context = 'com_installer.install';

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication('administrator');

		$this->setState('message', $app->getUserState('com_installer.message'));
		$this->setState('extension_message', $app->getUserState('com_installer.extension_message'));
		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		parent::populateState();
	}

	/**
	 * Install an extension from either folder, URL or upload.
	 *
	 * @return  boolean result of install.
	 *
	 * @since   1.5
	 */
	public function install()
	{
		$this->setState('action', 'install');

		// Set FTP credentials, if given.
		JClientHelper::setCredentialsFromRequest('ftp');
		$app = JFactory::getApplication();

		// Load installer plugins for assistance if required:
		JPluginHelper::importPlugin('installer');
		$dispatcher = JEventDispatcher::getInstance();

		$package = null;

		// This event allows an input pre-treatment, a custom pre-packing or custom installation.
		// (e.g. from a JSON description).
		$results = $dispatcher->trigger('onInstallerBeforeInstallation', array($this, &$package));

		if (in_array(true, $results, true))
		{
			return true;
		}

		if (in_array(false, $results, true))
		{
			return false;
		}

		$installType = $app->input->getWord('installtype');

		if ($package === null)
		{
			switch ($installType)
			{
				case 'folder':
					// Remember the 'Install from Directory' path.
					$app->getUserStateFromRequest($this->_context . '.install_directory', 'install_directory');
					$package = $this->_getPackageFromFolder();
					break;

				case 'upload':
					$package = $this->_getPackageFromUpload();
					break;

				case 'url':
					$package = $this->_getPackageFromUrl();
					break;

				default:
					$app->setUserState('com_installer.message', JText::_('COM_INSTALLER_NO_INSTALL_TYPE_FOUND'));

					return false;
					break;
			}
		}

		// This event allows a custom installation of the package or a customization of the package:
		$results = $dispatcher->trigger('onInstallerBeforeInstaller', array($this, &$package));

		if (in_array(true, $results, true))
		{
			return true;
		}

		if (in_array(false, $results, true))
		{
			if (in_array($installType, array('upload', 'url')))
			{
				JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);
			}

			return false;
		}

		// Check if package was uploaded successfully.
		if (!\is_array($package))
		{
			$app->enqueueMessage(JText::_('COM_INSTALLER_UNABLE_TO_FIND_INSTALL_PACKAGE'), 'error');

			return false;
		}

		// Get an installer instance.
		$installer = JInstaller::getInstance();

		/*
		 * Check for a Joomla core package.
		 * To do this we need to set the source path to find the manifest (the same first step as JInstaller::install())
		 *
		 * This must be done before the unpacked check because JInstallerHelper::detectType() returns a boolean false since the manifest
		 * can't be found in the expected location.
		 */
		if (isset($package['dir']) && is_dir($package['dir']))
		{
			$installer->setPath('source', $package['dir']);

			if (!$installer->findManifest())
			{
				// If a manifest isn't found at the source, this may be a Joomla package; check the package directory for the Joomla manifest
				if (file_exists($package['dir'] . '/administrator/manifests/files/joomla.xml'))
				{
					// We have a Joomla package
					if (in_array($installType, array('upload', 'url')))
					{
						JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);
					}

					$app->enqueueMessage(
						JText::sprintf('COM_INSTALLER_UNABLE_TO_INSTALL_JOOMLA_PACKAGE', JRoute::_('index.php?option=com_joomlaupdate')),
						'warning'
					);

					return false;
				}
			}
		}

		// Was the package unpacked?
		if (empty($package['type']))
		{
			if (in_array($installType, array('upload', 'url')))
			{
				JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);
			}

			$app->enqueueMessage(JText::_('JLIB_INSTALLER_ABORT_DETECTMANIFEST'), 'error');

			return false;
		}

		// Install the package.
		if (!$installer->install($package['dir']))
		{
			// There was an error installing the package.
			$msg = JText::sprintf('COM_INSTALLER_INSTALL_ERROR', JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])));
			$result = false;
			$msgType = 'error';
		}
		else
		{
			// Package installed successfully.
			$msg = JText::sprintf('COM_INSTALLER_INSTALL_SUCCESS', JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type'])));
			$result = true;
			$msgType = 'message';
		}

		// This event allows a custom a post-flight:
		$dispatcher->trigger('onInstallerAfterInstaller', array($this, &$package, $installer, &$result, &$msg));

		// Set some model state values.
		$app = JFactory::getApplication();
		$app->enqueueMessage($msg, $msgType);
		$this->setState('name', $installer->get('name'));
		$this->setState('result', $result);
		$app->setUserState('com_installer.message', $installer->message);
		$app->setUserState('com_installer.extension_message', $installer->get('extension_message'));
		$app->setUserState('com_installer.redirect_url', $installer->get('redirect_url'));

		// Cleanup the install files.
		if (!is_file($package['packagefile']))
		{
			$config = JFactory::getConfig();
			$package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile'];
		}

		JInstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);

		// Clear the cached extension data and menu cache
		$this->cleanCache('_system', 0);
		$this->cleanCache('_system', 1);
		$this->cleanCache('com_modules', 0);
		$this->cleanCache('com_modules', 1);
		$this->cleanCache('com_plugins', 0);
		$this->cleanCache('com_plugins', 1);
		$this->cleanCache('mod_menu', 0);
		$this->cleanCache('mod_menu', 1);

		return $result;
	}

	/**
	 * Works out an installation package from a HTTP upload.
	 *
	 * @return package definition or false on failure.
	 */
	protected function _getPackageFromUpload()
	{
		// Get the uploaded file information.
		$input    = JFactory::getApplication()->input;

		// Do not change the filter type 'raw'. We need this to let files containing PHP code to upload. See JInputFiles::get.
		$userfile = $input->files->get('install_package', null, 'raw');

		// Make sure that file uploads are enabled in php.
		if (!(bool) ini_get('file_uploads'))
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLFILE'));

			return false;
		}

		// Make sure that zlib is loaded so that the package can be unpacked.
		if (!extension_loaded('zlib'))
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLZLIB'));

			return false;
		}

		// If there is no uploaded file, we have a problem...
		if (!is_array($userfile))
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_NO_FILE_SELECTED'));

			return false;
		}

		// Is the PHP tmp directory missing?
		if ($userfile['error'] && ($userfile['error'] == UPLOAD_ERR_NO_TMP_DIR))
		{
			JError::raiseWarning(
				'',
				JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR') . '<br />' . JText::_('COM_INSTALLER_MSG_WARNINGS_PHPUPLOADNOTSET')
			);

			return false;
		}

		// Is the max upload size too small in php.ini?
		if ($userfile['error'] && ($userfile['error'] == UPLOAD_ERR_INI_SIZE))
		{
			JError::raiseWarning(
				'',
				JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR') . '<br />' . JText::_('COM_INSTALLER_MSG_WARNINGS_SMALLUPLOADSIZE')
			);

			return false;
		}

		// Check if there was a different problem uploading the file.
		if ($userfile['error'] || $userfile['size'] < 1)
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_WARNINSTALLUPLOADERROR'));

			return false;
		}

		// Build the appropriate paths.
		$config   = JFactory::getConfig();
		$tmp_dest = $config->get('tmp_path') . '/' . $userfile['name'];
		$tmp_src  = $userfile['tmp_name'];

		// Move uploaded file.
		jimport('joomla.filesystem.file');
		JFile::upload($tmp_src, $tmp_dest, false, true);

		// Unpack the downloaded package file.
		$package = JInstallerHelper::unpack($tmp_dest, true);

		return $package;
	}

	/**
	 * Install an extension from a directory
	 *
	 * @return  array  Package details or false on failure
	 *
	 * @since   1.5
	 */
	protected function _getPackageFromFolder()
	{
		$input = JFactory::getApplication()->input;

		// Get the path to the package to install.
		$p_dir = $input->getString('install_directory');
		$p_dir = JPath::clean($p_dir);

		// Did you give us a valid directory?
		if (!is_dir($p_dir))
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_PLEASE_ENTER_A_PACKAGE_DIRECTORY'));

			return false;
		}

		// Detect the package type
		$type = JInstallerHelper::detectType($p_dir);

		// Did you give us a valid package?
		if (!$type)
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_PATH_DOES_NOT_HAVE_A_VALID_PACKAGE'));
		}

		$package['packagefile'] = null;
		$package['extractdir'] = null;
		$package['dir'] = $p_dir;
		$package['type'] = $type;

		return $package;
	}

	/**
	 * Install an extension from a URL.
	 *
	 * @return  Package details or false on failure.
	 *
	 * @since   1.5
	 */
	protected function _getPackageFromUrl()
	{
		$input = JFactory::getApplication()->input;

		// Get the URL of the package to install.
		$url = $input->getString('install_url');

		// Did you give us a URL?
		if (!$url)
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_ENTER_A_URL'));

			return false;
		}

		// We only allow http & https here
		$uri = new JUri($url);

		if (!in_array($uri->getScheme(), array('http', 'https')))
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_INVALID_URL_SCHEME'));

			return false;
		}

		// Handle updater XML file case:
		if (preg_match('/\.xml\s*$/', $url))
		{
			jimport('joomla.updater.update');
			$update = new JUpdate;
			$update->loadFromXml($url);
			$package_url = trim($update->get('downloadurl', false)->_data);

			if ($package_url)
			{
				$url = $package_url;
			}

			unset($update);
		}

		// Download the package at the URL given.
		$p_file = JInstallerHelper::downloadPackage($url);

		// Was the package downloaded?
		if (!$p_file)
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_MSG_INSTALL_INVALID_URL'));

			return false;
		}

		$config   = JFactory::getConfig();
		$tmp_dest = $config->get('tmp_path');

		// Unpack the downloaded package file.
		$package = JInstallerHelper::unpack($tmp_dest . '/' . $p_file, true);

		return $package;
	}
}
update.php000060400000040731152456173470006556 0ustar00<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_installer
 *
 * @copyright   (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

jimport('joomla.updater.update');

use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Installer\InstallerHelper;

/**
 * Installer Update Model
 *
 * @since  1.6
 */
class InstallerModelUpdate extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'name', 'u.name',
				'client_id', 'u.client_id', 'client_translated',
				'type', 'u.type', 'type_translated',
				'folder', 'u.folder', 'folder_translated',
				'extension_id', 'u.extension_id',
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'u.name', $direction = 'asc')
	{
		$this->setState('filter.search', $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'string'));
		$this->setState('filter.client_id', $this->getUserStateFromRequest($this->context . '.filter.client_id', 'filter_client_id', null, 'int'));
		$this->setState('filter.type', $this->getUserStateFromRequest($this->context . '.filter.type', 'filter_type', '', 'string'));
		$this->setState('filter.folder', $this->getUserStateFromRequest($this->context . '.filter.folder', 'filter_folder', '', 'string'));

		$app = JFactory::getApplication();
		$this->setState('message', $app->getUserState('com_installer.message'));
		$this->setState('extension_message', $app->getUserState('com_installer.extension_message'));
		$app->setUserState('com_installer.message', '');
		$app->setUserState('com_installer.extension_message', '');

		parent::populateState($ordering, $direction);
	}

	/**
	 * Method to get the database query
	 *
	 * @return  JDatabaseQuery  The database query
	 *
	 * @since   1.6
	 */
	protected function getListQuery()
	{
		$db = $this->getDbo();

		// Grab updates ignoring new installs
		$query = $db->getQuery(true)
			->select('u.*')
			->select($db->quoteName('e.manifest_cache'))
			->from($db->quoteName('#__updates', 'u'))
			->join('LEFT', $db->quoteName('#__extensions', 'e') . ' ON ' . $db->quoteName('e.extension_id') . ' = ' . $db->quoteName('u.extension_id'))
			->where($db->quoteName('u.extension_id') . ' != ' . $db->quote(0));

		// Process select filters.
		$clientId    = $this->getState('filter.client_id');
		$type        = $this->getState('filter.type');
		$folder      = $this->getState('filter.folder');
		$extensionId = $this->getState('filter.extension_id');

		if ($type)
		{
			$query->where($db->quoteName('u.type') . ' = ' . $db->quote($type));
		}

		if ($clientId != '')
		{
			$query->where($db->quoteName('u.client_id') . ' = ' . (int) $clientId);
		}

		if ($folder != '' && in_array($type, array('plugin', 'library', '')))
		{
			$query->where($db->quoteName('u.folder') . ' = ' . $db->quote($folder == '*' ? '' : $folder));
		}

		if ($extensionId)
		{
			$query->where($db->quoteName('u.extension_id') . ' = ' . $db->quote((int) $extensionId));
		}
		else
		{
			$query->where($db->quoteName('u.extension_id') . ' != ' . $db->quote(0))
				->where($db->quoteName('u.extension_id') . ' != ' . $db->quote(700));
		}

		// Process search filter.
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'eid:') !== false)
			{
				$query->where($db->quoteName('u.extension_id') . ' = ' . (int) substr($search, 4));
			}
			else
			{
				if (stripos($search, 'uid:') !== false)
				{
					$query->where($db->quoteName('u.update_site_id') . ' = ' . (int) substr($search, 4));
				}
				elseif (stripos($search, 'id:') !== false)
				{
					$query->where($db->quoteName('u.update_id') . ' = ' . (int) substr($search, 3));
				}
				else
				{
					$query->where($db->quoteName('u.name') . ' LIKE ' . $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true)) . '%'));
				}
			}
		}

		return $query;
	}

	/**
	 * Translate a list of objects
	 *
	 * @param   array  $items  The array of objects
	 *
	 * @return  array The array of translated objects
	 *
	 * @since   3.5
	 */
	protected function translate(&$items)
	{
		foreach ($items as &$item)
		{
			$item->client_translated  = $item->client_id ? JText::_('JADMINISTRATOR') : JText::_('JSITE');
			$manifest                 = json_decode($item->manifest_cache);
			$item->current_version    = isset($manifest->version) ? $manifest->version : JText::_('JLIB_UNKNOWN');
			$item->type_translated    = JText::_('COM_INSTALLER_TYPE_' . strtoupper($item->type));
			$item->folder_translated  = $item->folder ?: JText::_('COM_INSTALLER_TYPE_NONAPPLICABLE');
			$item->install_type       = $item->extension_id ? JText::_('COM_INSTALLER_MSG_UPDATE_UPDATE') : JText::_('COM_INSTALLER_NEW_INSTALL');
		}

		return $items;
	}

	/**
	 * Returns an object list
	 *
	 * @param   string  $query       The query
	 * @param   int     $limitstart  Offset
	 * @param   int     $limit       The number of records
	 *
	 * @return  array
	 *
	 * @since   3.5
	 */
	protected function _getList($query, $limitstart = 0, $limit = 0)
	{
		$db = $this->getDbo();
		$listOrder = $this->getState('list.ordering', 'u.name');
		$listDirn  = $this->getState('list.direction', 'asc');

		// Process ordering.
		if (in_array($listOrder, array('client_translated', 'folder_translated', 'type_translated')))
		{
			$db->setQuery($query);
			$result = $db->loadObjectList();
			$this->translate($result);
			$result = ArrayHelper::sortObjects($result, $listOrder, strtolower($listDirn) === 'desc' ? -1 : 1, true, true);
			$total = count($result);

			if ($total < $limitstart)
			{
				$limitstart = 0;
				$this->setState('list.start', 0);
			}

			return array_slice($result, $limitstart, $limit ?: null);
		}
		else
		{
			$query->order($db->quoteName($listOrder) . ' ' . $db->escape($listDirn));

			$result = parent::_getList($query, $limitstart, $limit);
			$this->translate($result);

			return $result;
		}
	}

	/**
	 * Get the count of disabled update sites
	 *
	 * @return  integer
	 *
	 * @since   3.4
	 */
	public function getDisabledUpdateSites()
	{
		$db = $this->getDbo();

		$query = $db->getQuery(true)
			->select('COUNT(*)')
			->from($db->quoteName('#__update_sites'))
			->where($db->quoteName('enabled') . ' = 0');

		$db->setQuery($query);

		return $db->loadResult();
	}

	/**
	 * Finds updates for an extension.
	 *
	 * @param   int  $eid               Extension identifier to look for
	 * @param   int  $cacheTimeout      Cache timeout
	 * @param   int  $minimumStability  Minimum stability for updates {@see JUpdater} (0=dev, 1=alpha, 2=beta, 3=rc, 4=stable)
	 *
	 * @return  boolean Result
	 *
	 * @since   1.6
	 */
	public function findUpdates($eid = 0, $cacheTimeout = 0, $minimumStability = JUpdater::STABILITY_STABLE)
	{
		JUpdater::getInstance()->findUpdates($eid, $cacheTimeout, $minimumStability);

		return true;
	}

	/**
	 * Removes all of the updates from the table.
	 *
	 * @return  boolean result of operation
	 *
	 * @since   1.6
	 */
	public function purge()
	{
		$db = $this->getDbo();

		// Note: TRUNCATE is a DDL operation
		// This may or may not mean depending on your database
		$db->setQuery('TRUNCATE TABLE #__updates');

		try
		{
			$db->execute();
		}
		catch (JDatabaseExceptionExecuting $e)
		{
			$this->_message = JText::_('JLIB_INSTALLER_FAILED_TO_PURGE_UPDATES');

			return false;
		}

		// Reset the last update check timestamp
		$query = $db->getQuery(true)
			->update($db->quoteName('#__update_sites'))
			->set($db->quoteName('last_check_timestamp') . ' = ' . $db->quote(0));
		$db->setQuery($query);
		$db->execute();

		// Clear the administrator cache
		$this->cleanCache('_system', 1);

		$this->_message = JText::_('JLIB_INSTALLER_PURGED_UPDATES');

		return true;
	}

	/**
	 * Enables any disabled rows in #__update_sites table
	 *
	 * @return  boolean result of operation
	 *
	 * @since   1.6
	 */
	public function enableSites()
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true)
			->update($db->quoteName('#__update_sites'))
			->set($db->quoteName('enabled') . ' = 1')
			->where($db->quoteName('enabled') . ' = 0');
		$db->setQuery($query);

		try
		{
			$db->execute();
		}
		catch (JDatabaseExceptionExecuting $e)
		{
			$this->_message .= JText::_('COM_INSTALLER_FAILED_TO_ENABLE_UPDATES');

			return false;
		}

		if ($rows = $db->getAffectedRows())
		{
			$this->_message .= JText::plural('COM_INSTALLER_ENABLED_UPDATES', $rows);
		}

		return true;
	}

	/**
	 * Update function.
	 *
	 * Sets the "result" state with the result of the operation.
	 *
	 * @param   array  $uids              Array[int] List of updates to apply
	 * @param   int    $minimumStability  The minimum allowed stability for installed updates {@see JUpdater}
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function update($uids, $minimumStability = JUpdater::STABILITY_STABLE)
	{
		$result = true;

		foreach ($uids as $uid)
		{
			$update = new JUpdate;
			$instance = JTable::getInstance('update');
			$instance->load($uid);
			$update->loadFromXml($instance->detailsurl, $minimumStability);
			
			// Find and use extra_query from update_site if available
			$updateSiteInstance = JTable::getInstance('Updatesite');
			$updateSiteInstance->load($instance->update_site_id);

			if ($updateSiteInstance->extra_query)
			{
				$update->set('extra_query', $updateSiteInstance->extra_query);
			}

			$this->preparePreUpdate($update, $instance);

			// Install sets state and enqueues messages
			$res = $this->install($update);

			if ($res)
			{
				$instance->delete($uid);
			}

			$result = $res & $result;
		}

		// Clear the cached extension data and menu cache
		$this->cleanCache('_system', 0);
		$this->cleanCache('_system', 1);
		$this->cleanCache('com_modules', 0);
		$this->cleanCache('com_modules', 1);
		$this->cleanCache('com_plugins', 0);
		$this->cleanCache('com_plugins', 1);
		$this->cleanCache('mod_menu', 0);
		$this->cleanCache('mod_menu', 1);

		// Set the final state
		$this->setState('result', $result);
	}

	/**
	 * Handles the actual update installation.
	 *
	 * @param   JUpdate  $update  An update definition
	 *
	 * @return  boolean   Result of install
	 *
	 * @since   1.6
	 */
	private function install($update)
	{
		$app = JFactory::getApplication();

		if (!isset($update->get('downloadurl')->_data))
		{
			JError::raiseWarning('', JText::_('COM_INSTALLER_INVALID_EXTENSION_UPDATE'));

			return false;
		}

		$url     = trim($update->downloadurl->_data);
		$sources = $update->get('downloadSources', array());

		if ($extra_query = $update->get('extra_query'))
		{
			$url .= (strpos($url, '?') === false) ? '?' : '&amp;';
			$url .= $extra_query;
		}

		$mirror = 0;

		while (!($p_file = InstallerHelper::downloadPackage($url)) && isset($sources[$mirror]))
		{
			$name = $sources[$mirror];
			$url  = trim($name->url);

			if ($extra_query)
			{
				$url .= (strpos($url, '?') === false) ? '?' : '&amp;';
				$url .= $extra_query;
			}

			$mirror++;
		}

		// Was the package downloaded?
		if (!$p_file)
		{
			JError::raiseWarning('', JText::sprintf('COM_INSTALLER_PACKAGE_DOWNLOAD_FAILED', $url));

			return false;
		}

		$config   = JFactory::getConfig();
		$tmp_dest = $config->get('tmp_path');

		// Unpack the downloaded package file
		$package = InstallerHelper::unpack($tmp_dest . '/' . $p_file);

		if (empty($package))
		{
			$app->enqueueMessage(JText::sprintf('COM_INSTALLER_UNPACK_ERROR', $p_file), 'error');

			return false;
		}

		// Get an installer instance
		$installer = JInstaller::getInstance();
		$update->set('type', $package['type']);

		// Check the package
		$check = InstallerHelper::isChecksumValid($package['packagefile'], $update);

		// The validation was not successful. Just a warning for now.
		// TODO: In Joomla 4 this will abort the installation
		if ($check === InstallerHelper::HASH_NOT_VALIDATED)
		{
			$app->enqueueMessage(JText::_('COM_INSTALLER_INSTALL_CHECKSUM_WRONG'), 'error');
		}

		// Install the package
		if (!$installer->update($package['dir']))
		{
			// There was an error updating the package
			$app->enqueueMessage(
				JText::sprintf('COM_INSTALLER_MSG_UPDATE_ERROR',
					JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type']))
				), 'error'
			);
			$result = false;
		}
		else
		{
			// Package updated successfully
			$app->enqueueMessage(
				JText::sprintf('COM_INSTALLER_MSG_UPDATE_SUCCESS',
					JText::_('COM_INSTALLER_TYPE_TYPE_' . strtoupper($package['type']))
				)
			);
			$result = true;
		}

		// Quick change
		$this->type = $package['type'];

		// TODO: Reconfigure this code when you have more battery life left
		$this->setState('name', $installer->get('name'));
		$this->setState('result', $result);
		$app->setUserState('com_installer.message', $installer->message);
		$app->setUserState('com_installer.extension_message', $installer->get('extension_message'));

		// Cleanup the install files
		if (!is_file($package['packagefile']))
		{
			$config = JFactory::getConfig();
			$package['packagefile'] = $config->get('tmp_path') . '/' . $package['packagefile'];
		}

		InstallerHelper::cleanupInstall($package['packagefile'], $package['extractdir']);

		return $result;
	}

	/**
	 * Method to get the row form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed  A JForm object on success, false on failure
	 *
	 * @since	2.5.2
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		JForm::addFormPath(JPATH_COMPONENT . '/models/forms');
		JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');
		$form = JForm::getInstance('com_installer.update', 'update', array('load_data' => $loadData));

		// Check for an error.
		if ($form == false)
		{
			$this->setError($form->getMessage());

			return false;
		}

		// Check the session for previously entered form data.
		$data = $this->loadFormData();

		// Bind the form data if present.
		if (!empty($data))
		{
			$form->bind($data);
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since	2.5.2
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState($this->context, array());

		return $data;
	}

	/**
	 * Method to add parameters to the update
	 *
	 * @param   JUpdate       $update  An update definition
	 * @param   JTableUpdate  $table   The update instance from the database
	 *
	 * @return  void
	 *
	 * @since   3.7.0
	 */
	protected function preparePreUpdate($update, $table)
	{
		jimport('joomla.filesystem.file');

		switch ($table->type)
		{
			// Components could have a helper which adds additional data
			case 'component':
				$ename = str_replace('com_', '', $table->element);
				$fname = $ename . '.php';
				$cname = ucfirst($ename) . 'Helper';

				$path = JPATH_ADMINISTRATOR . '/components/' . $table->element . '/helpers/' . $fname;

				if (JFile::exists($path))
				{
					require_once $path;

					if (class_exists($cname) && is_callable(array($cname, 'prepareUpdate')))
					{
						call_user_func_array(array($cname, 'prepareUpdate'), array(&$update, &$table));
					}
				}

				break;

			// Modules could have a helper which adds additional data
			case 'module':
				$cname = str_replace('_', '', $table->element) . 'Helper';
				$path = ($table->client_id ? JPATH_ADMINISTRATOR : JPATH_SITE) . '/modules/' . $table->element . '/helper.php';

				if (JFile::exists($path))
				{
					require_once $path;

					if (class_exists($cname) && is_callable(array($cname, 'prepareUpdate')))
					{
						call_user_func_array(array($cname, 'prepareUpdate'), array(&$update, &$table));
					}
				}

				break;

			// If we have a plugin, we can use the plugin trigger "onInstallerBeforePackageDownload"
			// But we should make sure, that our plugin is loaded, so we don't need a second "installer" plugin
			case 'plugin':
				$cname = str_replace('plg_', '', $table->element);
				JPluginHelper::importPlugin($table->folder, $cname);
				break;
		}
	}
}