Spade
Mini Shell
| Directory:~$ /home/lmsyaran/public_html/css/ |
| [Home] [System Details] [Kill Me] |
blanksite.php000064400000007416151165335300007243 0ustar00<?php
/*----------------------------------------------------------------------------------|
www.vdm.io |----/
Lmskaran
/-------------------------------------------------------------------------------------------------------/
@version 1.0.0
@build 10th April, 2021
@created 10th April, 2021
@package Blank
@subpackage blanksite.php
@author Mojtaba Taheri <http://lmskaran.com/>
@copyright Copyright (C) 2015. All Rights Reserved
@license GNU/GPL Version 2 or later -
http://www.gnu.org/licenses/gpl-2.0.html
____ _____ _____ __ __ __ __ ___ _____ __ __ ____
_____ _ _ ____ _ _ ____
(_ _)( _ )( _ )( \/ )( ) /__\ / __)( _ )( \/ )( _ \(
_ )( \( )( ___)( \( )(_ _)
.-_)( )(_)( )(_)( ) ( )(__ /(__)\ ( (__ )(_)( ) ( )___/
)(_)( ) ( )__) ) ( )(
\____) (_____)(_____)(_/\/\_)(____)(__)(__) \___)(_____)(_/\/\_)(__)
(_____)(_)\_)(____)(_)\_) (__)
/------------------------------------------------------------------------------------------------------*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
use Joomla\Utilities\ArrayHelper;
/**
* Blank Blanksite Model
*/
class BlankModelBlanksite extends JModelItem
{
/**
* Model context string.
*
* @var string
*/
protected $_context = 'com_blank.blanksite';
/**
* Model user data.
*
* @var strings
*/
protected $user;
protected $userId;
protected $guest;
protected $groups;
protected $levels;
protected $app;
protected $input;
protected $uikitComp;
/**
* @var object item
*/
protected $item;
/**
* 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()
{
$this->app = JFactory::getApplication();
$this->input = $this->app->input;
// Get the itme main id
$id = $this->input->getInt('id', null);
$this->setState('blanksite.id', $id);
// Load the parameters.
$params = $this->app->getParams();
$this->setState('params', $params);
parent::populateState();
}
/**
* Method to get article data.
*
* @param integer $pk The id of the article.
*
* @return mixed Menu item data object on success, false on failure.
*/
public function getItem($pk = null)
{
$this->user = JFactory::getUser();
$this->userId = $this->user->get('id');
$this->guest = $this->user->get('guest');
$this->groups = $this->user->get('groups');
$this->authorisedGroups = $this->user->getAuthorisedGroups();
$this->levels = $this->user->getAuthorisedViewLevels();
$this->initSet = true;
$pk = (!empty($pk)) ? $pk : (int)
$this->getState('blanksite.id');
if ($this->_item === null)
{
$this->_item = array();
}
if (!isset($this->_item[$pk]))
{
try
{
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Get data
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a stdClass object.
$data = array();
if (empty($data))
{
// $app = JFactory::getApplication();
// If no data is found redirect to default page and show warning.
//
$app->enqueueMessage(JText::_('COM_BLANK_NOT_FOUND_OR_ACCESS_DENIED'),
'warning');
// $app->redirect(JURI::root());
return false;
}
// set data object to item.
$this->_item[$pk] = $data;
}
catch (Exception $e)
{
if ($e->getCode() == 404)
{
// Need to go thru the error handler to allow Redirect to work.
JError::raiseWarning(404, $e->getMessage());
}
else
{
$this->setError($e);
$this->_item[$pk] = false;
}
}
}
return $this->_item[$pk];
}
}
index.html000064400000000054151165335300006542 0ustar00<html><body
bgcolor="#FFFFFF"></body></html>search.php000064400000102332151165346570006540
0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_finder
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;
// Register dependent classes.
define('FINDER_PATH_INDEXER', JPATH_ADMINISTRATOR .
'/components/com_finder/helpers/indexer');
JLoader::register('FinderIndexerHelper', FINDER_PATH_INDEXER .
'/helper.php');
JLoader::register('FinderIndexerQuery', FINDER_PATH_INDEXER .
'/query.php');
JLoader::register('FinderIndexerResult', FINDER_PATH_INDEXER .
'/result.php');
JLoader::register('FinderIndexerStemmer', FINDER_PATH_INDEXER .
'/stemmer.php');
/**
* Search model class for the Finder package.
*
* @since 2.5
*/
class FinderModelSearch extends JModelList
{
/**
* Context string for the model type
*
* @var string
* @since 2.5
*/
protected $context = 'com_finder.search';
/**
* The query object is an instance of FinderIndexerQuery which contains
and
* models the entire search query including the text input; static and
* dynamic taxonomy filters; date filters; etc.
*
* @var FinderIndexerQuery
* @since 2.5
*/
protected $query;
/**
* An array of all excluded terms ids.
*
* @var array
* @since 2.5
*/
protected $excludedTerms = array();
/**
* An array of all included terms ids.
*
* @var array
* @since 2.5
*/
protected $includedTerms = array();
/**
* An array of all required terms ids.
*
* @var array
* @since 2.5
*/
protected $requiredTerms = array();
/**
* Method to get the results of the query.
*
* @return array An array of FinderIndexerResult objects.
*
* @since 2.5
* @throws Exception on database error.
*/
public function getResults()
{
// Check if the search query is valid.
if (empty($this->query->search))
{
return null;
}
// Check if we should return results.
if (empty($this->includedTerms) &&
(empty($this->query->filters) || !$this->query->empty))
{
return null;
}
// Get the store id.
$store = $this->getStoreId('getResults');
// Use the cached data if possible.
if ($this->retrieve($store))
{
return $this->retrieve($store);
}
// Get the row data.
$items = $this->getResultsData();
// Check the data.
if (empty($items))
{
return null;
}
// Create the query to get the search results.
$db = $this->getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('link_id') . ', ' .
$db->quoteName('object'))
->from($db->quoteName('#__finder_links'))
->where($db->quoteName('link_id') . ' IN (' .
implode(',', array_keys($items)) . ')');
// Load the results from the database.
$db->setQuery($query);
$rows = $db->loadObjectList('link_id');
// Set up our results container.
$results = $items;
// Convert the rows to result objects.
foreach ($rows as $rk => $row)
{
// Build the result object.
$result = unserialize($row->object);
$result->weight = $results[$rk];
$result->link_id = $rk;
// Add the result back to the stack.
$results[$rk] = $result;
}
// Switch to a non-associative array.
$results = array_values($results);
// Push the results into cache.
$this->store($store, $results);
// Return the results.
return $this->retrieve($store);
}
/**
* Method to get the total number of results.
*
* @return integer The total number of results.
*
* @since 2.5
* @throws Exception on database error.
*/
public function getTotal()
{
// Check if the search query is valid.
if (empty($this->query->search))
{
return null;
}
// Check if we should return results.
if (empty($this->includedTerms) &&
(empty($this->query->filters) || !$this->query->empty))
{
return null;
}
// Get the store id.
$store = $this->getStoreId('getTotal');
// Use the cached data if possible.
if ($this->retrieve($store))
{
return $this->retrieve($store);
}
// Get the results total.
$total = $this->getResultsTotal();
// Push the total into cache.
$this->store($store, $total);
// Return the total.
return $this->retrieve($store);
}
/**
* Method to get the query object.
*
* @return FinderIndexerQuery A query object.
*
* @since 2.5
*/
public function getQuery()
{
// Return the query object.
return $this->query;
}
/**
* Method to build a database query to load the list data.
*
* @return JDatabaseQuery A database query.
*
* @since 2.5
*/
protected function getListQuery()
{
// Get the store id.
$store = $this->getStoreId('getListQuery');
// Use the cached data if possible.
if ($this->retrieve($store, false))
{
return clone $this->retrieve($store, false);
}
// Set variables
$user = JFactory::getUser();
$groups = implode(',', $user->getAuthorisedViewLevels());
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('l.link_id')
->from($db->quoteName('#__finder_links') . ' AS
l')
->where('l.access IN (' . $groups . ')')
->where('l.state = 1')
->where('l.published = 1');
// Get the null date and the current date, minus seconds.
$nullDate = $db->quote($db->getNullDate());
$nowDate = $db->quote(substr_replace(JFactory::getDate()->toSql(),
'00', -2));
// Add the publish up and publish down filters.
$query->where('(l.publish_start_date = ' . $nullDate .
' OR l.publish_start_date <= ' . $nowDate . ')')
->where('(l.publish_end_date = ' . $nullDate . ' OR
l.publish_end_date >= ' . $nowDate . ')');
/*
* Add the taxonomy filters to the query. We have to join the taxonomy
* map table for each group so that we can use AND clauses across
* groups. Within each group there can be an array of values that will
* use OR clauses.
*/
if (!empty($this->query->filters))
{
// Convert the associative array to a numerically indexed array.
$groups = array_values($this->query->filters);
// Iterate through each taxonomy group and add the join and where.
for ($i = 0, $c = count($groups); $i < $c; $i++)
{
// We use the offset because each join needs a unique alias.
$query->join('INNER',
$db->quoteName('#__finder_taxonomy_map') . ' AS t' .
$i . ' ON t' . $i . '.link_id = l.link_id')
->where('t' . $i . '.node_id IN (' .
implode(',', $groups[$i]) . ')');
}
}
// Add the start date filter to the query.
if (!empty($this->query->date1))
{
// Escape the date.
$date1 = $db->quote($this->query->date1);
// Add the appropriate WHERE condition.
if ($this->query->when1 === 'before')
{
$query->where($db->quoteName('l.start_date') . '
<= ' . $date1);
}
elseif ($this->query->when1 === 'after')
{
$query->where($db->quoteName('l.start_date') . '
>= ' . $date1);
}
else
{
$query->where($db->quoteName('l.start_date') . ' =
' . $date1);
}
}
// Add the end date filter to the query.
if (!empty($this->query->date2))
{
// Escape the date.
$date2 = $db->quote($this->query->date2);
// Add the appropriate WHERE condition.
if ($this->query->when2 === 'before')
{
$query->where($db->quoteName('l.start_date') . '
<= ' . $date2);
}
elseif ($this->query->when2 === 'after')
{
$query->where($db->quoteName('l.start_date') . '
>= ' . $date2);
}
else
{
$query->where($db->quoteName('l.start_date') . ' =
' . $date2);
}
}
// Filter by language
if ($this->getState('filter.language'))
{
$query->where('l.language IN (' .
$db->quote(JFactory::getLanguage()->getTag()) . ', ' .
$db->quote('*') . ')');
}
// Push the data into cache.
$this->store($store, $query, false);
// Return a copy of the query object.
return clone $this->retrieve($store, false);
}
/**
* Method to get the total number of results for the search query.
*
* @return integer The results total.
*
* @since 2.5
* @throws Exception on database error.
*/
protected function getResultsTotal()
{
// Get the store id.
$store = $this->getStoreId('getResultsTotal', false);
// Use the cached data if possible.
if ($this->retrieve($store))
{
return $this->retrieve($store);
}
// Get the base query and add the ordering information.
$base = $this->getListQuery();
$base->select('0 AS ordering');
// Get the maximum number of results.
$limit = (int) $this->getState('match.limit');
/*
* If there are no optional or required search terms in the query,
* we can get the result total in one relatively simple database query.
*/
if (empty($this->includedTerms))
{
// Adjust the query to join on the appropriate mapping table.
$query = clone $base;
$query->clear('select')
->select('COUNT(DISTINCT l.link_id)');
// Get the total from the database.
$this->_db->setQuery($query);
$total = $this->_db->loadResult();
// Push the total into cache.
$this->store($store, min($total, $limit));
// Return the total.
return $this->retrieve($store);
}
/*
* If there are optional or required search terms in the query, the
* process of getting the result total is more complicated.
*/
$start = 0;
$items = array();
$sorted = array();
$maps = array();
$excluded = $this->getExcludedLinkIds();
/*
* Iterate through the included search terms and group them by mapping
* table suffix. This ensures that we never have to do more than 16
* queries to get a batch. This may seem like a lot but it is rarely
* anywhere near 16 because of the improved mapping algorithm.
*/
foreach ($this->includedTerms as $token => $ids)
{
// Get the mapping table suffix.
$suffix = StringHelper::substr(md5(StringHelper::substr($token, 0, 1)),
0, 1);
// Initialize the mapping group.
if (!array_key_exists($suffix, $maps))
{
$maps[$suffix] = array();
}
// Add the terms to the mapping group.
$maps[$suffix] = array_merge($maps[$suffix], $ids);
}
/*
* When the query contains search terms we need to find and process the
* result total iteratively using a do-while loop.
*/
do
{
// Create a container for the fetched results.
$results = array();
$more = false;
/*
* Iterate through the mapping groups and load the total from each
* mapping table.
*/
foreach ($maps as $suffix => $ids)
{
// Create a storage key for this set.
$setId = $this->getStoreId('getResultsTotal:' .
serialize(array_values($ids)) . ':' . $start . ':' .
$limit);
// Use the cached data if possible.
if ($this->retrieve($setId))
{
$temp = $this->retrieve($setId);
}
// Load the data from the database.
else
{
// Adjust the query to join on the appropriate mapping table.
$query = clone $base;
$query->join('INNER', '#__finder_links_terms' .
$suffix . ' AS m ON m.link_id = l.link_id')
->where('m.term_id IN (' . implode(',', $ids)
. ')');
// Load the results from the database.
$this->_db->setQuery($query, $start, $limit);
$temp = $this->_db->loadObjectList();
// Set the more flag to true if any of the sets equal the limit.
$more = count($temp) === $limit;
// We loaded the data unkeyed but we need it to be keyed for later.
$junk = $temp;
$temp = array();
// Convert to an associative array.
for ($i = 0, $c = count($junk); $i < $c; $i++)
{
$temp[$junk[$i]->link_id] = $junk[$i];
}
// Store this set in cache.
$this->store($setId, $temp);
}
// Merge the results.
$results = array_merge($results, $temp);
}
// Check if there are any excluded terms to deal with.
if (count($excluded))
{
// Remove any results that match excluded terms.
for ($i = 0, $c = count($results); $i < $c; $i++)
{
if (in_array($results[$i]->link_id, $excluded))
{
unset($results[$i]);
}
}
// Reset the array keys.
$results = array_values($results);
}
// Iterate through the set to extract the unique items.
for ($i = 0, $c = count($results); $i < $c; $i++)
{
if (!isset($sorted[$results[$i]->link_id]))
{
$sorted[$results[$i]->link_id] = $results[$i]->ordering;
}
}
/*
* If the query contains just optional search terms and we have
* enough items for the page, we can stop here.
*/
if (empty($this->requiredTerms))
{
// If we need more items and they're available, make another pass.
if ($more && count($sorted) < $limit)
{
// Increment the batch starting point and continue.
$start += $limit;
continue;
}
// Push the total into cache.
$this->store($store, min(count($sorted), $limit));
// Return the total.
return $this->retrieve($store);
}
/*
* The query contains required search terms so we have to iterate
* over the items and remove any items that do not match all of the
* required search terms. This is one of the most expensive steps
* because a required token could theoretically eliminate all of
* current terms which means we would have to loop through all of
* the possibilities.
*/
foreach ($this->requiredTerms as $token => $required)
{
// Create a storage key for this set.
$setId = $this->getStoreId('getResultsTotal:required:' .
serialize(array_values($required)) . ':' . $start . ':'
. $limit);
// Use the cached data if possible.
if ($this->retrieve($setId))
{
$reqTemp = $this->retrieve($setId);
}
// Check if the token was matched.
elseif (empty($required))
{
return null;
}
// Load the data from the database.
else
{
// Setup containers in case we have to make multiple passes.
$reqStart = 0;
$reqTemp = array();
do
{
// Get the map table suffix.
$suffix = StringHelper::substr(md5(StringHelper::substr($token, 0,
1)), 0, 1);
// Adjust the query to join on the appropriate mapping table.
$query = clone $base;
$query->join('INNER', '#__finder_links_terms'
. $suffix . ' AS m ON m.link_id = l.link_id')
->where('m.term_id IN (' . implode(',',
$required) . ')');
// Load the results from the database.
$this->_db->setQuery($query, $reqStart, $limit);
$temp = $this->_db->loadObjectList('link_id');
// Set the required token more flag to true if the set equal the
limit.
$reqMore = count($temp) === $limit;
// Merge the matching set for this token.
$reqTemp += $temp;
// Increment the term offset.
$reqStart += $limit;
}
while ($reqMore === true);
// Store this set in cache.
$this->store($setId, $reqTemp);
}
// Remove any items that do not match the required term.
$sorted = array_intersect_key($sorted, $reqTemp);
}
// If we need more items and they're available, make another pass.
if ($more && count($sorted) < $limit)
{
// Increment the batch starting point.
$start += $limit;
// Merge the found items.
$items += $sorted;
continue;
}
// Otherwise, end the loop.
{
// Merge the found items.
$items += $sorted;
$more = false;
}
// End do-while loop.
}
while ($more === true);
// Set the total.
$total = count($items);
$total = min($total, $limit);
// Push the total into cache.
$this->store($store, $total);
// Return the total.
return $this->retrieve($store);
}
/**
* Method to get the results for the search query.
*
* @return array An array of result data objects.
*
* @since 2.5
* @throws Exception on database error.
*/
protected function getResultsData()
{
// Get the store id.
$store = $this->getStoreId('getResultsData', false);
// Use the cached data if possible.
if ($this->retrieve($store))
{
return $this->retrieve($store);
}
// Get the result ordering and direction.
$ordering = $this->getState('list.ordering',
'l.start_date');
$direction = $this->getState('list.direction',
'DESC');
// Get the base query and add the ordering information.
$base = $this->getListQuery();
$base->select($this->_db->escape($ordering) . ' AS
ordering');
$base->order($this->_db->escape($ordering) . ' ' .
$this->_db->escape($direction));
/*
* If there are no optional or required search terms in the query, we
* can get the results in one relatively simple database query.
*/
if (empty($this->includedTerms))
{
// Get the results from the database.
$this->_db->setQuery($base, (int)
$this->getState('list.start'), (int)
$this->getState('list.limit'));
$return = $this->_db->loadObjectList('link_id');
// Get a new store id because this data is page specific.
$store = $this->getStoreId('getResultsData', true);
// Push the results into cache.
$this->store($store, $return);
// Return the results.
return $this->retrieve($store);
}
/*
* If there are optional or required search terms in the query, the
* process of getting the results is more complicated.
*/
$start = 0;
$limit = (int) $this->getState('match.limit');
$items = array();
$sorted = array();
$maps = array();
$excluded = $this->getExcludedLinkIds();
/*
* Iterate through the included search terms and group them by mapping
* table suffix. This ensures that we never have to do more than 16
* queries to get a batch. This may seem like a lot but it is rarely
* anywhere near 16 because of the improved mapping algorithm.
*/
foreach ($this->includedTerms as $token => $ids)
{
// Get the mapping table suffix.
$suffix = StringHelper::substr(md5(StringHelper::substr($token, 0, 1)),
0, 1);
// Initialize the mapping group.
if (!array_key_exists($suffix, $maps))
{
$maps[$suffix] = array();
}
// Add the terms to the mapping group.
$maps[$suffix] = array_merge($maps[$suffix], $ids);
}
/*
* When the query contains search terms we need to find and process the
* results iteratively using a do-while loop.
*/
do
{
// Create a container for the fetched results.
$results = array();
$more = false;
/*
* Iterate through the mapping groups and load the results from each
* mapping table.
*/
foreach ($maps as $suffix => $ids)
{
// Create a storage key for this set.
$setId = $this->getStoreId('getResultsData:' .
serialize(array_values($ids)) . ':' . $start . ':' .
$limit);
// Use the cached data if possible.
if ($this->retrieve($setId))
{
$temp = $this->retrieve($setId);
}
// Load the data from the database.
else
{
// Adjust the query to join on the appropriate mapping table.
$query = clone $base;
$query->join('INNER',
$this->_db->quoteName('#__finder_links_terms' . $suffix) .
' AS m ON m.link_id = l.link_id')
->where('m.term_id IN (' . implode(',', $ids)
. ')');
// Load the results from the database.
$this->_db->setQuery($query, $start, $limit);
$temp = $this->_db->loadObjectList('link_id');
// Store this set in cache.
$this->store($setId, $temp);
// The data is keyed by link_id to ease caching, we don't need it
till later.
$temp = array_values($temp);
}
// Set the more flag to true if any of the sets equal the limit.
$more = count($temp) === $limit;
// Merge the results.
$results = array_merge($results, $temp);
}
// Check if there are any excluded terms to deal with.
if (count($excluded))
{
// Remove any results that match excluded terms.
for ($i = 0, $c = count($results); $i < $c; $i++)
{
if (in_array($results[$i]->link_id, $excluded))
{
unset($results[$i]);
}
}
// Reset the array keys.
$results = array_values($results);
}
/*
* If we are ordering by relevance we have to add up the relevance
* scores that are contained in the ordering field.
*/
if ($ordering === 'm.weight')
{
// Iterate through the set to extract the unique items.
for ($i = 0, $c = count($results); $i < $c; $i++)
{
// Add the total weights for all included search terms.
if (isset($sorted[$results[$i]->link_id]))
{
$sorted[$results[$i]->link_id] += (float)
$results[$i]->ordering;
}
else
{
$sorted[$results[$i]->link_id] = (float)
$results[$i]->ordering;
}
}
}
/*
* If we are ordering by start date we have to add convert the
* dates to unix timestamps.
*/
elseif ($ordering === 'l.start_date')
{
// Iterate through the set to extract the unique items.
for ($i = 0, $c = count($results); $i < $c; $i++)
{
if (!isset($sorted[$results[$i]->link_id]))
{
$sorted[$results[$i]->link_id] =
strtotime($results[$i]->ordering);
}
}
}
/*
* If we are not ordering by relevance or date, we just have to add
* the unique items to the set.
*/
else
{
// Iterate through the set to extract the unique items.
for ($i = 0, $c = count($results); $i < $c; $i++)
{
if (!isset($sorted[$results[$i]->link_id]))
{
$sorted[$results[$i]->link_id] = $results[$i]->ordering;
}
}
}
// Sort the results.
natcasesort($items);
if ($direction === 'DESC')
{
$items = array_reverse($items, true);
}
/*
* If the query contains just optional search terms and we have
* enough items for the page, we can stop here.
*/
if (empty($this->requiredTerms))
{
// If we need more items and they're available, make another pass.
if ($more && count($sorted) <
($this->getState('list.start') +
$this->getState('list.limit')))
{
// Increment the batch starting point and continue.
$start += $limit;
continue;
}
// Push the results into cache.
$this->store($store, $sorted);
// Return the requested set.
return array_slice($this->retrieve($store), (int)
$this->getState('list.start'), (int)
$this->getState('list.limit'), true);
}
/*
* The query contains required search terms so we have to iterate
* over the items and remove any items that do not match all of the
* required search terms. This is one of the most expensive steps
* because a required token could theoretically eliminate all of
* current terms which means we would have to loop through all of
* the possibilities.
*/
foreach ($this->requiredTerms as $token => $required)
{
// Create a storage key for this set.
$setId = $this->getStoreId('getResultsData:required:' .
serialize(array_values($required)) . ':' . $start . ':'
. $limit);
// Use the cached data if possible.
if ($this->retrieve($setId))
{
$reqTemp = $this->retrieve($setId);
}
// Check if the token was matched.
elseif (empty($required))
{
return null;
}
// Load the data from the database.
else
{
// Setup containers in case we have to make multiple passes.
$reqStart = 0;
$reqTemp = array();
do
{
// Get the map table suffix.
$suffix = StringHelper::substr(md5(StringHelper::substr($token, 0,
1)), 0, 1);
// Adjust the query to join on the appropriate mapping table.
$query = clone $base;
$query->join('INNER',
$this->_db->quoteName('#__finder_links_terms' . $suffix) .
' AS m ON m.link_id = l.link_id')
->where('m.term_id IN (' . implode(',',
$required) . ')');
// Load the results from the database.
$this->_db->setQuery($query, $reqStart, $limit);
$temp = $this->_db->loadObjectList('link_id');
// Set the required token more flag to true if the set equal the
limit.
$reqMore = count($temp) === $limit;
// Merge the matching set for this token.
$reqTemp += $temp;
// Increment the term offset.
$reqStart += $limit;
}
while ($reqMore === true);
// Store this set in cache.
$this->store($setId, $reqTemp);
}
// Remove any items that do not match the required term.
$sorted = array_intersect_key($sorted, $reqTemp);
}
// If we need more items and they're available, make another pass.
if ($more && count($sorted) <
($this->getState('list.start') +
$this->getState('list.limit')))
{
// Increment the batch starting point.
$start += $limit;
// Merge the found items.
$items = array_merge($items, $sorted);
continue;
}
// Otherwise, end the loop.
else
{
// Set the found items.
$items = $sorted;
$more = false;
}
// End do-while loop.
}
while ($more === true);
// Push the results into cache.
$this->store($store, $items);
// Return the requested set.
return array_slice($this->retrieve($store), (int)
$this->getState('list.start'), (int)
$this->getState('list.limit'), true);
}
/**
* Method to get an array of link ids that match excluded terms.
*
* @return array An array of links ids.
*
* @since 2.5
* @throws Exception on database error.
*/
protected function getExcludedLinkIds()
{
// Check if the search query has excluded terms.
if (empty($this->excludedTerms))
{
return array();
}
// Get the store id.
$store = $this->getStoreId('getExcludedLinkIds', false);
// Use the cached data if possible.
if ($this->retrieve($store))
{
return $this->retrieve($store);
}
// Initialize containers.
$links = array();
$maps = array();
/*
* Iterate through the excluded search terms and group them by mapping
* table suffix. This ensures that we never have to do more than 16
* queries to get a batch. This may seem like a lot but it is rarely
* anywhere near 16 because of the improved mapping algorithm.
*/
foreach ($this->excludedTerms as $token => $id)
{
// Get the mapping table suffix.
$suffix = StringHelper::substr(md5(StringHelper::substr($token, 0, 1)),
0, 1);
// Initialize the mapping group.
if (!array_key_exists($suffix, $maps))
{
$maps[$suffix] = array();
}
// Add the terms to the mapping group.
$maps[$suffix][] = (int) $id;
}
/*
* Iterate through the mapping groups and load the excluded links ids
* from each mapping table.
*/
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
foreach ($maps as $suffix => $ids)
{
// Create the query to get the links ids.
$query->clear()
->select('link_id')
->from($db->quoteName('#__finder_links_terms' .
$suffix))
->where($db->quoteName('term_id') . ' IN (' .
implode(',', $ids) . ')')
->group($db->quoteName('link_id'));
// Load the link ids from the database.
$db->setQuery($query);
$temp = $db->loadColumn();
// Merge the link ids.
$links = array_merge($links, $temp);
}
// Sanitize the link ids.
$links = array_unique($links);
$links = ArrayHelper::toInteger($links);
// Push the link ids into cache.
$this->store($store, $links);
return $links;
}
/**
* 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]
* @param boolean $page True to store the data paged, false to store
all data. [optional]
*
* @return string A store id.
*
* @since 2.5
*/
protected function getStoreId($id = '', $page = true)
{
// Get the query object.
$query = $this->getQuery();
// Add the search query state.
$id .= ':' . $query->input;
$id .= ':' . $query->language;
$id .= ':' . $query->filter;
$id .= ':' . serialize($query->filters);
$id .= ':' . $query->date1;
$id .= ':' . $query->date2;
$id .= ':' . $query->when1;
$id .= ':' . $query->when2;
if ($page)
{
// Add the list state for page specific data.
$id .= ':' . $this->getState('list.start');
$id .= ':' . $this->getState('list.limit');
$id .= ':' . $this->getState('list.ordering');
$id .= ':' . $this->getState('list.direction');
}
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 = null, $direction = null)
{
// Get the configuration options.
$app = JFactory::getApplication();
$input = $app->input;
$params = $app->getParams();
$user = JFactory::getUser();
$this->setState('filter.language',
JLanguageMultilang::isEnabled());
// Setup the stemmer.
if ($params->get('stem', 1) &&
$params->get('stemmer', 'porter_en'))
{
FinderIndexerHelper::$stemmer =
FinderIndexerStemmer::getInstance($params->get('stemmer',
'porter_en'));
}
$request = $input->request;
$options = array();
// Get the empty query setting.
$options['empty'] =
$params->get('allow_empty_query', 0);
// Get the static taxonomy filters.
$options['filter'] = $request->getInt('f',
$params->get('f', ''));
// Get the dynamic taxonomy filters.
$options['filters'] = $request->get('t',
$params->get('t', array()), '', 'array');
// Get the query string.
$options['input'] = $request->getString('q',
$params->get('q', ''));
// Get the query language.
$options['language'] = $request->getCmd('l',
$params->get('l', ''));
// Get the start date and start date modifier filters.
$options['date1'] = $request->getString('d1',
$params->get('d1', ''));
$options['when1'] = $request->getString('w1',
$params->get('w1', ''));
// Get the end date and end date modifier filters.
$options['date2'] = $request->getString('d2',
$params->get('d2', ''));
$options['when2'] = $request->getString('w2',
$params->get('w2', ''));
// Load the query object.
$this->query = new FinderIndexerQuery($options);
// Load the query token data.
$this->excludedTerms = $this->query->getExcludedTermIds();
$this->includedTerms = $this->query->getIncludedTermIds();
$this->requiredTerms = $this->query->getRequiredTermIds();
// Load the list state.
$this->setState('list.start',
$input->get('limitstart', 0, 'uint'));
$this->setState('list.limit',
$input->get('limit', $app->get('list_limit', 20),
'uint'));
/**
* Load the sort ordering.
* Currently this is 'hard' coded via menu item parameter but
may not satisfy a users need.
* More flexibility was way more user friendly. So we allow the user to
pass a custom value
* from the pool of fields that are indexed like the 'title'
field.
* Also, we allow this parameter to be passed in either case
(lower/upper).
*/
$order = $input->getWord('filter_order',
$params->get('sort_order', 'relevance'));
$order = StringHelper::strtolower($order);
switch ($order)
{
case 'date':
$this->setState('list.ordering',
'l.start_date');
break;
case 'price':
$this->setState('list.ordering',
'l.list_price');
break;
case ($order === 'relevance' &&
!empty($this->includedTerms)) :
$this->setState('list.ordering', 'm.weight');
break;
// Custom field that is indexed and might be required for ordering
case 'title':
$this->setState('list.ordering', 'l.title');
break;
default:
$this->setState('list.ordering', 'l.link_id');
break;
}
/**
* Load the sort direction.
* Currently this is 'hard' coded via menu item parameter but
may not satisfy a users need.
* More flexibility was way more user friendly. So we allow to be
inverted.
* Also, we allow this parameter to be passed in either case
(lower/upper).
*/
$dirn = $input->getWord('filter_order_Dir',
$params->get('sort_direction', 'desc'));
$dirn = StringHelper::strtolower($dirn);
switch ($dirn)
{
case 'asc':
$this->setState('list.direction', 'ASC');
break;
default:
case 'desc':
$this->setState('list.direction', 'DESC');
break;
}
// Set the match limit.
$this->setState('match.limit', 1000);
// Load the parameters.
$this->setState('params', $params);
// Load the user state.
$this->setState('user.id', (int)
$user->get('id'));
$this->setState('user.groups',
$user->getAuthorisedViewLevels());
}
/**
* Method to retrieve data from cache.
*
* @param string $id The cache store id.
* @param boolean $persistent Flag to enable the use of external
cache. [optional]
*
* @return mixed The cached data if found, null otherwise.
*
* @since 2.5
*/
protected function retrieve($id, $persistent = true)
{
$data = null;
// Use the internal cache if possible.
if (isset($this->cache[$id]))
{
return $this->cache[$id];
}
// Use the external cache if data is persistent.
if ($persistent)
{
$data = JFactory::getCache($this->context,
'output')->get($id);
$data = $data ? unserialize($data) : null;
}
// Store the data in internal cache.
if ($data)
{
$this->cache[$id] = $data;
}
return $data;
}
/**
* Method to store data in cache.
*
* @param string $id The cache store id.
* @param mixed $data The data to cache.
* @param boolean $persistent Flag to enable the use of external
cache. [optional]
*
* @return boolean True on success, false on failure.
*
* @since 2.5
*/
protected function store($id, $data, $persistent = true)
{
// Store the data in internal cache.
$this->cache[$id] = $data;
// Store the data in external cache if data is persistent.
if ($persistent)
{
return JFactory::getCache($this->context,
'output')->store(serialize($data), $id);
}
return true;
}
}
suggestions.php000064400000011552151165346570007650 0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_finder
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @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($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)')
->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($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'));
}
}
account.php000064400000001015151165414670006720 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelAccount extends JModelLegacy
{
public function __construct() {
parent::__construct();
}
}
?>categories.php000064400000014440151165414670007417 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelCategories extends JModelLegacy
{
protected $categories = null;
protected $categories_ordering = null;
protected $category_ordering = null;
public function __construct() {
parent::__construct();
$app = JFactory::getApplication();
$this->setState('filter.language',$app->getLanguageFilter());
}
public function getCategoriesList($displaySubcategories = 0) {
if (empty($this->categories)) {
$categoriesOrdering = $this->getCategoryOrdering();
if ((int)$displaySubcategories > 0) {
$id = -1; // display subcategories - -1 means to load all items
} else {
$id = 0;// display only parent categories
}
$query = $this->getCategoriesListQuery($id, $categoriesOrdering);
$categories = $this->_getList($query);
if (!empty($categories)) {
// Parent Only
foreach ($categories as $k => $v) {
if ($v->parent_id == 0) {
$this->categories[$v->id] = $categories[$k];
}
}
// Subcategories
foreach ($categories as $k => $v) {
if (isset($this->categories[$v->parent_id])) {
$this->categories[$v->parent_id]->subcategories[] =
$categories[$k];
$this->categories[$v->parent_id]->numsubcat++;
}
}
}
/*
$this->categories = $this->_getList( $query );
if (!empty($this->categories)) {
foreach ($this->categories as $key => $value) {
$query = $this->getCategoriesListQuery( $value->id,
$categoriesOrdering );
$this->categories[$key]->subcategories = $this->_getList(
$query );
}
}*/
}
return $this->categories;
}
public function getCategoriesListQuery($id, $categoriesOrdering) {
$wheres = array();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$app = JFactory::getApplication();
$params = $app->getParams();
$display_categories = $params->get('display_categories',
'');
$hide_categories = $params->get('hide_categories',
'');
if (!empty($display_categories)) {
$display_categories = implode(',', $display_categories);
}
if (!empty($hide_categories)) {
$hide_categories = implode(',', $hide_categories);
}
if ( $display_categories != '' ) {
$wheres[] = " c.id IN (".$display_categories.")";
}
if ( $hide_categories != '' ) {
$wheres[] = " c.id NOT IN (".$hide_categories.")";
}
$wheres[] = " c.type IN (0,1)";// type: common, onlineshop,
pos
if ($id == -1) {
// No limit for parent_id - load all categories include subcategories
} else {
$wheres[] = " c.parent_id = " . (int)$id;
}
$wheres[] = " c.published = 1";
if ($this->getState('filter.language')) {
$wheres[] = ' c.language IN
('.$this->_db->Quote(JFactory::getLanguage()->getTag()).','.$this->_db->Quote('*').')';
}
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
/*$query = " SELECT c.id, c.title, c.alias, c.image, c.description,
c.image as image, c.parent_id as parentid, COUNT(c.id) AS numdoc"
. " FROM #__phocacart_categories AS c"
. " LEFT JOIN #__phocacart_products AS a ON a.catid = c.id AND
a.published = 1"
. " WHERE " . implode( " AND ", $wheres )
. " GROUP BY c.id"
. " ORDER BY c.".$categoriesOrdering;*/
// Views Plugin can load additional columns
$additionalColumns = array();
$pluginLayout = PluginHelper::importPlugin('pcv');
if ($pluginLayout) {
$pluginOptions = array();
$eventData = array();
Factory::getApplication()->triggerEvent('PCVonCategoriesBeforeLoadColumns',
array('com_phocacart.categories', &$pluginOptions,
$eventData));
if (isset($pluginOptions['columns']) &&
$pluginOptions['columns'] != '') {
if (!empty($pluginOptions['columns'])) {
foreach ($pluginOptions['columns'] as $k => $v) {
$additionalColumns[] = PhocacartText::filterValue($v,
'alphanumeric3');
}
}
}
}
$baseColumns = array('c.id', 'c.title',
'c.alias', 'c.image', 'c.description',
'c.icon_class');
$col = array_merge($baseColumns, $additionalColumns);
$col = array_unique($col);
$columns = implode(',', $col) . ', c.parent_id as
parentid, COUNT(c.id) AS numdoc, c.parent_id, 0 AS numsubcat';
$groupsFull = implode(',', $col) . ', c.parent_id';
$groupsFast = 'c.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$query = 'SELECT '.$columns
. " FROM #__phocacart_categories AS c"
//. " LEFT JOIN #__phocacart_categories AS s ON s.parent_id = c.id
AND s.published = 1"
//. " LEFT JOIN #__phocacart_product_categories AS pc ON
pc.category_id = c.id"
//. " LEFT JOIN #__phocacart_products AS a ON a.id = pc.product_id
AND a.published = 1"
//. " LEFT JOIN #__phocacart_products AS a ON a.catid = c.id AND
a.published = 1"
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " GROUP BY ".$groups
. " ORDER BY ".$categoriesOrdering;
/*
$query = "SELECT c.id, c.title, group_concat(s.title) as subtitle,
group_concat(s.id, ':', s.title, ':', s.alias) as
subalias
FROM #__phocacart_categories as c LEFT JOIN
#__phocacart_categories as s
on s.parent_id = c.id
group by c.id";*/
//echo nl2br(str_replace('#__', 'jos_',
$query->__toString()));
return $query;
}
public function getCategoryOrdering() {
if (empty($this->category_ordering)) {
$app = JFactory::getApplication();
$params = $app->getParams();
$ordering = $params->get( 'category_ordering', 1 );
$this->category_ordering =
PhocacartOrdering::getOrderingText($ordering, 1);
}
return $this->category_ordering;
}
}
?>
category.php000064400000044431151165414670007112 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelCategory extends JModelLegacy
{
protected $item = null;
protected $item_ordering = null;
protected $layout_type = null;
protected $category = null;
protected $subcategories = null;
protected $category_ordering = null;
protected $pagination = null;
protected $total = null;
protected $ordering = null;
protected $category_layout_plugin = '';
public function __construct() {
parent::__construct();
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$paramsC = $app->getParams();
$item_pagination = $paramsC->get(
'item_pagination_default', '20' );
$item_ordering = $paramsC->get( 'item_ordering', 1 );
$layout_type = $paramsC->get( 'layout_type',
'grid' );
$this->category_layout_plugin = $paramsC->get(
'category_layout_plugin', '' );
$manufacturer_alias = $paramsC->get( 'manufacturer_alias',
'manufacturer');
$manufacturer_alias = $manufacturer_alias != '' ?
trim(PhocacartText::filterValue($manufacturer_alias,
'alphanumeric')) : 'manufacturer';
$limit =
PhocacartPagination::getMaximumLimit($app->getUserStateFromRequest('com_phocacart.limit',
'limit', $item_pagination, 'int'));
$this->setState('limit', $limit);
$this->setState('limitstart',
$app->input->get('limitstart', 0, 'int'));
$this->setState('limitstart',
($this->getState('limit') != 0 ?
(floor($this->getState('limitstart') /
$this->getState('limit')) *
$this->getState('limit')) : 0));
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('filter_order',
$app->input->get('filter_order', 'ordering'));
$this->setState('filter_order_dir',
$app->input->get('filter_order_Dir', 'ASC'));
$this->setState('itemordering',
$app->getUserStateFromRequest('com_phocacart.itemordering',
'itemordering', $item_ordering, 'int'));
$this->setState('layouttype',
$app->getUserStateFromRequest('com_phocacart.layouttype',
'layouttype', $layout_type, 'string'));
}
public function getLayoutType() {
$layoutType = $this->getState('layouttype');
$layoutType = PhocacartRenderFront::getLayoutType($layoutType);
return $layoutType;
}
public function getPagination($categoryId) {
if (empty($this->pagination)) {
jimport('joomla.html.pagination');
$this->pagination = new PhocacartPagination(
$this->getTotal($categoryId),
$this->getState('limitstart'),
$this->getState('limit') );
}
return $this->pagination;
}
function getOrdering() {
if(empty($this->ordering)) {
$this->ordering =
PhocacartOrdering::renderOrderingFront($this->getState('itemordering'),
0);
}
return $this->ordering;
}
public function getTotal($categoryId) {
if (empty($this->total)) {
$query = $this->getItemListQuery($categoryId, 1);
$this->total = $this->_getListCount($query);
}
return $this->total;
}
public function getItemList($categoryId) {
if (empty($this->item)) {
$query = $this->getItemListQuery( $categoryId);
$this->item = $this->_getList( $query
,$this->getState('limitstart'),
$this->getState('limit'));
}
return $this->item;
}
public function getCategory($categoryId) {
if (empty($this->category)) {
$query = $this->getCategoriesQuery( $categoryId, FALSE );
$this->category = $this->_getList( $query, 0, 1 );
}
return $this->category;
}
public function getSubcategories($categoryId) {
if (empty($this->subcategories)) {
$query = $this->getCategoriesQuery( $categoryId, TRUE );
$this->subcategories = $this->_getList( $query );
}
return $this->subcategories;
}
protected function getItemListQuery($categoryId, $count = 0) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$params = $app->getParams();
$wheres = array();
$lefts = array();
$skip = array();
$skip['access'] =
$params->get('sql_products_skip_access', 0);
$skip['group'] =
$params->get('sql_products_skip_group', 0);
$skip['attributes'] =
$params->get('sql_products_skip_attributes', 0);
$skip['category_type'] =
$params->get('sql_products_skip_category_type', 0);
$skip['tax'] =
$params->get('sql_products_skip_tax', 0);
$p = array();
$p['hide_products_out_of_stock'] = $params->get(
'hide_products_out_of_stock', 0);
$p['switch_image_category_items'] = $params->get(
'switch_image_category_items', 0 );
$p['display_products_all_subcategories'] = $params->get(
'display_products_all_subcategories', 0 );
$leftImages = '';
$selImages = '';
if ($p['switch_image_category_items'] == 1) {
$leftImages = ' LEFT JOIN #__phocacart_product_images AS im ON a.id
= im.product_id';
$selImages = ' GROUP_CONCAT(im.image) as additional_image,';
}
$wheres = array();
$subWherePcCat = '';
if ((int)$categoryId > 0) {
// Standard - only products from one category
$subWherePcCat = ' AND pc.category_id = '.(int)$categoryId;
// Display products not only from current category but even from all
subcategories
if ($p['display_products_all_subcategories'] == 1) {
$categoryChildrenId =
PhocacartCategoryMultiple::getCategoryChildrenString((int)$categoryId,
(string)$categoryId);
if ($categoryChildrenId !== '') {
$wheres[] = " c.id IN
(".$categoryChildrenId.")";
$subWherePcCat = " AND pc.category_id IN
(".$categoryChildrenId.")";
} else {
$wheres[] = " c.id = ".(int)$categoryId;
}
} else {
$wheres[] = " c.id = ".(int)$categoryId;
}
}
$wheres[] = ' a.published = 1';
$wheres[] = ' c.published = 1';
if (!$skip['category_type']) {
$wheres[] = " c.type IN (0,1)";// type: common,
onlineshop, pos
}
if ($this->getState('filter.language')) {
$lang = JFactory::getLanguage()->getTag();
$wheres[] =
PhocacartUtilsSettings::getLangQuery('a.language', $lang);
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
$itemOrdering = $this->getItemOrdering();
// BE AWARE
// g.item_id is in this case product_id: phocacart_item_groups table is
used for more instances: user, product, category
// so item_id in case type = 3 is product_id, items_id in case type = 2
is category_id
// see types:
administrator\components\com_phocacart\libraries\phocacart\group\group.php
if (!$skip['access']) {
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " a.access IN (".$userLevels.")";
}
if (!$skip['group']) {
$wheres[] = " (ga.group_id IN (".$userGroups.") OR
ga.group_id IS NULL)";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
}
if ($p['hide_products_out_of_stock'] == 1) {
$wheres[] = " a.stock > 0";
}
// Category Layout Plugin can change ordering
// Category Layout Plugin can load additional columns
$additionalColumns = array();
if ($this->category_layout_plugin != '') {
$this->category_layout_plugin =
PhocacartText::filterValue($this->category_layout_plugin,
'alphanumeric2');
$pluginLayout = PluginHelper::importPlugin('pcl',
$this->category_layout_plugin);
if ($pluginLayout) {
$pluginOptions = array();
$eventData = array();
$eventData['pluginname'] =
$this->category_layout_plugin;
Factory::getApplication()->triggerEvent('PCLonCategoryGetOptions',
array('com_phocacart.category', &$pluginOptions,
$eventData));
if (isset($pluginOptions['ordering']) &&
$pluginOptions['ordering'] != '') {
$pluginOrdering =
PhocacartText::filterValue($pluginOptions['ordering'],
'alphanumeric5');
if ($pluginOrdering != '') {
$itemOrdering = $pluginOrdering . ',' . $itemOrdering;
}
}
if (isset($pluginOptions['columns']) &&
$pluginOptions['columns'] != '') {
if (!empty($pluginOptions['columns'])) {
foreach ($pluginOptions['columns'] as $k => $v) {
$additionalColumns[] = PhocacartText::filterValue($v,
'alphanumeric3');
}
}
}
}
}
// Views Plugin can load additional columns
$pluginLayout = PluginHelper::importPlugin('pcv');
if ($pluginLayout) {
$pluginOptions = array();
$eventData = array();
Factory::getApplication()->triggerEvent('PCVonCategoryBeforeLoadColumns',
array('com_phocacart.category', &$pluginOptions,
$eventData));
if (isset($pluginOptions['columns']) &&
$pluginOptions['columns'] != '') {
if (!empty($pluginOptions['columns'])) {
foreach ($pluginOptions['columns'] as $k => $v) {
$additionalColumns[] = PhocacartText::filterValue($v,
'alphanumeric3');
}
}
}
}
$baseColumns = array('a.id', 'a.title',
'a.image', 'a.alias', 'a.unit_amount',
'a.unit_unit', 'a.description',
'a.sku', 'a.ean', 'a.upc',
'a.type', 'a.points_received',
'a.price_original',
'a.stock', 'a.stock_calculation',
'a.min_quantity', 'a.min_multiple_quantity',
'a.stockstatus_a_id',
'a.stockstatus_n_id','a.date', 'a.sales',
'a.featured',
'a.external_id', 'a.unit_amount',
'a.unit_unit', 'a.external_link',
'a.external_text', 'a.price',
'a.gift_types');
$col = array_merge($baseColumns, $additionalColumns);
$col = array_unique($col);
if ($count == 1) {
//$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
a.catid';
$lefts[] = ' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = a.id'.$subWherePcCat;
$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id';
$lefts[] = ' LEFT JOIN #__phocacart_manufacturers AS m ON m.id =
a.manufacturer_id';
if (!$skip['attributes']) {
// see below for explanation
// LEFT JOIN (SELECT id, product_id, MAX(required) AS required FROM
jos_phocacart_attributes GROUP BY product_id) AS at ON a.id = at.product_id
AND at.id > 0
$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0 AND at.required = 1';
}
if (!$skip['group']) {
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id =
ga.item_id AND ga.type = 3';// type 3 is product
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id =
gc.item_id AND gc.type = 2';// type 2 is category
}
//$query = ' SELECT COUNT(DISTINCT a.id) AS count'; // 2.85ms
0.12mb
$q = ' SELECT a.id' // 2.42ms 0.12mb
. ' FROM #__phocacart_products AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres )
. ' GROUP BY a.id';
} else {
//$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
a.catid';
$lefts[] = ' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = a.id'.$subWherePcCat;
$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id';
$lefts[] = ' LEFT JOIN #__phocacart_reviews AS r ON a.id =
r.product_id AND r.id > 0';
$lefts[] = ' LEFT JOIN #__phocacart_manufacturers AS m ON m.id =
a.manufacturer_id';
if (!$skip['tax']) {
$lefts[] = ' LEFT JOIN #__phocacart_taxes AS t ON t.id =
a.tax_id';
}
if (!$skip['attributes']) {
// We need to get information if at least one of the attributes of
selected product is required
// 1) Select more rows - one product is displayed e.g. in two rows
//$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0';
// 2) right solution as it select only the maximal value and if maximal
value is 1 then one of product attribute is required
// LEFT JOIN (SELECT id, product_id, MAX(required) AS required FROM
jos_phocacart_attributes GROUP BY product_id) AS at ON a.id = at.product_id
AND at.id > 0
// 3) faster version of 2)
$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0 AND at.required = 1';
}
if (!$skip['group']) {
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id =
ga.item_id AND ga.type = 3';// type 3 is product
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id =
gc.item_id AND gc.type = 2';// type 2 is category
// user is in more groups, select lowest price by best group
$lefts[] = ' LEFT JOIN #__phocacart_product_price_groups AS ppg ON
a.id = ppg.product_id AND ppg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = a.id AND group_id IN (' .
$userGroups . ') AND type = 3)';
// user is in more groups, select highest points by best group
$lefts[] = ' LEFT JOIN #__phocacart_product_point_groups AS pptg
ON a.id = pptg.product_id AND pptg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = a.id AND group_id IN (' .
$userGroups . ') AND type = 3)';
}
$columns = implode(',', $col) . ','
.' GROUP_CONCAT(DISTINCT c.id) AS catid, GROUP_CONCAT(DISTINCT
c.title) AS cattitle,'
.' GROUP_CONCAT(DISTINCT c.alias) AS catalias,';
if (!$skip['tax']) {
$columns .= ' t.id as taxid, t.tax_rate as taxrate,
t.calculation_type as taxcalculationtype, t.title as taxtitle,';
} else {
$columns .= ' NULL as taxid, NULL as taxrate, NULL as
taxcalculationtype, NULL as taxtitle,';
}
if (!$skip['attributes']) {
$columns .= 'at.required AS attribute_required,
';
}
if (!$skip['group']) {
$columns .= ' MIN(ppg.price) as group_price,
MAX(pptg.points_received) as group_points_received,';
} else {
$columns .= ' NULL as group_price, NULL as
group_points_received,';
}
$columns .= ' m.id as manufacturerid, m.title as manufacturertitle,
m.alias as manufactureralias,'
. $selImages
.' AVG(r.rating) AS rating';
$groupsFull = implode(',', $col) ;
if (!$skip['tax']) {
$groupsFull .= ', t.id, t.tax_rate,
t.calculation_type, t.title';
}
if (!$skip['attributes']) {
$groupsFull .= ', at.required';
}
$groupsFast = 'a.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$q = ' SELECT '.$columns
. ' FROM #__phocacart_products AS a'
. implode( ' ', $lefts )
. $leftImages
. ' WHERE ' . implode( ' AND ', $wheres )
. ' GROUP BY '.$groups
. ' ORDER BY '.$itemOrdering;
}
//echo nl2br(str_replace('#__', 'jos_',
$q->__toString()));
return $q;
}
protected function getCategoriesQuery($categoryId, $subcategories = FALSE)
{
$wheres = array();
$app = JFactory::getApplication();
$params = $app->getParams();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
// Get the current category or get parent categories of the current
category
if ($subcategories) {
$wheres[] = " c.parent_id = ".(int)$categoryId;
$categoryOrdering = $this->getCategoryOrdering();
} else {
$wheres[] = " c.id= ".(int)$categoryId;
}
$wheres[] = " c.published = 1";
$wheres[] = " c.type IN (0,1)";// type: common, onlineshop,
pos
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
if ($this->getState('filter.language')) {
$lang = JFactory::getLanguage()->getTag();
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
if ($subcategories) {
$columns = 'c.id, c.parent_id, c.title, c.alias, c.image,
COUNT(c.id) AS numdoc';
$groupsFull = 'c.id, c.parent_id, c.title, c.alias, c.image';
$groupsFast = 'c.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$query = " SELECT ".$columns
. " FROM #__phocacart_categories AS c"
//. " LEFT JOIN #__phocacart_product_categories AS pc ON
pc.category_id = c.id"
//. " LEFT JOIN #__phocacart_products AS a ON a.id = pc.product_id
AND a.published = 1 AND a.access IN (".$userLevels.")"
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " GROUP BY ".$groups
. " ORDER BY ".$categoryOrdering;
} else {
$query = " SELECT c.id, c.parent_id, c.title, c.alias, c.image,
c.description, c.metatitle, c.metakey, c.metadesc, c.metadata, cc.title as
parenttitle, c.parent_id as parentid, cc.alias as parentalias"
. " FROM #__phocacart_categories AS c"
. " LEFT JOIN #__phocacart_categories AS cc ON cc.id =
c.parent_id"
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " ORDER BY c.ordering";
}
//echo nl2br(str_replace('#__', 'jos_', $query));
return $query;
}
protected function getItemOrdering() {
if (empty($this->item_ordering)) {
$app = JFactory::getApplication();
$params = $app->getParams();
//$ordering = $params->get( 'item_ordering', 1 );
$ordering = $this->getState('itemordering');
$this->item_ordering =
PhocacartOrdering::getOrderingText($ordering);
}
return $this->item_ordering;
}
protected function getCategoryOrdering() {
if (empty($this->category_ordering)) {
$app = JFactory::getApplication();
$params = $app->getParams();
$ordering = $params->get( 'category_ordering', 1 );
$this->category_ordering =
PhocacartOrdering::getOrderingText($ordering, 1);
}
return $this->category_ordering;
}
public function hit($pk = 0) {
$input = JFactory::getApplication()->input;
$hitcount = $input->getInt('hitcount', 1);
if ($hitcount) {
$pk = (!empty($pk)) ? $pk : (int)
$this->getState('cateogry.id');
$table = JTable::getInstance('PhocacartCategory',
'Table');
$table->load($pk);
$table->hit($pk);
}
return true;
}
}
?>
checkout.php000064400000035373151165414670007107 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelCheckout extends JModelForm
{
//protected $data;
protected $fields;
protected $fieldsguest;
public function getFields($billing = 1, $shipping = 1, $account = 0){
if (empty($this->fields)) {
$this->fields = PhocacartFormUser::getFormXml('',
'_phs', $billing, $shipping, $account);//Fields in XML Format
}
return $this->fields;
}
public function getTable($type = 'PhocacartUser', $prefix =
'Table', $config = array()) {
return JTable::getInstance($type, $prefix, $config);
}
public function getForm($data = array(), $loadData = true) {
if (empty($this->fields['xml'])) {
$this->fields = $this->getFields();
}
$form = $this->loadForm('com_phocacart.checkout',
(string)$this->fields['xml'], array('control' =>
'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
protected function loadFormData() {
$formData = (array)
JFactory::getApplication()->getUserState('com_phocacart.checkout.data',
array());
if (empty($data)) {
$formData = $this->getItem();
}
return $formData;
}
public function getItem($pk = null) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
$table = $this->getTable('PhocacartUser',
'Table');
$tableS = $this->getTable('PhocacartUser',
'Table');
// Billing
if(isset($user->id) && (int)$user->id > 0) {
$return = $table->load(array('user_id' =>
(int)$user->id, 'type' => 0));
if ($return === false && $table->getError()) {
$this->setError($table->getError());
return false;
}
}
// Shipping
if(isset($user->id) && (int)$user->id > 0) {
$returnS = $tableS->load(array('user_id' =>
(int)$user->id, 'type' => 1));
if ($returnS === false && $tableS->getError()) {
$this->setError($tableS->getError());
return false;
}
}
// Convert to the JObject before adding other data.
$properties = $table->getProperties(1);
$item = \Joomla\Utilities\ArrayHelper::toObject($properties,
'JObject');
$propertiesS = $tableS->getProperties(1);
//$itemS = \Joomla\Utilities\ArrayHelper::toObject($propertiesS,
'JObject');
//Add shipping data to billing and do both data package
if(!empty($propertiesS) && is_object($item)) {
foreach($propertiesS as $k => $v) {
$newName = $k . '_phs';
$item->$newName = $v;
}
}
/*
if (property_exists($item, 'params'))
{
$registry = new JRegistry;
$registry->loadString($item->params);
$item->params = $registry->toArray();
}*/
return $item;
}
public function getData() {
return PhocacartUser::getUserData();
}
public function saveAddress($data, $type = 0) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
if ((int)$user->id < 1) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_USER_NOT_LOGGED_IN'),
'error');
return false;
}
// Email cannot be changed in checkout or in user account (form address),
only in user account profile
if (isset($data['email'])) {
if (isset($user->email) && $user->email != '') {
$data['email'] = $user->email;
} else {
//unset($data['email']);
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_USER_EMAIL_NOT_EXISTS'),
'error');
return false;
}
}
$data['user_id'] = (int)$user->id;
$data['type'] = (int)$type;
$row = $this->getTable('PhocacartUser', 'Table');
if(isset($user->id) && $user->id > 0) {
if (!$row->load(array('user_id' => (int)$user->id,
'type' => $type))) {
// No data yet
}
}
//$row->bind($data);
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$row->date = gmdate('Y-m-d H:i:s');
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the table to the database
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return $row->id;
}
public function saveShipping($shippingId) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
if ((int)$user->id < 1) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_USER_NOT_LOGGED_IN'),
'error');
return false;
}
$data['shipping'] = (int)$shippingId;
$data['user_id'] = (int)$user->id;
$shipping = new PhocacartShipping();
//$shipping->setType();
$isValidShipping = $shipping->checkAndGetShippingMethod($shippingId);
if (!$isValidShipping) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_SHIPPING_METHOD_NOT_AVAILABLE'),
'error');
return false;
}
$row = $this->getTable('PhocacartCart', 'Table');
if(isset($user->id) && $user->id > 0) {
if (!$row->load(array('user_id' => (int)$user->id,
'vendor_id' => 0, 'ticket_id' => 0,
'unit_id' => 0, 'section_id' => 0))) {
// No data yet
}
}
if (empty($row->cart)) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_CART_IS_EMPTY_SHIPPING_METHOD_CANNOT_BE_SET'),
'error');
return false;
}
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$row->date = gmdate('Y-m-d H:i:s');
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return $row->user_id;
}
public function savePaymentAndCouponAndReward($paymentId, $couponId,
$reward) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
if ((int)$user->id < 1) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_USER_NOT_LOGGED_IN'),
'error');
return false;
}
$data['user_id'] = (int)$user->id;
$data['payment'] = (int)$paymentId;
if ((int)$couponId === -1) {
// Coupon was not sent in form, only payment, Don't change the
coupon
} else {
$data['coupon'] = (int)$couponId;
}
if ((int)$reward === -1) {
// Reward points was not sent in form, only payment, Don't change
the reward points
} else {
$data['reward'] = (int)$reward;
}
$payment = new PhocacartPayment();
//$payment->setType();
$isValidPayment = $payment->checkAndGetPaymentMethod($paymentId);
if (!$isValidPayment) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_PAYMENT_METHOD_NOT_AVAILABLE'),
'error');
return false;
}
// Coupon has own rules in cart
// Reward points have own rules in cart
$row = $this->getTable('PhocacartCart', 'Table');
if(isset($user->id) && $user->id > 0) {
if (!$row->load(array('user_id' => (int)$user->id,
'vendor_id' => 0, 'ticket_id' => 0,
'unit_id' => 0, 'section_id' => 0))) {
// No data yet
}
}
if (empty($row->cart)) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_CART_IS_EMPTY_PAYMENT_METHOD_CANNOT_BE_SET'),
'error');
return false;
}
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$row->date = gmdate('Y-m-d H:i:s');
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the table to the database
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return $row->user_id;
}
public function saveCoupon($couponId) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
if ((int)$user->id < 1) {
// This should not happen as the user is controlled in controller
(because of different return messages for standard checkout or guest
checkout
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_USER_NOT_LOGGED_IN'),
'error');
return false;
}
$data['coupon'] = (int)$couponId;
$data['user_id'] = (int)$user->id;
// Coupon has own rules in cart
$row = $this->getTable('PhocacartCart', 'Table');
if(isset($user->id) && $user->id > 0) {
if (!$row->load(array('user_id' => (int)$user->id,
'vendor_id' => 0, 'ticket_id' => 0,
'unit_id' => 0, 'section_id' => 0))) {
// No data yet
}
}
// Possible feature request ceck for if cart is empty
/*if (empty($row->cart)) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_CART_IS_EMPTY_PAYMENT_METHOD_CANNOT_BE_SET'),
'error');
return false;
}*/
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$row->date = gmdate('Y-m-d H:i:s');
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the table to the database
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return $row->user_id;
}
public function saveRewardPoints($reward) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
if ((int)$user->id < 1) {
// This should not happen as the user is controlled in controller
(because of different return messages for standard checkout or guest
checkout
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_USER_NOT_LOGGED_IN'),
'error');
return false;
}
$data['user_id'] = (int)$user->id;
$data['reward'] = (int)$reward;
// Reward points have own rules in cart
$row = $this->getTable('PhocacartCart', 'Table');
if(isset($user->id) && $user->id > 0) {
if (!$row->load(array('user_id' => (int)$user->id,
'vendor_id' => 0, 'ticket_id' => 0,
'unit_id' => 0, 'section_id' => 0))) {
// No data yet
}
}
// Possible feature request ceck for if cart is empty
/*if (empty($row->cart)) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_CART_IS_EMPTY_PAYMENT_METHOD_CANNOT_BE_SET'),
'error');
return false;
}*/
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$row->date = gmdate('Y-m-d H:i:s');
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the table to the database
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
return $row->user_id;
}
/*
*
* GUEST CHECKOUT
*
*/
public function getFieldsGuest(){
if (empty($this->fieldsguest)) {
$this->fieldsguest = PhocacartFormUser::getFormXml('',
'_phs', 1, 1, 0, 1);//Fields in XML Format
}
return $this->fieldsguest;
}
public function getFormGuest($data = array(), $loadData = true) {
if (empty($this->fieldsguest['xml'])) {
$this->fieldsguest = $this->getFieldsGuest();
}
$form = $this->loadFormGuest('com_phocacart.checkout',
(string)$this->fieldsguest['xml'], array('control'
=> 'jform', 'load_data' => $loadData));
if (empty($form)) {
return false;
}
return $form;
}
protected function loadFormGuest($name, $source = null, $options =
array(), $clear = false, $xpath = false)
{
// Handle the optional arguments.
$options['control'] =
\Joomla\Utilities\ArrayHelper::getValue($options, 'control',
false);
// Create a signature hash.
$hash = md5($source . serialize($options));
// Check if we can use a previously loaded form.
if (isset($this->_forms[$hash]) && !$clear)
{
return $this->_forms[$hash];
}
// Get the form.
JForm::addFormPath(JPATH_COMPONENT . '/models/forms');
JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');
JForm::addFormPath(JPATH_COMPONENT . '/model/form');
JForm::addFieldPath(JPATH_COMPONENT . '/model/field');
try
{
$form = JForm::getInstance($name, $source, $options, false, $xpath);
if (isset($options['load_data']) &&
$options['load_data'])
{
// Get the data for the form.
$data = $this->loadFormDataGuest();
}
else
{
$data = array();
}
// Allow for additional modification of the form, and events to be
triggered.
// We pass the data because plugins may require it.
$this->preprocessForm($form, $data);
// Load the data into the form after the plugins have operated.
$form->bind($data);
}
catch (Exception $e)
{
$this->setError($e->getMessage());
return false;
}
// Store the form for later.
$this->_forms[$hash] = $form;
return $form;
}
protected function loadFormDataGuest() {
$formData = (array)
JFactory::getApplication()->getUserState('com_phocacart.checkout.data',
array());
if (empty($data)) {
$formData = $this->getItemGuest();
}
return $formData;
}
public function getItemGuest($pk = null) {
//$guest = new PhocacartUserGuestuser();
//$item = $guest->getAddress();
$item = PhocacartUserGuestuser::getAddress();
return $item;
}
public function saveAddressGuest($data) {
//$guest = new PhocacartUserGuestuser();
$data['user_id'] = 0;
$data['type'] = 0;
if (PhocacartUserGuestuser::storeAddress($data)) {
return true;
} else {
return false;
}
}
public function getDataGuest() {
//$guest = new PhocacartUserGuestuser();
$data = PhocacartUserGuestuser::getAddress();
if (!empty($data)) {
$dataN = PhocacartUser::convertAddressTwo($data, 0);
$dataN[0]->countrytitle = null;
$dataN[0]->regiontitle = null;
$dataN[1]->countrytitle = null;
$dataN[1]->regiontitle = null;
if (isset($dataN[0]->country) && $dataN[0]->country >
0) {
$dataN[0]->countrytitle =
PhocacartCountry::getCountryById($dataN[0]->country);
}
if (isset($dataN[0]->region) && $dataN[0]->region > 0)
{
$dataN[0]->regiontitle =
PhocacartRegion::getRegionById($dataN[0]->region);
}
if (isset($dataN[1]->country) && $dataN[1]->country > 0
) {
if (isset($dataN[0]->country) && $dataN[0]->country ==
$dataN[1]->country) {
$dataN[1]->countrytitle = $dataN[0]->countrytitle;//great to
save one sql query
} else {
$dataN[1]->countrytitle =
PhocacartCountry::getCountryById($dataN[1]->country);
}
}
if (isset($dataN[1]->region) && $dataN[1]->region > 0 )
{
if (isset($dataN[0]->region) && $dataN[0]->region ==
$dataN[1]->region) {
$dataN[1]->regiontitle = $dataN[0]->regiontitle;//great to save
one sql query
} else {
$dataN[1]->regiontitle =
PhocacartRegion::getRegionById($dataN[1]->region);
}
}
return $dataN;
}
return false;
}
public function saveShippingGuest($shippingId) {
if (PhocacartUserGuestuser::storeShipping((int)$shippingId)) {
return true;
}
return false;
}
public function savePaymentAndCouponGuest($paymentId, $couponId) {
if ($couponId === -1) {
// we ignore storing the coupon (it is not a part of payment form)
if (PhocacartUserGuestuser::storePayment((int)$paymentId)) {
return true;
}
} else {
if (PhocacartUserGuestuser::storePayment((int)$paymentId) &&
PhocacartUserGuestuser::storeCoupon((int)$couponId)) {
return true;
}
}
return false;
}
public function saveCouponGuest($couponId) {
if (PhocacartUserGuestuser::storeCoupon((int)$couponId)) {
return true;
}
return false;
}
}
?>
comparison.php000064400000001020151165414670007432 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelComparison extends JModelForm
{
public function getForm($data = array(), $loadData = true) {
return false;
}
}
?>
download.php000064400000001016151165414670007074 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelDownload extends JModelForm
{
public function getForm($data = array(), $loadData = true) {
return false;
}
}
?>
fields/index.html000064400000000054151165414670010020
0ustar00<html><body
bgcolor="#FFFFFF"></body></html>fields/phocacaptcha.php000064400000001665151165414670011163
0ustar00<?php
/**
* @package phocaguestbook
* @subpackage Models
* @copyright Copyright (C) 2012 Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('JPATH_BASE') or die;
class JFormFieldPhocacaptcha extends JFormField
{
protected $type = 'phocacaptcha';
protected function getInput() {
$document = JFactory::getDocument();
$session = JFactory::getSession();
$params = PhocacartUtils::getComponentParameters();
$string = bin2hex(openssl_random_pseudo_bytes(10));
$namespace = 'pc'.$params->get('session_suffix',
$string);
$captchaCnt = $session->get('captcha_cnt', 0, $namespace) +
1;
// Possible extension of different captcha
$id = $session->get('captcha_id', '', $namespace);
switch ($id){
default:
case 1:
$retval = PhocacartCaptchaRecaptcha::render();
//$session->set('captcha_cnt', $captchaCnt, $namespace);
break;
}
return $retval;
}
}
?>
fields/phocacartcategory.php000064400000010762151165414670012245
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
if (! class_exists('PhocacartCategory')) {
require_once(
JPATH_ADMINISTRATOR.'/components/com_phocacart/libraries/phocacart/category/category.php');
}
if (! class_exists('PhocacartCategoryMultiple')) {
require_once(
JPATH_ADMINISTRATOR.'/components/com_phocacart/libraries/phocacart/category/multiple.php');
}
$lang = JFactory::getLanguage();
$lang->load('com_phocacart');
class JFormFieldPhocacartCategory extends JFormField
{
protected $type = 'PhocacartCategory';
protected function getInput() {
$db = JFactory::getDBO();
$javascript = '';
//$required = ((string) $this->element['required'] ==
'true') ? TRUE : FALSE;
$required = $this->required;// accept dynamically added required
$multiple = ((string) $this->element['multiple'] ==
'true') ? TRUE : FALSE;
$class = ((string) $this->element['class'] !=
'') ?
'class="'.$this->element['class'].'"'
: 'class="inputbox"';
$typeMethod = $this->element['typemethod'];
$categoryType = $this->element['categorytype'];// 0 all, 1
... online shop, 2 ... pos
$attr = '';
$attr .= $class . ' ';
if ($multiple) {
$attr .= 'size="4" multiple="multiple"
';
}
if ($required) {
$attr .= 'required aria-required="true" ';
}
$attr .= $javascript . ' ';
// Multiple load more values
$activeCats = array();
$id = 0;
// Active cats can be selected in administration item view
// but this function is even called in module so ignore this part for
module administration or submit items
if ($multiple && $this->form->getName() ==
'com_phocacart.phocacartitem') {
$id = (int) $this->form->getValue('id');// Product ID
if ((int)$id > 0) {
$activeCats = PhocacartCategoryMultiple::getCategories($id, 1);
}
}
// Filter language
$whereLang = '';
if (!empty($this->element['language'])) {
if (strpos($this->element['language'],
',') !== false)
{
$language = implode(',',
$db->quote(explode(',',
$this->element['language'])));
}
else
{
$language =
$db->quote($this->element['language']);
}
$whereLang = ' AND
'.$db->quoteName('a.language') . ' IN (' .
$language . ')';
}
//build the list of categories
$query = 'SELECT a.title AS text, a.id AS value, a.parent_id as
parentid'
. ' FROM #__phocacart_categories AS a';
// don't lose information about category when it will be
unpublished - you should still be able to edit product with such category
in administration
//. ' WHERE a.published = 1';
switch($categoryType) {
case 1:
$query .= ' WHERE a.type IN (0,1)';
break;
case 2:
$query .= ' WHERE a.type IN (0,2)';
break;
case 0:
default:
break;
}
$query .= $whereLang;
$query .= ' ORDER BY a.ordering';
$db->setQuery( $query );
$data = $db->loadObjectList();
// TO DO - check for other views than category edit
$view = JFactory::getApplication()->input->get( 'view'
);
$catId = -1;
if ($view == 'phocacartcategory') {
$id = $this->form->getValue('id'); // id of current
category
if ((int)$id > 0) {
$catId = $id;
}
}
$tree = array();
$text = '';
$tree = PhocacartCategory::CategoryTreeOption($data, $tree, 0, $text,
$catId);
if ($multiple) {
if ($typeMethod == 'allnone') {
array_unshift($tree,
Joomla\CMS\HTML\HTMLHelper::_('select.option', '0',
JText::_('COM_PHOCACART_NONE'), 'value',
'text'));
array_unshift($tree,
Joomla\CMS\HTML\HTMLHelper::_('select.option', '-1',
JText::_('COM_PHOCACART_ALL'), 'value',
'text'));
}
} else {
array_unshift($tree,
Joomla\CMS\HTML\HTMLHelper::_('select.option', '',
'- '.JText::_('COM_PHOCACART_SELECT_CATEGORY').'
-', 'value', 'text'));
}
if (!empty($activeCats)) {
return Joomla\CMS\HTML\HTMLHelper::_('select.genericlist',
$tree, $this->name, $attr, 'value', 'text',
$activeCats, $this->id );
} else {
return Joomla\CMS\HTML\HTMLHelper::_('select.genericlist',
$tree, $this->name, $attr, 'value', 'text',
$this->value, $this->id );
}
}
}
?>
fields/phocacartfile.php000064400000012435151165414670011346
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
use Joomla\CMS\HTML\HTMLHelper;
class JFormFieldPhocacartFile extends JFormField
{
protected $type = 'PhocacartFile';
protected function getInput()
{
$document = JFactory::getDocument();
$document->addScript(JURI::root(true) .
'/media/com_phocacart/js/tower/tower-file-input.min.js');
JHtml::stylesheet('media/com_phocacart/js/tower/tower-file-input.min.css');
$pC = PhocacartUtils::getComponentParameters();
$s = PhocacartRenderStyle::getStyles();
$submit_item_upload_image_maxsize =
$pC->get('submit_item_upload_image_maxsize', 512000);
$submit_item_upload_image_count =
$pC->get('submit_item_upload_image_count', 1);
$app = JFactory::getApplication();
$option = $app->input->get('option');
$view = $app->input->get('view');
$admin = 0;
if (!$app->isClient('site') && $option ==
'com_phocacart' && $view ==
'phocacartsubmititem') {
$admin = 1;
}
if ($admin == 1) {
$o = array();
if (!empty($this->value)) {
foreach($this->value as $k => $v) {
if (isset($v['name'])) {
$o[] = '<div
class="'.$s['c']['control-group'].'">';
$o[] = '<div
class="'.$s['c']['control-label'].'">'.$this->form->getLabel($this->name).'</div>';
$o[] = '<div
class="'.$s['c']['controls'].'">';
$o[] = '<input type="text"
name="jform[image]['.$k.'][name]"
id="jform_image"
value="'.$v['name'].'"
class="inputbox" size="40">';
$o[] = '</div>';
$o[] = '</div>';
}
if (isset($v['size'])) {
$o[] = '<div
class="'.$s['c']['control-group'].'">';
$o[] = '<div
class="'.$s['c']['control-label'].'">'.$this->form->getLabel($this->name).'</div>';
$o[] = '<div
class="'.$s['c']['controls'].'">';
$o[] = '<input type="text"
name="jform[image]['.$k.'][size]"
id="jform_image"
value="'.$v['size'].'"
class="inputbox" size="40">';
$o[] = '</div>';
$o[] = '</div>';
}
if (isset($v['nametoken'])) {
$o[] = '<div
class="'.$s['c']['control-group'].'">';
$o[] = '<div
class="'.$s['c']['control-label'].'">'.$this->form->getLabel($this->name).'</div>';
$o[] = '<div
class="'.$s['c']['controls'].'">';
$o[] = '<input type="text"
name="jform[image]['.$k.'][nametoken]"
id="jform_image"
value="'.$v['nametoken'].'"
class="inputbox" size="40">';
$o[] = '</div>';
$o[] = '</div>';
}
if (isset($v['fullpath'])) {
$o[] = '<div
class="'.$s['c']['control-group'].'">';
$o[] = '<div
class="'.$s['c']['control-label'].'">'.$this->form->getLabel($this->name).'</div>';
$o[] = '<div
class="'.$s['c']['controls'].'">';
$o[] = '<input type="text"
name="jform[image]['.$k.'][fullpath]"
id="jform_image"
value="'.$v['fullpath'].'"
class="inputbox" size="40">';
$o[] = '</div>';
$o[] = '</div>';
}
}
}
} else {
$requInput = $this->required ? ' required
aria-required="true"' : '';
$typeMethod = $this->element['typemethod'];
$accepts = '';
if ($typeMethod == 'image'){
$accepts = 'accept="image/*"';
$accepts =
'accept="image/x-png,image/gif,image/jpeg,image/webp"';
}
$s = PhocacartRenderStyle::getStyles();
$id = PhocacartUtils::getRandomString(12);
$id = 'phFile'. $id;
$o = array();
$o[] = '<div class="tower-file">';
$o[] = '<input type="file"
id="'.$id.'"
name="'.$this->name.'[]" multiple
'.$accepts.' '. $requInput.' />';
$o[] = '<label for="'.$id.'"
class="'.$s['c']['btn.btn-primary'].'"><span
class="'.$s['i']['upload'].'"></span>
'.JText::_('COM_PHOCACART_SELECT_FILES').'</label>';
$o[] = '<button type="button"
class="tower-file-clear
'.$s['c']['btn.btn-secondary'].'
align-top"><span
class="'.$s['i']['clear'].'"></span>
'.JText::_('COM_PHOCACART_CLEAR').'</button>';
$o[] = '</div>';
$o[] = '<script type="text/javascript">';
$o[] =
'jQuery("#'.$id.'").phFileInput({';
$o[] = ' fileCount:
'.(int)$submit_item_upload_image_count.',';
$o[] = ' fileSizeLimit:
'.(int)$submit_item_upload_image_maxsize.',';
$o[] = ' iconClass:
"'.$s['i']['upload'].'",';
$o[] = ' lang: {';
$o[] = '
"COM_PHOCACART_ERROR_TOO_MANY_FILES_SELECTED":
"'.JText::_('COM_PHOCACART_ERROR_TOO_MANY_FILES_SELECTED').
'",';
$o[] = '
"COM_PHOCACART_MAXIMUM_NUMBER_FILES_SELECTED_IS":
"'.JText::_('COM_PHOCACART_MAXIMUM_NUMBER_FILES_SELECTED_IS').
'",';
$o[] = ' "COM_PHOCACART_WARNFILETOOLARGE":
"'.JText::_('COM_PHOCACART_WARNFILETOOLARGE').
'",';
$o[] = ' "COM_PHOCACART_FILE_SIZE":
"'.JText::_('COM_PHOCACART_FILE_SIZE').
'",';
$o[] = ' "COM_PHOCACART_FILE_SIZE_LIMIT":
"'.JText::_('COM_PHOCACART_FILE_SIZE_LIMIT').
'",';
$o[] = ' "COM_PHOCACART_ERROR":
"'.JText::_('COM_PHOCACART_ERROR').
'",';
$o[] = ' "COM_PHOCACART_FILES_SELECTED":
"'.JText::_('COM_PHOCACART_FILES_SELECTED').
'"';
$o[] = ' }';
$o[] = '});';
$o[] = '</script>';
}
return implode("\n", $o);
}
}
?>
fields/phocacartparameter.php000064400000001636151165414670012410
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
if (! class_exists('PhocacartParameter')) {
require_once(
JPATH_ADMINISTRATOR.'/components/com_phocacart/libraries/phocacart/parameter/parameter.php');
}
$lang = JFactory::getLanguage();
$lang->load('com_phocacart');
class JFormFieldPhocacartParameter extends JFormField
{
protected $type = 'PhocacartParameter';
protected function getInput() {
//$activeId = (int) $this->form->getValue('id');
return PhocacartParameter::getAllParametersSelectBox($this->name,
$this->id, $this->value /*$activeId*/,
'class="inputbox"','id' );
}
}
?>
fields/phocacartparametervalues.php000064400000003130151165414670013617
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
if (! class_exists('PhocacartParameter')) {
require_once(
JPATH_ADMINISTRATOR.'/components/com_phocacart/libraries/phocacart/parameter/parameter.php');
}
$lang = JFactory::getLanguage();
$lang->load('com_phocacart');
defined('_JEXEC') or die();
class JFormFieldPhocaCartParameterValues extends JFormField
{
protected $type = 'PhocaCartParameterValues';
protected function getInput() {
$id = (int) $this->form->getValue('id');
$parameterId = (int)$this->element['parameterid'];
$attr = $this->element['class'] ? '
class="'.(string)
$this->element['class'].'"' : '
class="inputbox"';
$attr .= $this->element['size'] ? '
size="'.(int)
$this->element['size'].'"' : '';
//$attr .= ((string) $this->element['required'] ==
'true') ? ' required aria-required="true"' :
'';
$attr .= $this->required ? ' required
aria-required="true"' : '';
$attr .= ((string) $this->element['multiple'] ==
'true') ? ' multiple="multiple"' :
'';
$activeParameters = array();
if ((int)$id > 0) {
$activeParameters = PhocacartParameter::getParameterValues($id,
$parameterId, 1);
}
return PhocacartParameter::getAllParameterValuesSelectBox($this->name,
$this->id, $parameterId, $activeParameters, $attr, 'a.id');
}
}
?>
fields/phocacartparametervaluessubmititems.php000064400000003173151165414670016114
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
if (! class_exists('PhocacartParameter')) {
require_once(
JPATH_ADMINISTRATOR.'/components/com_phocacart/libraries/phocacart/parameter/parameter.php');
}
$lang = JFactory::getLanguage();
$lang->load('com_phocacart');
defined('_JEXEC') or die();
class JFormFieldPhocaCartParameterValuesSubmitItems extends JFormField
{
protected $type = 'PhocaCartParameterValuesSubmitItems';
protected function getInput() {
$id = (int) $this->form->getValue('id');
$parameterId = (int)$this->element['parameterid'];
$attr = $this->element['class'] ? '
class="'.(string)
$this->element['class'].'"' : '
class="inputbox"';
$attr .= $this->element['size'] ? '
size="'.(int)
$this->element['size'].'"' : '';
//$attr .= ((string) $this->element['required'] ==
'true') ? ' required aria-required="true"' :
'';
$attr .= $this->required ? ' required
aria-required="true"' : '';
$attr .= ((string) $this->element['multiple'] ==
'true') ? ' multiple="multiple"' :
'';
$activeParameters = array();
if ((int)$id > 0) {
$activeParameters =
PhocacartParameter::getParameterValuesSubmitItems($id, $parameterId, 1);
}
return PhocacartParameter::getAllParameterValuesSelectBox($this->name,
$this->id, $parameterId, $activeParameters, $attr, 'a.id');
}
}
?>
fields/phocaeditor.php000064400000016126151165414670011044 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
class JFormFieldPhocaEditor extends JFormField
{
public $type = 'PhocaEditor';
protected $editor;
protected function getInput(){
$class = $this->element['class'] ? ' class="'
. (string) $this->element['class'] . '
mceEditor"' : '';
$disabled = ((string) $this->element['disabled'] ==
'true') ? ' disabled="disabled"' :
'';
$columns = $this->element['cols'] ? ' cols="'
. (int) $this->element['cols'] . '"' :
'';
$rows = $this->element['rows'] ? ' rows="' .
(int) $this->element['rows'] . '"' :
'';
// Initialize JavaScript field attributes.
$onchange = $this->element['onchange'] ? '
onchange="' . (string) $this->element['onchange'] .
'"' : '';
$height = ((string) $this->element['height']) ?
(string) $this->element['height'] : '250';
$width = ((string) $this->element['width']) ? (string)
$this->element['width'] : '100%';
$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'];
// Build the buttons array.
$buttons = (string) $this->element['buttons'];
if ($buttons == 'true' || $buttons == 'yes' ||
$buttons == '1')
{
$buttons = true;
}
elseif ($buttons == 'false' || $buttons == 'no' ||
$buttons == '0')
{
$buttons = false;
}
else
{
$buttons = explode(',', $buttons);
}
$hide = ((string) $this->element['hide']) ?
explode(',', (string) $this->element['hide']) :
array();
// We search for defined editor (tinymce)
$editor = $this->getEditor();
if ($editor) {
$js = '<script type="text/javascript">' .
"\n";
$js .= 'tinyMCE.init({'. "\n"
.'mode : "textareas",'. "\n"
.'theme : "advanced",'. "\n"
.'language : "en",'. "\n"
.'plugins : "emotions",'. "\n"
.'editor_selector : "mceEditor",'.
"\n"
.'theme_advanced_buttons1 : "bold, italic, underline,
separator, strikethrough, justifyleft, justifycenter, justifyright,
justifyfull, bullist, numlist, undo, redo, link, unlink, separator,
emotions",'. "\n"
.'theme_advanced_buttons2 : "",'. "\n"
.'theme_advanced_buttons3 : "",'. "\n"
.'theme_advanced_toolbar_location : "top",'.
"\n"
.'theme_advanced_toolbar_align : "left",'.
"\n";
//if ($displayPath == 1) {
$js .= 'theme_advanced_path_location : "bottom",'.
"\n";
//}
$js .= 'extended_valid_elements :
"a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
});' . "\n";
$js .= '</script>';
$js2 = "\t<script type=\"text/javascript\"
src=\"".JURI::root()."media/editors/tinymce/jscripts/tiny_mce/tiny_mce.js\"></script>\n";
$js = '<script type="text/javascript">
tinyMCE.init({
// General
//directionality: "ltr",
//language : "en",
menubar:false,
statusbar: false,
mode : "specific_textareas",
skin : "lightgray",
theme : "modern",
schema: "html5",
selector: "textarea.mce_editable",
// Cleanup/Output
inline_styles : true,
gecko_spellcheck : true,
entity_encoding : "raw",
extended_valid_elements :
"hr[id|title|alt|class|width|size|noshade]",
force_br_newlines : false, force_p_newlines : true, forced_root_block
: \'p\',
toolbar_items_size: "small",
invalid_elements : "script,applet,iframe",
// Plugins
plugins : "link image autolink lists",
// Toolbar
toolbar1: "bold italic underline strikethrough | alignleft
aligncenter alignright alignjustify | bullist numlist | undo redo | link
unlink anchor image",
removed_menuitems: "newdocument",
// URL
relative_urls : true,
remove_script_host : false,
document_base_url : "'.JURI::base().'",
// Layout
content_css :
"'.JURI::base().'templates/system/css/editor.css",
//importcss_append: true,
// Advanced Options
resize: "both",
//height : "550",
//width : "750",
});
</script>';
$js2 = "\t<script type=\"text/javascript\"
src=\"".JURI::root()."media/editors/tinymce/tinymce.min.js\"></script>\n";
$document = JFactory::getDocument();
$document->addCustomTag($js2);
$document->addCustomTag($js);
if (is_numeric( $width )) {
$width .= 'px';
}
if (is_numeric( $height )) {
$height .= 'px';
}
// Problem with required
$class = str_replace('required', '', $class);
$editor = '<textarea class="mce_editable"
name="' . $this->name . '" id="' .
$this->id . '"' . $columns . $rows . $class . $disabled .
$onchange . ' style="width:' . $width .';
height:'. $height.'">'
. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') .
'</textarea>';
} else {
$editor = '<textarea class="mce_editable"
name="' . $this->name . '" id="' .
$this->id . '"' . $columns . $rows . $class . $disabled .
$onchange . ' style="width:' . $width .';
height:'. $height.'">'
. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') .
'</textarea>';
}
return $editor;
}
/**
* Method to get a JEditor object based on the form field.
*
* @return JEditor The JEditor object.
*
* @since 1.6
*/
protected function getEditor()
{
// Only create the editor if it is not already created.
if (empty($this->editor))
{
$editor = null;
// Get the editor type attribute. Can be in the form of:
editor="desired|alternative".
$type = trim((string) $this->element['editor']);
if ($type)
{
// Get the list of editor types.
$types = explode('|', $type);
// Get the database object.
$db = JFactory::getDBO();
// Iterate over teh types looking for an existing editor.
foreach ($types as $element)
{
// Build the query.
$query = $db->getQuery(true);
$query->select('element');
$query->from('#__extensions');
$query->where('element = ' . $db->quote($element));
$query->where('folder = ' .
$db->quote('editors'));
$query->where('enabled = 1');
// Check of the editor exists.
$db->setQuery($query, 0, 1);
$editor = $db->loadResult();
// If an editor was found stop looking.
if ($editor)
{
break;
}
}
}
// Create the JEditor instance based on the given editor.
if (is_null($editor))
{
$conf = JFactory::getConfig();
$editor = $conf->get('editor');
}
//PHOCAEDIT
if ($editor != trim((string) $this->element['editor'])) {
return false;
}
// END PHOCAEDIT
$this->editor = JEditor::getInstance($editor);
}
return $this->editor;
}
public function save()
{
return $this->getEditor()->save($this->id);
}
}
fields/phocaemail.php000064400000006260151165414670010643 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
defined('JPATH_BASE') or die();
JFormHelper::loadFieldClass('email');
class JFormFieldPhocaEmail extends JFormFieldEMail
{
protected $type = 'PhocaEmail';
protected function getInput() {
if (!$this->hidden &&
($this->form->getValue('version') == 1)) {
// Initialize some field attributes.
$size = $this->element['size'] ? '
size="'.(int)
$this->element['size'].'"' : '';
$class = $this->element['class'] ? '
class="'.(string)
$this->element['class'].'"' : '';
$maxLength = $this->element['maxlength'] ? '
maxlength="'.(int)
$this->element['maxlength'].'"' : '';
$readonly = ((string) $this->element['readonly'] ==
'true') ? ' readonly="readonly"' :
'';
$disabled = ((string) $this->element['disabled'] ==
'true') ? ' disabled="disabled"' :
'';
$placeholder= htmlspecialchars($this->getTitle() .
($this->required ?
''.JText::_('COM_PHOCAGUESTBOOK_REQUIREDSIGN') :
''), ENT_COMPAT, 'UTF-8');
// Initialize JavaScript field attributes.
$onchange = $this->element['onchange'] ? '
onchange="'.(string)
$this->element['onchange'].'"' : '';
$value = htmlspecialchars($this->value, ENT_COMPAT,
'UTF-8');
$requInput = $this->required ? ' required="required"
aria-required="true"' : '';
//prepend:
$preIcon = $this->element['preicon'] ? '<i
class="' . $this->element['preicon'] . '
tip" title="' . $placeholder .
'"></i>' : '';
$postIcon = $this->element['posticon'] ? '<i
class="' . $this->element['preicon'] .
'"></i>' : '';
if ($postIcon && $this->element['posthref']) {
//$postIcon = '<a href="' . (string)
$this->element['posthref'] . '" title="' .
JText::_('COM_PHOCAGUESTBOOK_RELOAD_IMAGE') . '"
class="btn hasTooltip" >' . $postIcon .
'</a>';
$postIcon = '<span class="add-on
input-group-addon"><a href="' . (string)
$this->element['posthref'] . '" title="' .
JText::_('COM_PHOCAGUESTBOOK_RELOAD_IMAGE') . '"
class="" >' . $postIcon .
'</a></span>';
}
// Get the label text from the XML element, defaulting to the element
name.
$text = $this->element['label'] ? (string)
$this->element['label'] : (string)
$this->element['name'];
$text = $this->translateLabel ? JText::_($text) : $text;
// Add the opening label tag and main attributes attributes.
$label = '<label id="' . $this->id .
'-lbl" for="' . $this->id . '"
class="element-invisible" title="' . $placeholder .
'">' . $text . '</label>';
return '<span class="add-on
input-group-addon">' . $preIcon . $label .
'</span>'
. '<input'. $requInput. ' type="text"
name="'.$this->name.'"
id="'.$this->id.'"
placeholder="'.$placeholder.'"
value="'.$value.'"'
.$class.$size.$disabled.$readonly.$onchange.$maxLength.'/>';
} else {
return parent::getInput();
}
}
protected function getLabel() {
if (!$this->hidden &&
($this->form->getValue('version') == 1)) {
return '';
} else {
return parent::getLabel();
}
}
}
?>
fields/phocaformcountry.php000064400000010410151165414670012133
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
class JFormFieldPhocaFormCountry extends JFormField
{
protected $type = 'PhocaFormCountry';
protected function getInput() {
$app = JFactory::getApplication();
$db = JFactory::getDBO();
if ($this->id == 'jform_country') {
$regionId = 'jform_region';
} else if ($this->id == 'jform_country_phs') {
$regionId = 'jform_region_phs';
} else if ($this->id == 'jform_country_phb') {
$regionId = 'jform_region_phb';
}
$s = array();
$s[] = 'function phUpdateRegion'.$this->id.'(value)
{';
$config = JComponentHelper::getParams('com_media');
//$paramsC = PhocacartUtils::getComponentParameters() ;
if (!$app->isClient('administrator')) {
$paramsC = $app->getParams();
$load_chosen= $paramsC->get( 'load_chosen', 1 );
$s[] = ' var url =
\''.JURI::base(true).'/index.php?option=com_phocacart&task=checkout.setregion&format=json&'.
JSession::getFormToken().'=1\';';
} else {
$paramsC = PhocacartUtils::getComponentParameters();
$load_chosen= $paramsC->get( 'load_chosen', 1 );
$s[] = ' var url =
\''.JURI::base(true).'/index.php?option=com_phocacart&task=phocacartuser.setregion&format=json&'.
JSession::getFormToken().'=1\';';
}
$s[] = ' var dataPost = {};';
$s[] = ' dataPost[\'countryid\'] =
encodeURIComponent(value);';
$s[] = ' phRequestActive = jQuery.ajax({';
$s[] = ' url: url,';
$s[] = ' type:\'POST\',';
$s[] = ' data:dataPost,';
$s[] = ' dataType:\'JSON\',';
$s[] = ' success:function(data){';
$s[] = ' if ( data.status == 1 ){';
$s[] = '
jQuery(\'#'.$regionId.'\').empty().append(data.content);';
if (!$app->isClient('administrator')) {
if ($load_chosen > 0) {
$s[] = '
jQuery(\'#'.$regionId.'\').trigger("chosen:updated");';//Reload
Chosen
}
} else {
// in admin, older version of chosen is used
$s[] = '
jQuery(\'#'.$regionId.'\').trigger("liszt:updated");';//Reload
Chosen older version
}
$s[] = ' } else {';
$s[] = '
jQuery("#ph-request-message").show();';
$s[] = '
jQuery(\'#ph-request-message\').html(data.error)';
$s[] = ' }';
$s[] = ' }';
$s[] = ' });';
$s[] = '}';
JFactory::getDocument()->addScriptDeclaration(implode("\n",
$s));
$query = 'SELECT a.title AS text, a.id AS value'
. ' FROM #__phocacart_countries AS a'
. ' WHERE a.published = 1'
. ' ORDER BY a.ordering';
$db->setQuery( $query );
$data = $db->loadObjectList();
$attr = '';
$attr .= !empty($this->class) ? ' class="' .
$this->class . ' form-control chosen-select
ph-input-select-countries"' : 'class="form-control
chosen-select ph-input-select-countries"';
$attr .= !empty($this->size) ? ' size="' .
$this->size . '"' : '';
$attr .= $this->multiple ? ' multiple' : '';
$attr .= $this->required ? ' required
aria-required="true"' : '';
$attr .= $this->autofocus ? ' autofocus' : '';
// Set default value in case, there is no value
if (($this->value == 0 || $this->value == '') &&
isset($this->default) && (int)$this->default > 0) {
$this->value = $this->default;
$this->form->setValue(str_replace('jform_',
'', $this->id), null, $this->default);
}
if ((string) $this->readonly == '1' || (string)
$this->readonly == 'true' || (string) $this->disabled ==
'1'|| (string) $this->disabled == 'true') {
$attr .= ' disabled="disabled"';
}
$attr .= $this->onchange ? '
onchange="phUpdateRegion'.$this->id.'(this.value);'
. $this->onchange . '" ' : '
onchange="phUpdateRegion'.$this->id.'(this.value);"
';
array_unshift($data,
Joomla\CMS\HTML\HTMLHelper::_('select.option', '',
'- '.JText::_('COM_PHOCACART_SELECT_COUNTRY').' -',
'value', 'text'));
return Joomla\CMS\HTML\HTMLHelper::_('select.genericlist',
$data, $this->name, trim($attr), 'value', 'text',
$this->value, $this->id );
}
}
?>
fields/phocaformregion.php000064400000005626151165414670011730
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
class JFormFieldPhocaFormRegion extends JFormField
{
protected $type = 'PhocaFormRegion';
protected function getInput() {
$db = JFactory::getDBO();
$country = $this->form->getValue('country');
$countryPhs = $this->form->getValue('country_phs');
$countryPhb = $this->form->getValue('country_phb');
$countryId = 0;
if ($this->id == 'jform_region' && (int)$country
> 0) {
$countryId = (int)$country;
}
if ($this->id == 'jform_region_phs' &&
(int)$countryPhs > 0) {
$countryId = (int)$countryPhs;
}
if ($this->id == 'jform_region_phb' &&
(int)$countryPhb > 0) {
$countryId = (int)$countryPhb;
}
$query = 'SELECT a.title AS text, a.id AS value'
. ' FROM #__phocacart_regions AS a'
. ' WHERE a.published = 1';
if ($countryId > 0) {
$query .= ' AND a.country_id = '.(int)$countryId;
}
$query .= ' ORDER BY a.ordering';
$db->setQuery( $query );
$data = $db->loadObjectList();
// Set default value in case, there is no value
// Check if the default value belongs to country
if (($this->value == 0 || $this->value == '') &&
isset($this->default) && (int)$this->default > 0) {
$queryR = 'SELECT a.id'
. ' FROM #__phocacart_regions AS a'
. ' WHERE a.published = 1';
if ($countryId > 0) {
$queryR .= ' AND a.country_id = '.(int)$countryId;
}
$queryR .= ' ORDER BY a.ordering';
$db->setQuery( $queryR );
$dataR = $db->loadColumn();
if (!empty($dataR)) {
if (in_array($this->default, $dataR)) {
$this->value = $this->default;
}
}
}
$attr = '';
$attr .= !empty($this->class) ? ' class="' .
$this->class . ' form-control chosen-select
ph-input-select-region"' : 'class="form-control
chosen-select ph-input-select-region"';
$attr .= !empty($this->size) ? ' size="' .
$this->size . '"' : '';
$attr .= $this->multiple ? ' multiple' : '';
$attr .= $this->required ? ' required
aria-required="true"' : '';
$attr .= $this->autofocus ? ' autofocus' : '';
if ((string) $this->readonly == '1' || (string)
$this->readonly == 'true' || (string) $this->disabled ==
'1'|| (string) $this->disabled == 'true') {
$attr .= ' disabled="disabled"';
}
$attr .= $this->onchange ? ' onchange="' .
$this->onchange . '"' : '';
array_unshift($data,
Joomla\CMS\HTML\HTMLHelper::_('select.option', '',
'- '.JText::_('COM_PHOCACART_SELECT_REGION').' -',
'value', 'text'));
return Joomla\CMS\HTML\HTMLHelper::_('select.genericlist',
$data, $this->name, trim($attr), 'value', 'text',
$this->value, $this->id );
}
}
?>
fields/phocamanufacturer.php000064400000002040151165414670012240
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
class JFormFieldPhocaManufacturer extends JFormField
{
protected $type = 'PhocaManufacturer';
protected function getInput() {
$db = JFactory::getDBO();
$query = 'SELECT a.title AS text, a.id AS value'
. ' FROM #__phocacart_manufacturers AS a'
. ' WHERE a.published = 1'
. ' ORDER BY a.ordering';
$db->setQuery( $query );
$data = $db->loadObjectList();
array_unshift($data,
Joomla\CMS\HTML\HTMLHelper::_('select.option', '',
'-
'.JText::_('COM_PHOCACART_SELECT_MANUFACTURER').'
-', 'value', 'text'));
return Joomla\CMS\HTML\HTMLHelper::_('select.genericlist',
$data, $this->name, 'class="inputbox"',
'value', 'text', $this->value, $this->id );
}
}
?>
fields/phocataglabels.php000064400000002501151165414670011504
0ustar00<?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
version 2 or later;
*/
defined('_JEXEC') or die();
class JFormFieldPhocaTaglabels extends JFormField
{
protected $type = 'PhocaTaglabels';
protected function getInput() {
$id = (int) $this->form->getValue('id');
$javascript = '';
$required = $this->required;// accept dynamically added required
$multiple = ((string) $this->element['multiple'] ==
'true') ? TRUE : FALSE;
$class = ((string) $this->element['class'] !=
'') ?
'class="'.$this->element['class'].'"'
: 'class="inputbox"';
$attr = '';
$attr .= $class . ' ';
if ($multiple) {
$attr .= 'size="4" multiple="multiple"
';
}
if ($required) {
$attr .= 'required aria-required="true" ';
}
$attr .= $javascript . ' ';
$activeTags = array();
if ((int)$id > 0) {
$activeTags = PhocacartTag::getTagLabels($id, 1);
}
return PhocacartTag::getAllTagsSelectBox($this->name, $this->id,
$activeTags, NULL, 'id', 1, $attr );
}
}
?>
fields/phocataglabelssubmititems.php000064400000002537151165414670014003
0ustar00<?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
version 2 or later;
*/
defined('_JEXEC') or die();
class JFormFieldPhocaTaglabelsSubmitItems extends JFormField
{
protected $type = 'PhocaTaglabelsSubmitItems';
protected function getInput() {
$id = (int) $this->form->getValue('id');
$javascript = '';
$required = $this->required;// accept dynamically added required
$multiple = ((string) $this->element['multiple'] ==
'true') ? TRUE : FALSE;
$class = ((string) $this->element['class'] !=
'') ?
'class="'.$this->element['class'].'"'
: 'class="inputbox"';
$attr = '';
$attr .= $class . ' ';
if ($multiple) {
$attr .= 'size="4" multiple="multiple"
';
}
if ($required) {
$attr .= 'required aria-required="true" ';
}
$attr .= $javascript . ' ';
$activeTags = array();
if ((int)$id > 0) {
$activeTags = PhocacartTag::getTagLabelsSubmitItems($id);
}
return PhocacartTag::getAllTagsSelectBox($this->name, $this->id,
$activeTags, NULL, 'id', 1, $attr );
}
}
?>
fields/phocatags.php000064400000002464151165414670010514 0ustar00<?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
version 2 or later;
*/
defined('_JEXEC') or die();
class JFormFieldPhocaTags extends JFormField
{
protected $type = 'PhocaTags';
protected function getInput() {
$id = (int) $this->form->getValue('id');
$javascript = '';
$required = $this->required;// accept dynamically added required
$multiple = ((string) $this->element['multiple'] ==
'true') ? TRUE : FALSE;
$class = ((string) $this->element['class'] !=
'') ?
'class="'.$this->element['class'].'"'
: 'class="inputbox"';
$attr = '';
$attr .= $class . ' ';
if ($multiple) {
$attr .= 'size="4" multiple="multiple"
';
}
if ($required) {
$attr .= 'required aria-required="true" ';
}
$attr .= $javascript . ' ';
$activeTags = array();
if ((int)$id > 0) {
$activeTags = PhocacartTag::getTags($id, 1);
}
return PhocacartTag::getAllTagsSelectBox($this->name, $this->id,
$activeTags, NULL, 'id', 0, $attr );
}
}
?>
fields/phocatagssubmititems.php000064400000002520151165414670012773
0ustar00<?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
version 2 or later;
*/
defined('_JEXEC') or die();
class JFormFieldPhocaTagsSubmitItems extends JFormField
{
protected $type = 'PhocaTagsSubmitItems';
protected function getInput() {
$id = (int) $this->form->getValue('id');
$javascript = '';
$required = $this->required;// accept dynamically added required
$multiple = ((string) $this->element['multiple'] ==
'true') ? TRUE : FALSE;
$class = ((string) $this->element['class'] !=
'') ?
'class="'.$this->element['class'].'"'
: 'class="inputbox"';
$attr = '';
$attr .= $class . ' ';
if ($multiple) {
$attr .= 'size="4" multiple="multiple"
';
}
if ($required) {
$attr .= 'required aria-required="true" ';
}
$attr .= $javascript . ' ';
$activeTags = array();
if ((int)$id > 0) {
$activeTags = PhocacartTag::getTagsSubmitItems($id);
}
return PhocacartTag::getAllTagsSelectBox($this->name, $this->id,
$activeTags, NULL, 'id', 0, $attr );
}
}
?>
fields/phocatax.php000064400000003252151165414670010346 0ustar00<?php
/*
* @package Joomla.Framework
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*
* @component Phoca Component
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
version 2 or later;
*/
defined('_JEXEC') or die();
class JFormFieldPhocaTax extends JFormField
{
protected $type = 'PhocaTax';
protected function getInput() {
$db = JFactory::getDBO();
$javascript = '';
$required = $this->required;// accept dynamically added required
$multiple = ((string) $this->element['multiple'] ==
'true') ? TRUE : FALSE;
$class = ((string) $this->element['class'] !=
'') ?
'class="'.$this->element['class'].'"'
: 'class="inputbox"';
$attr = '';
$attr .= $class . ' ';
if ($multiple) {
$attr .= 'size="4" multiple="multiple"
';
}
if ($required) {
$attr .= 'required aria-required="true" ';
}
$attr .= $javascript . ' ';
$query = 'SELECT a.title AS text, a.id AS value'
. ' FROM #__phocacart_taxes AS a'
. ' WHERE a.published = 1'
. ' ORDER BY a.ordering';
$db->setQuery( $query );
$data = $db->loadObjectList();
if (!empty($data)) {
foreach($data as $k => $v) {
$data[$k]->text = JText::_($v->text);
}
}
array_unshift($data,
Joomla\CMS\HTML\HTMLHelper::_('select.option', '',
'- '.JText::_('COM_PHOCACART_SELECT_TAX').'
-', 'value', 'text'));
return Joomla\CMS\HTML\HTMLHelper::_('select.genericlist',
$data, $this->name, $attr, 'value', 'text',
$this->value, $this->id );
}
}
?>
fields/phocatext.php000064400000007213151165414670010537 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
JFormHelper::loadFieldClass('text');
class JFormFieldPhocaText extends JFormFieldText
{
protected $type = 'PhocaText';
protected function getInput() {
if (!$this->hidden &&
($this->form->getValue('version') == 1)) {
// Initialize some field attributes.
$size = $this->element['size'] ? '
size="'.(int)
$this->element['size'].'"' : '';
//$class = $this->element['class'] ? '
class="'.(string) $this->element['class'].'
form-control"' :
'class="form-control"';//Bootstrap3
$class = $this->element['class'] ? '
class="'.(string) $this->element['class'].'
"' : '';
$maxLength = $this->element['maxlength'] ? '
maxlength="'.(int)
$this->element['maxlength'].'"' : '';
$readonly = ((string) $this->element['readonly'] ==
'true') ? ' readonly="readonly"' :
'';
$disabled = ((string) $this->element['disabled'] ==
'true') ? ' disabled="disabled"' :
'';
$placeholder= htmlspecialchars($this->getTitle() .
($this->required ? ' ' .
JText::_('COM_PHOCAGUESTBOOK_REQUIREDSIGN') : ''),
ENT_COMPAT, 'UTF-8');
// Initialize JavaScript field attributes.
$onchange = $this->element['onchange'] ? '
onchange="'.(string)
$this->element['onchange'].'"' : '';
$value = htmlspecialchars($this->value, ENT_COMPAT,
'UTF-8');
$requInput = $this->required ? ' required="required"
aria-required="true"' : '';
//prepend:
$preIcon = $this->element['preicon'] ? '<i
class="' . $this->element['preicon'] . '"
title="' . $placeholder . '"></i>' :
'';
$postIcon = $this->element['posticon'] ? '<i
class="' . $this->element['posticon'] .
'"></i>' : '';
if ($postIcon && $this->element['posthref']) {
//$postIcon = '<a href="' . (string)
$this->element['posthref'] . '" title="' .
JText::_('COM_PHOCAGUESTBOOK_RELOAD_IMAGE') . '"
class="btn hasTooltip" >' . $postIcon .
'</a>';
$postIcon = '<span class="add-on
input-group-addon"><a href="' . (string)
$this->element['posthref'] . '" title="' .
JText::_('COM_PHOCAGUESTBOOK_RELOAD_IMAGE') . '"
class="" >' . $postIcon .
'</a></span>';
}
// Get the label text from the XML element, defaulting to the element
name.
$text = $this->element['label'] ? (string)
$this->element['label'] : (string)
$this->element['name'];
$text = $this->translateLabel ? JText::_($text) : $text;
// Add the opening label tag and main attributes attributes.
$label = '<label id="' . $this->id .
'-lbl" for="' . $this->id . '"
class="element-invisible" title="' . $placeholder .
'">' . $text . '</label>';
return '<span class="add-on
input-group-addon">' . $preIcon . $label .
'</span>'
. '<input'. $requInput. ' type="text"
name="'.$this->name.'"
id="'.$this->id.'"
placeholder="'.$placeholder.'"
value="'.$value.'"'
.$class.$size.$disabled.$readonly.$onchange.$maxLength.'/>
' . $postIcon;
} else {
$postIcon = $this->element['posticon'] ? '<i
class="' . $this->element['posticon'] .
'"></i>' : '';
if ($postIcon && $this->element['posthref']) {
$postIcon = '<a href="' . (string)
$this->element['posthref'] . '" title="' .
JText::_('COM_PHOCAGUESTBOOK_RELOAD_IMAGE') . '"
class="btn " >' . $postIcon . '</a>';
}
return parent::getInput() . $postIcon;
}
}
protected function getLabel() {
if (!$this->hidden &&
($this->form->getValue('version') == 1)) {
return '';
} else {
return parent::getLabel();
}
}
}
?>
fields/phocaurl.php000064400000005634151165414670010362 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
JFormHelper::loadFieldClass('url');
class JFormFieldPhocaUrl extends JFormFieldUrl
{
protected $type = 'PhocaUrl';
protected function getInput() {
if (!$this->hidden &&
($this->form->getValue('version') == 1)) {
// Initialize some field attributes.
$size = $this->element['size'] ? '
size="'.(int)
$this->element['size'].'"' : '';
$class = $this->element['class'] ? '
class="'.(string)
$this->element['class'].'"' : '';
$maxLength = $this->element['maxlength'] ? '
maxlength="'.(int)
$this->element['maxlength'].'"' : '';
$readonly = ((string) $this->element['readonly'] ==
'true') ? ' readonly="readonly"' :
'';
$disabled = ((string) $this->element['disabled'] ==
'true') ? ' disabled="disabled"' :
'';
$placeholder= htmlspecialchars($this->getTitle() .
($this->required ?
''.JText::_('COM_PHOCAGUESTBOOK_REQUIREDSIGN') :
''), ENT_COMPAT, 'UTF-8');
// Initialize JavaScript field attributes.
$onchange = $this->element['onchange'] ? '
onchange="'.(string)
$this->element['onchange'].'"' : '';
$value = htmlspecialchars($this->value, ENT_COMPAT,
'UTF-8');
$requInput = $this->required ? ' required="required"
aria-required="true"' : '';
//prepend:
$preIcon = $this->element['preicon'] ? '<i
class="' . $this->element['preicon'] . '
tip" title="' . $placeholder .
'"></i>' : '';
$postIcon = $this->element['posticon'] ? '<i
class="' . $this->element['preicon'] .
'"></i>' : '';
if ($postIcon && $this->element['posthref']) {
$postIcon = '<a href="' . (string)
$this->element['posthref'] . '" title="' .
JText::_('COM_PHOCAGUESTBOOK_RELOAD_IMAGE') . '"
class="btn hasTooltip" >' . $postIcon .
'</a>';
}
// Get the label text from the XML element, defaulting to the element
name.
$text = $this->element['label'] ? (string)
$this->element['label'] : (string)
$this->element['name'];
$text = $this->translateLabel ? JText::_($text) : $text;
// Add the opening label tag and main attributes attributes.
$label = '<label id="' . $this->id .
'-lbl" for="' . $this->id . '"
class="element-invisible" title="' . $placeholder .
'">' . $text . '</label>';
return '<span class="add-on">' . $preIcon .
$label . '</span>'
. '<input'. $requInput. ' type="text"
name="'.$this->name.'"
id="'.$this->id.'"
placeholder="'.$placeholder.'"
value="'.$value.'"'
.$class.$size.$disabled.$readonly.$onchange.$maxLength.'/>';
} else {
return parent::getInput();
}
}
protected function getLabel() {
if (!$this->hidden &&
($this->form->getValue('version') == 1)) {
return '';
} else {
return parent::getLabel();
}
}
}
?>
forms/checkout.xml000064400000000443151165414670010234 0ustar00<?xml
version="1.0" encoding="UTF-8"?>
<form>
<fieldset name="user"
addrulepath="components/com_phocacart/models/rules"
addfieldpath="components/com_phocacart/models/fields"
label="COM_PHOCACART_FORM_LABEL">
</fieldset>
<fieldset name="hidden">
</fieldset>
</form>
forms/index.html000064400000000072151165414670007700
0ustar00<html><body style="background-color:
#000;"></body></html>forms/question.xml000064400000006432151165414670010302
0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset
addfieldpath="/components/com_phocacart/models/fields"
addrulepath="/components/com_phocacart/models/rules">
<field name="id" type="text" default="0"
label="JGLOBAL_FIELD_ID_LABEL" readonly="true"
class="readonly" filter="integer" />
<field name="user_id" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_USER_ID_LABEL"
description="COM_PHOCACART_FIELD_USER_ID_DESC"
filter="integer" />
<field name="product_id" type="hidden"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_PRODUCT_ID_LABEL"
description="COM_PHOCACART_FIELD_PRODUCT_ID_DESC"
filter="integer" />
<field name="category_id" type="hidden"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_CATEGORY_ID_LABEL"
description="COM_PHOCACART_FIELD_CATEGORY_ID_DESC"
filter="integer" />
<field name="name" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_NAME_LABEL"
description="COM_PHOCACART_FIELD_F_NAME_DESC"
filter="string" />
<field name="email" type="email"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_EMAIL_LABEL"
description="COM_PHOCACART_FIELD_F_EMAIL_DESC"
validate="phocacartemail" filter="string" />
<field name="phone" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_PHONE_LABEL"
description="COM_PHOCACART_FIELD_F_PHONE_DESC"
filter="string" />
<field name="phone_mobile" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_MOBILE_PHONE_LABEL"
description="COM_PHOCACART_FIELD_F_MOBILE_PHONE_DESC"
filter="string" />
<field name="message" type="textarea"
class="inputbox ph-question-message"
label="COM_PHOCACART_FIELD_F_MESSAGE_LABEL"
description="COM_PHOCACART_FIELD_F_MESSAGE_DESC"
filter="string" rows="7" cols="45" />
<field
name="phq_captcha"
id="question-captcha"
type="phocacaptcha"
required="true"
label="COM_PHOCACART_SECURITY_CHECK"
description="COM_PHOCACART_PLEASE_PROVE_THAT_YOU_ARE_HUMAN"
validate="phocacartcaptcha"
preicon=""
posticon=""
posthref=""
class="inputbox"
/>
<field name="ip" type="hidden"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_IP_LABEL"
description="COM_PHOCACART_FIELD_IP_DESC"
filter="string" />
<field name="ordering" type="PhocacartOrdering"
table="region" class="inputbox"
label="COM_PHOCACART_FIELD_ORDERING_LABEL"
description="COM_PHOCACART_FIELD_ORDERING_DESC"
filter="integer" />
</fieldset>
<fieldset name="publish"
label="COM_PHOCACART_GROUP_LABEL_PUBLISHING_DETAILS" >
<field name="published" type="list"
label="COM_PHOCACART_FIELD_PUBLISHED_LABEL"
description="COM_PHOCACART_FIELD_PUBLISHED_DESC"
class="inputbox" size="1" default="1"
filter="string" >
<option value="1">JPUBLISHED</option>
<option value="0">JUNPUBLISHED</option>
</field>
<field name="language" type="contentlanguage"
label="JFIELD_LANGUAGE_LABEL"
description="COM_PHOCACART_FIELD_LANGUAGE_DESC"
class="inputbox" filter="string">
<option value="*">JALL</option>
</field>
<field name="date" type="Calendar"
class="inputbox" label="COM_PHOCACART_FIELD_DATE_LABEL"
description="COM_PHOCACART_FIELD_DATE_DESC"
filter="server-utc" />
</fieldset>
<fieldset >
<field name="hidden_field" type="text"
preicon="icon-flag" id="phocacart-hidden"
validate="phocacarthidden"/>
<field name="privacy" type="hidden"
filter="integer"/>
</fieldset>
</form>
forms/submit.xml000064400000032227151165414670007737 0ustar00<?xml
version="1.0" encoding="utf-8"?>
<form>
<fields name="items_item">
<fieldset name="items_item"
addfieldpath="/components/com_phocacart/models/fields"
addrulepath="/components/com_phocacart/models/rules">
<field name="title" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_TITLE_LABEL"
description="COM_PHOCACART_FIELD_TITLE_DESC"
filter="string"/>
<field name="alias" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_ALIAS_LABEL"
description="COM_PHOCACART_FIELD_ALIAS_DESC"
filter="string"/>
<field name="sku" type="text"
class="inputbox" size="255"
label="COM_PHOCACART_FIELD_SKU_LABEL"
description="COM_PHOCACART_FIELD_SKU_DESC"
filter="string"/>
<field name="upc" type="text"
class="inputbox" size="15"
label="COM_PHOCACART_FIELD_UPC_LABEL"
description="COM_PHOCACART_FIELD_UPC_DESC"
filter="string"/>
<field name="ean" type="text"
class="inputbox" size="15"
label="COM_PHOCACART_FIELD_EAN_LABEL"
description="COM_PHOCACART_FIELD_EAN_DESC"
filter="string"/>
<field name="jan" type="text"
class="inputbox" size="15"
label="COM_PHOCACART_FIELD_JAN_LABEL"
description="COM_PHOCACART_FIELD_JAN_DESC"
filter="string"/>
<field name="isbn" type="text"
class="inputbox" size="15"
label="COM_PHOCACART_FIELD_ISBN_LABEL"
description="COM_PHOCACART_FIELD_ISBN_DESC"
filter="string"/>
<field name="mpn" type="text"
class="inputbox" size="255"
label="COM_PHOCACART_FIELD_MPN_LABEL"
description="COM_PHOCACART_FIELD_MPN_DESC"
filter="string"/>
<field name="serial_number" type="text"
class="inputbox" size="255"
label="COM_PHOCACART_FIELD_SERIAL_NUMBER_LABEL"
description="COM_PHOCACART_FIELD_SERIAL_NUMBER_DESC"
filter="string"/>
<field name="registration_key"
type="text" class="inputbox" size="255"
label="COM_PHOCACART_FIELD_REGISTRATION_KEY_LABEL"
description="COM_PHOCACART_FIELD_REGISTRATION_KEY_DESC"
filter="string"/>
<field name="external_id" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_EXTERNAL_PRODUCT_ID_LABEL"
description="COM_PHOCACART_FIELD_EXTERNAL_PRODUCT_ID_DESC"
filter="string"/>
<field name="external_key" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_EXTERNAL_PRODUCT_KEY_LABEL"
description="COM_PHOCACART_FIELD_EXTERNAL_PRODUCT_KEY_DESC"
filter="string"/>
<field name="external_link" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_EXTERNAL_LINK_LABEL"
description="COM_PHOCACART_FIELD_EXTERNAL_LINK_DESC"
filter="url"/>
<field name="external_text" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_EXTERNAL_TEXT_LABEL"
description="COM_PHOCACART_FIELD_EXTERNAL_TEXT_DESC"
filter="string"/>
<field name="external_link2" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_EXTERNAL_LINK_2_LABEL"
description="COM_PHOCACART_FIELD_EXTERNAL_LINK_2_DESC"
filter="url"/>
<field name="external_text2" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_EXTERNAL_TEXT_2_LABEL"
description="COM_PHOCACART_FIELD_EXTERNAL_TEXT_2_DESC"
filter="string"/>
<field name="price" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_PRICE_LABEL"
description="COM_PHOCACART_FIELD_PRICE_DESC"
filter="float"/>
<field name="price_original" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_ORIGINAL_PRICE_LABEL"
description="COM_PHOCACART_FIELD_ORIGINAL_PRICE_DESC"
filter="float"/>
<field name="tax_id" type="phocatax"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_TAX_LABEL"
description="COM_PHOCACART_FIELD_TAX_DESC"
filter="integer"/>
<field name="catid_multiple"
type="phocacartcategory"
label="COM_PHOCACART_FIELD_CATEGORY_LABEL"
description="COM_PHOCACART_FIELD_CATEGORY_DESC"
class="inputbox" multiple="true"
filter="int_array"/>
<field name="manufacturer_id"
type="phocamanufacturer"
label="COM_PHOCACART_FIELD_MANUFACTURER_LABEL"
description="COM_PHOCACART_FIELD_MANUFACTURER_DESC"
class="inputbox" filter="integer"/>
<field name="description"
type="textarea" buttons="true"
hide="pagebreak,readmore" class="inputbox"
label="COM_PHOCACART_FIELD_DESCRIPTION_LABEL"
filter="string"
description="COM_PHOCACART_FIELD_DESCRIPTION_DESC"
cols="75" rows="10"/>
<field name="description_long"
type="textarea" buttons="true"
hide="pagebreak,readmore" class="inputbox"
label="COM_PHOCACART_FIELD_DESCRIPTION_LONG_LABEL"
filter="string"
description="COM_PHOCACART_FIELD_DESCRIPTION_LONG_DESC"
cols="75" rows="10"/>
<field name="features" type="textarea"
buttons="true" hide="pagebreak,readmore"
class="inputbox"
label="COM_PHOCACART_FIELD_FEATURES_LABEL"
filter="string"
description="COM_PHOCACART_FIELD_FEATURES_DESC"
cols="75" rows="10"/>
<field name="image" type="phocacartfile"
typemethod="image"
label="COM_PHOCACART_FIELD_IMAGE_LABEL"
description="COM_PHOCACART_FIELD_IMAGE_DESC" class="inputbox
imageCreateThumbs" size="40" filter="string"/>
<field name="video" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_VIDEO_URL_LABEL"
description="COM_PHOCACART_FIELD_VIDEO_URL_DESC"
filter="url"/>
<field name="type" default="0"
type="list"
label="COM_PHOCACART_FIELD_PRODUCT_TYPE_LABEL"
description="COM_PHOCACART_FIELD_PRODUCT_TYPE_DESC"
filter="integer">
<option
value="0">COM_PHOCACART_PHYSICAL_PRODUCT</option>
<option
value="1">COM_PHOCACART_DIGITAL_DOWNLOADABLE_PRODUCT</option>
<option
value="2">COM_PHOCACART_MIXED_PRODUCT_DIGITAL_PHYSICAL</option>
<option
value="3">COM_PHOCACART_PRICE_ON_DEMAND_PRODUCT</option>
</field>
<field name="unit_amount" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_UNIT_AMOUNT_LABEL"
description="COM_PHOCACART_FIELD_UNIT_AMOUNT_DESC"
filter="string"/>
<field name="unit_unit" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_UNIT_UNIT_LABEL"
description="COM_PHOCACART_FIELD_UNIT_UNIT_DESC"
filter="string"/>
<field name="length" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_LENGTH_LABEL"
description="COM_PHOCACART_FIELD_LENGTH_DESC"
filter="string"/>
<field name="width" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_WIDTH_LABEL"
description="COM_PHOCACART_FIELD_WIDTH_DESC"
filter="string"/>
<field name="height" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_HEIGHT_LABEL"
description="COM_PHOCACART_FIELD_HEIGHT_DESC"
filter="string"/>
<field name="weight" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_WEIGHT_LABEL"
description="COM_PHOCACART_FIELD_WEIGHT_DESC"
filter="string"/>
<field name="volume" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_VOLUME_LABEL"
description="COM_PHOCACART_FIELD_VOLUME_DESC"
filter="string"/>
<field name="condition" type="list"
label="COM_PHOCACART_FIELD_PRODUCT_CONDITION_LABEL"
description="COM_PHOCACART_FIELD_PRODUCT_CONDITION_DESC"
class="inputbox" size="1" default="0"
filter="integer">
<option
value="0">COM_PHOCACART_CONDITION_NEW</option>
<option
value="1">COM_PHOCACART_CONDITION_REFURBISHED</option>
<option
value="2">COM_PHOCACART_CONDITION_USED</option>
</field>
<field name="type_feed" type="textarea"
label="COM_PHOCACART_FIELD_PRODUCT_TYPE_FEED_LABEL"
description="COM_PHOCACART_FIELD_PRODUCT_TYPE_FEED_DESC"
class="inputbox" rows="3" cols="30"
filter="string"/>
<field name="type_category_feed"
type="textarea"
label="COM_PHOCACART_FIELD_PRODUCT_CATEGORY_TYPE_FEED_LABEL"
description="COM_PHOCACART_FIELD_PRODUCT_CATEGORY_TYPE_FEED_DESC"
class="inputbox" rows="3"
cols="30" filter="string"/>
<field name="delivery_date"
type="Calendar" class="inputbox"
label="COM_PHOCACART_FIELD_PRODUCT_DELIVERY_DATE_LABEL"
description="COM_PHOCACART_FIELD_PRODUCT_DELIVERY_DATE_DESC"
filter="string" showtime="true"
format="%Y-%m-%d %H:%M:%S"/>
<field name="metatitle" type="text"
label="COM_PHOCACART_FIELD_META_TITLE_LABEL"
description="COM_PHOCACART_FIELD_META_TITLE_DESC"
class="inputbox"
filter="string"/>
<field name="metakey" type="textarea"
label="JField_Meta_Keywords_Label"
description="JField_Meta_Keywords_Desc"
class="inputbox" rows="3"
cols="30" filter="string"/>
<field name="metadesc" type="textarea"
label="JField_Meta_Description_Label"
description="JField_Meta_Description_Desc"
class="inputbox" rows="3"
cols="30" filter="string"/>
<field name="date" type="Calendar"
class="inputbox" label="COM_PHOCACART_FIELD_DATE_LABEL"
description="COM_PHOCACART_FIELD_DATE_DESC"
filter="string"/>
<field name="date_update"
type="Calendar" class="inputbox"
label="COM_PHOCACART_FIELD_UPDATE_DATE_LABEL"
description="COM_PHOCACART_FIELD_UPDATE_DATE_DESC"
filter="string"/>
<field name="tags" type="phocatags"
multiple="true" label="COM_PHOCACART_FIELD_TAGS_LABEL"
description="COM_PHOCACART_FIELD_TAGS_DESC"
class="inputbox" size="1"
filter="int_array"/>
<field name="taglabels"
type="phocataglabels" multiple="true"
label="COM_PHOCACART_FIELD_LABELS_LABEL"
description="COM_PHOCACART_FIELD_LABELS_DESC"
class="inputbox" size="1"
filter="int_array"/>
</fieldset>
</fields>
<fields name="items_contact">
<fieldset name="items_contact"
addfieldpath="/components/com_phocacart/models/fields"
addrulepath="/components/com_phocacart/models/rules">
<field name="name" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_NAME_LABEL"
description="COM_PHOCACART_FIELD_F_NAME_DESC"
filter="string"/>
<field name="email" type="email"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_EMAIL_LABEL"
description="COM_PHOCACART_FIELD_F_EMAIL_DESC"
filter="string" validate="phocacartemail"/>
<field name="phone" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_PHONE_LABEL"
description="COM_PHOCACART_FIELD_F_PHONE_DESC"
filter="string"/>
<field name="phone_mobile" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_F_MOBILE_PHONE_LABEL"
description="COM_PHOCACART_FIELD_F_MOBILE_PHONE_DESC"
filter="string"/>
<field name="message" type="textarea"
class="inputbox ph-question-message"
label="COM_PHOCACART_FIELD_F_MESSAGE_LABEL"
description="COM_PHOCACART_FIELD_F_MESSAGE_DESC"
filter="string"
rows="7" cols="45"/>
</fieldset>
</fields>
<fieldset
addfieldpath="/components/com_phocacart/models/fields"
addrulepath="/components/com_phocacart/models/rules">
<field name="hidden_field" type="text"
preicon="icon-flag" id="phocacart-hidden"
validate="phocacarthidden"/>
<field
name="phq_captcha"
id="question-captcha"
type="phocacaptcha"
required="true"
label="COM_PHOCACART_SECURITY_CHECK"
description="COM_PHOCACART_PLEASE_PROVE_THAT_YOU_ARE_HUMAN"
validate="phocacartcaptcha"
preicon=""
posticon=""
posthref=""
class="inputbox"
/>
<field name="ip" type="hidden"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_IP_LABEL"
description="COM_PHOCACART_FIELD_IP_DESC"
filter="string"/>
<field name="id" type="text"
default="0" label="JGLOBAL_FIELD_ID_LABEL"
readonly="true" class="readonly"/>
<field name="user_id" type="user"
default="0" label="COM_PHOCACART_USER_ID_LABEL"
description="COM_PHOCACART_USER_ID_DESC"/>
<field name="date_submit" type="Calendar"
class="inputbox" label="COM_PHOCACART_FIELD_DATE_LABEL"
description="COM_PHOCACART_FIELD_DATE_DESC"
filter="JComponentHelper::filterText"/>
<field name="published" type="list"
label="COM_PHOCACART_FIELD_PUBLISHED_LABEL"
description="COM_PHOCACART_FIELD_PUBLISHED_DESC"
class="inputbox" size="1" default="1">
<option value="1">JPUBLISHED</option>
<option value="0">JUNPUBLISHED</option>
</field>
<field name="ordering"
type="PhocacartOrdering" table="submititem"
class="inputbox"
label="COM_PHOCACART_FIELD_ORDERING_LABEL"
description="COM_PHOCACART_FIELD_ORDERING_DESC"/>
<field name="privacy" type="hidden"
filter="integer"/>
<field name="upload_folder" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_UPLOAD_FOLDER_LABEL"
description="COM_PHOCACART_FIELD_UPLOAD_FOLDER_LABEL"
filter="string"/>
<field name="upload_token" type="text"
class="inputbox" size="40"
label="COM_PHOCACART_FIELD_UPLOAD_TOKEN_LABEL"
description="COM_PHOCACART_FIELD_UPLOAD_TOKEN_LABEL"
filter="string"/>
</fieldset>
<fieldset>
<field name="hidden_field" type="text"
preicon="icon-flag" id="phocacart-hidden"
validate="phocacarthidden"/>
</fieldset>
</form>
item.php000064400000031044151165414670006227 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelItem extends JModelLegacy
{
var $item = null;
var $category = null;
var $itemname = null;
var $itemnext = null;
var $itemprev = null;
function __construct() {
$app = JFactory::getApplication();
parent::__construct();
$this->setState('filter.language',$app->getLanguageFilter());
}
function getItem( $itemId, $catId) {
if (empty($this->item)) {
$query = $this->getItemQuery( $itemId, $catId);
$this->item = $this->_getList( $query, 0 , 1 );
if (empty($this->item)) {
return null;
}
}
return $this->item;
}
function getItemNext($ordering, $catid) {
if (empty($this->itemnext)) {
$query = $this->getItemQueryOrdering( $ordering, $catid, 2 );
$this->itemnext = $this->_getList( $query, 0 , 1 );
if (empty($this->itemnext)) {
return null;
}
}
return $this->itemnext;
}
function getItemPrev($ordering, $catid) {
if (empty($this->itemprev)) {
$query = $this->getItemQueryOrdering( $ordering, $catid, 1 );
$this->itemprev = $this->_getList( $query, 0 , 1 );
if (empty($this->itemprev)) {
return null;
}
}
return $this->itemprev;
}
private function getItemQueryOrdering($ordering, $catid, $direction) {
$app = JFactory::getApplication();
$params = $app->getParams();
$p['hide_products_out_of_stock'] = $params->get(
'hide_products_out_of_stock', 0);
$skip = array();
$skip['access'] =
$params->get('sql_product_skip_access', 0);
$skip['group'] =
$params->get('sql_product_skip_group', 0);
//$skip['attributes'] =
$params->get('sql_product_skip_attributes', 0);
$skip['category_type'] =
$params->get('sql_product_skip_category_type', 0);
//$skip['tax'] =
$params->get('sql_product_skip_tax', 0);
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$wheres[] = " pc.category_id = ".(int) $catid;
//$wheres[] = " c.catid= c.id";
$wheres[] = " a.published = 1";
$wheres[] = " c.published = 1";
if ($direction == 1) {
$wheres[] = " pc.ordering < " . (int) $ordering;
$order = 'DESC';
} else {
$wheres[] = " pc.ordering > " . (int) $ordering;
$order = 'ASC';
}
if (!$skip['category_type']) {
$wheres[] = " c.type IN (0,1)";// type: common, onlineshop,
pos
}
if (!$skip['access']) {
$wheres[] = " c.access IN (" . $userLevels . ")";
$wheres[] = " a.access IN (" . $userLevels . ")";
}
if (!$skip['group']) {
$wheres[] = " (ga.group_id IN (" . $userGroups . ") OR
ga.group_id IS NULL)";
$wheres[] = " (gc.group_id IN (" . $userGroups . ") OR
gc.group_id IS NULL)";
}
if ($this->getState('filter.language')) {
$lang = JFactory::getLanguage()->getTag();
$wheres[] =
PhocacartUtilsSettings::getLangQuery('a.language', $lang);
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
if ($p['hide_products_out_of_stock'] == 1) {
$wheres[] = " a.stock > 0";
}
$query = ' SELECT a.id, a.title, a.alias, a.catid, c.id AS
categoryid, c.title AS categorytitle, c.alias AS categoryalias'
.' FROM #__phocacart_products AS a'
.' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = a.id'
.' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id';
if (!$skip['group']) {
$query .= ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id =
ga.item_id AND ga.type = 3'// type 3 is product
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2';// type 2 is category
}
$query .= ' WHERE ' . implode( ' AND ', $wheres )
.' ORDER BY pc.ordering '.$order;
return $query;
}
private function getItemQuery( $itemId, $catId ) {
$app = JFactory::getApplication();
$params = $app->getParams();
$p['hide_products_out_of_stock'] = $params->get(
'hide_products_out_of_stock', 0);
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$categoryId = 0;
$category = $this->getCategory($itemId, $catId);
if (isset($category[0]->id)) {
$categoryId = $category[0]->id;
}
$skip = array();
$skip['access'] =
$params->get('sql_product_skip_access', 0);
$skip['group'] =
$params->get('sql_product_skip_group', 0);
//$skip['attributes'] =
$params->get('sql_product_skip_attributes', 0);
$skip['category_type'] =
$params->get('sql_product_skip_category_type', 0);
$skip['tax'] =
$params->get('sql_product_skip_tax', 0);
$wheres = array();
$wheres[] = " pc.category_id= ".(int) $categoryId;
$wheres[] = " pc.category_id= c.id";
$wheres[] = " i.published = 1";
$wheres[] = " c.published = 1";
$wheres[] = " i.id = " . (int) $itemId;
if (!$skip['category_type']) {
$wheres[] = " c.type IN (0,1)";// type: common, onlineshop,
pos
}
if (!$skip['access']) {
$wheres[] = " c.access IN (" . $userLevels . ")";
$wheres[] = " i.access IN (" . $userLevels . ")";
}
if (!$skip['group']) {
$wheres[] = " (ga.group_id IN (" . $userGroups . ") OR
ga.group_id IS NULL)";
$wheres[] = " (gc.group_id IN (" . $userGroups . ") OR
gc.group_id IS NULL)";
}
if ($this->getState('filter.language')) {
$wheres[] = ' i.language IN
('.$this->_db->Quote(JFactory::getLanguage()->getTag()).','.$this->_db->Quote('*').')';
$wheres[] = ' c.language IN
('.$this->_db->Quote(JFactory::getLanguage()->getTag()).','.$this->_db->Quote('*').')';
}
if ($p['hide_products_out_of_stock'] == 1) {
$wheres[] = " i.stock > 0";
}
// Views Plugin can load additional columns
$additionalColumns = array();
$pluginLayout = PluginHelper::importPlugin('pcv');
if ($pluginLayout) {
$pluginOptions = array();
$eventData = array();
Factory::getApplication()->triggerEvent('PCVonItemBeforeLoadColumns',
array('com_phocacart.items', &$pluginOptions, $eventData));
if (isset($pluginOptions['columns']) &&
$pluginOptions['columns'] != '') {
if (!empty($pluginOptions['columns'])) {
foreach ($pluginOptions['columns'] as $k => $v) {
$additionalColumns[] = PhocacartText::filterValue($v,
'alphanumeric3');
}
}
}
}
$baseColumns = array('i.id', 'i.title',
'i.alias', 'i.description', 'i.features',
'i.metatitle', 'i.metadesc', 'i.metakey',
'i.metadata', 'i.type', 'i.image',
'i.weight', 'i.height', 'i.width',
'i.length', 'i.min_multiple_quantity',
'i.min_quantity_calculation', 'i.volume',
'i.description', 'i.description_long',
'i.price', 'i.price_original',
'i.stockstatus_a_id', 'i.stockstatus_n_id',
'i.stock_calculation', 'i.min_quantity',
'i.min_multiple_quantity', 'i.stock',
'i.sales', 'i.featured', 'i.external_id',
'i.unit_amount', 'i.unit_unit', 'i.video',
'i.external_link', 'i.external_text',
'i.external_link2', 'i.external_text2',
'i.public_download_file', 'i.public_download_text',
'i.public_play_file', 'i.public_play_text',
'i.sku', 'i.upc', 'i.ean', 'i.jan',
'i.isbn', 'i.mpn', 'i.serial_number',
'i.points_needed', 'i.points_received',
'i.date', 'i.date_update', 'i.delivery_date',
'i.gift_types');
$col = array_merge($baseColumns, $additionalColumns);
$col = array_unique($col);
$columns = implode(',', $col) . ', pc.ordering, c.id AS
catid, c.title AS cattitle, c.alias AS catalias, m.id as manufacturerid,
m.title as manufacturertitle, m.link as manufacturerlink,';
if (!$skip['tax']) {
$columns .= ' t.id as taxid, t.tax_rate as taxrate,
t.calculation_type as taxcalculationtype, t.title as taxtitle,';
} else {
$columns .= ' NULL as taxid, NULL as taxrate, NULL as
taxcalculationtype, NULL as taxtitle,';
}
if (!$skip['group']) {
$columns .= ' MIN(ppg.price) as group_price,
MAX(pptg.points_received) as group_points_received';
} else {
$columns .= ' NULL as group_price, NULL as
group_points_received';
}
$groupsFull = implode(',', $col) .',pc.ordering, c.id,
c.title, c.alias, m.id, m.title, m.link';
if (!$skip['tax']) {
$groupsFull .= ', t.id, t.tax_rate, t.calculation_type,
t.title';
}
$groupsFast = 'i.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$query = ' SELECT '.$columns
.' FROM #__phocacart_products AS i'
.' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = i.id'
.' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id'
.' LEFT JOIN #__phocacart_manufacturers AS m ON m.id =
i.manufacturer_id';
if (!$skip['tax']) {
$query .= ' LEFT JOIN #__phocacart_taxes AS t ON t.id =
i.tax_id';
}
if (!$skip['group']) {
$query .= ' LEFT JOIN #__phocacart_item_groups AS ga ON i.id =
ga.item_id AND ga.type = 3';// type 3 is product
$query .= ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id =
gc.item_id AND gc.type = 2';// type 2 is category
// user is in more groups, select lowest price by best group
$query .= ' LEFT JOIN #__phocacart_product_price_groups AS ppg ON
i.id = ppg.product_id AND ppg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = i.id AND group_id IN
('.$userGroups.') AND type = 3)';
// user is in more groups, select highest points by best group
$query .= ' LEFT JOIN #__phocacart_product_point_groups AS pptg ON
i.id = pptg.product_id AND pptg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = i.id AND group_id IN
('.$userGroups.') AND type = 3)';
}
$query .= ' WHERE ' . implode( ' AND ', $wheres )
.' GROUP BY '.$groups
.' ORDER BY pc.ordering';
//echo nl2br(str_replace('#__', 'jos_', $query));
return $query;
}
function getCategory($itemId, $catId) {
if (empty($this->category)) {
$query = $this->getCategoryQuery( $itemId, $catId );
$this->category = $this->_getList( $query, 0, 1 );
}
return $this->category;
}
function getCategoryQuery($itemId, $catId) {
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$wheres = array();
//$app = JFactory::getApplication();
//$params = $app->getParams();
$wheres[] = " c.published = 1";
$wheres[] = " c.type IN (0,1)";// type: common, onlineshop,
pos
if ($this->getState('filter.language')) {
$lang = JFactory::getLanguage()->getTag();
//$wheres[] =
PhocacartUtilsSettings::getLangQuery('a.language', $lang);
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
if ((int)$catId > 0) {
$wheres[] = " c.id= ".(int)$catId;
} else {
$wheres[] = " a.id= ".(int)$itemId;
}
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " a.access IN (".$userLevels.")";
$wheres[] = " (ga.group_id IN (".$userGroups.") OR
ga.group_id IS NULL)";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
$query = " SELECT c.id, c.title, c.alias, c.description,
c.parent_id"
. " FROM #__phocacart_categories AS c"
. ' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.category_id = c.id'
. " LEFT JOIN #__phocacart_products AS a ON a.id =
pc.product_id"
. ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id = ga.item_id
AND ga.type = 3'// type 3 is product
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " ORDER BY c.ordering";
return $query;
}
public function hit($pk = 0) {
$input = JFactory::getApplication()->input;
$hitcount = $input->getInt('hitcount', 1);
if ($hitcount) {
$pk = (!empty($pk)) ? $pk : (int)
$this->getState('product.id');
$table = JTable::getInstance('PhocaCartItem',
'Table');
$table->load($pk);
$table->hit($pk);
}
return true;
}
}
?>
items.php000064400000056504151165414670006422 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\PluginHelper;
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelItems extends JModelLegacy
{
protected $item = null;
protected $item_ordering = null;
protected $layout_type = null;
protected $category = null;
protected $subcategories = null;
protected $category_ordering = null;
protected $pagination = null;
protected $total = null;
protected $ordering = null;
protected $items_layout_plugin = '';
public function __construct() {
parent::__construct();
$app = Factory::getApplication();
$config = Factory::getConfig();
$paramsC = $app->getParams();
$item_pagination = $paramsC->get( 'item_pagination_default',
'20' );
$item_ordering = $paramsC->get( 'item_ordering', 1 );
$layout_type = $paramsC->get( 'layout_type',
'grid' );
// Items View Menu link parameters
$items_view_id_cats = $paramsC->get( 'items_view_id_cats',
array() );
$this->items_layout_plugin = $paramsC->get(
'items_layout_plugin', '' );
$manufacturer_alias = $paramsC->get( 'manufacturer_alias',
'manufacturer');
$manufacturer_alias = $manufacturer_alias != '' ?
trim(PhocacartText::filterValue($manufacturer_alias,
'alphanumeric')) : 'manufacturer';
$limit =
PhocacartPagination::getMaximumLimit($app->getUserStateFromRequest('com_phocacart.limit',
'limit', $item_pagination, 'int'));
$this->setState('limit', $limit);
$this->setState('limitstart',
$app->input->get('limitstart', 0, 'int'));
$this->setState('limitstart',
($this->getState('limit') != 0 ?
(floor($this->getState('limitstart') /
$this->getState('limit')) *
$this->getState('limit')) : 0));
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('filter_order',
$app->input->get('filter_order', 'ordering'));
$this->setState('filter_order_dir',
$app->input->get('filter_order_Dir', 'ASC'));
$this->setState('itemordering',
$app->getUserStateFromRequest('com_phocacart.itemordering',
'itemordering', $item_ordering, 'int'));
$this->setState('layouttype',
$app->getUserStateFromRequest('com_phocacart.layouttype',
'layouttype', $layout_type, 'string'));
// =FILTER=
$this->setState('tag',
$app->input->get('tag', '',
'string'));
$this->setState('label',
$app->input->get('label', '',
'string'));
$manufacturerParameter = '';
$this->setState('manufacturer',
$app->input->get($manufacturer_alias, '',
'string'));
$this->setState('price_from',
$app->input->get('price_from', '',
'float'));
$this->setState('price_to',
$app->input->get('price_to', '',
'float'));
// CATEGORIES
// 1) there can be set one category per ID
// 2) there can be set more categories per c parameter
// 3) there can be set more categories by menu link parameters. If menu
link parameter is used, then 2) is deactivated
// because if somebody wants to force displaying only some categories,
another cannot be displayed e.g. per URL parameters
// E.g. we want to display only category 1 and 3 in items view and
user even set c=1,2,3 in URL - so the 2 will be just ignored
// 1)
$this->setState('id', $app->input->get('id',
'', 'int')); // Category ID (Active Category)
// 2) 3)
if (!empty($items_view_id_cats)) {
$this->setState('c', implode(',',
$items_view_id_cats));
} else {
$this->setState('c', $app->input->get('c',
'', 'string')); // Category More (All Categories)
}
$this->setState('a', $app->input->get('a',
'', 'array')); // Attributes
$this->setState('s', $app->input->get('s',
'', 'array')); // Specifications
$parameters = PhocacartParameter::getAllParameters();
$this->setState('parameter', $parameters);
// =SEARCH=
$this->setState('search',
$app->input->get('search', '',
'string'));
}
public function getLayoutType() {
$layoutType = $this->getState('layouttype');
$layoutType = PhocacartRenderFront::getLayoutType($layoutType);
return $layoutType;
}
public function getPagination() {
if (empty($this->pagination)) {
jimport('joomla.html.pagination');
$this->pagination = new PhocacartPagination( $this->getTotal(),
$this->getState('limitstart'),
$this->getState('limit') );
}
return $this->pagination;
}
function getOrdering() {
if(empty($this->ordering)) {
$this->ordering =
PhocacartOrdering::renderOrderingFront($this->getState('itemordering'),
0);
}
return $this->ordering;
}
public function getTotal() {
if (empty($this->total)) {
$query = $this->getItemListQuery(1);
$this->total = $this->_getListCount($query);
}
return $this->total;
}
public function getItemList() {
if (empty($this->item)) {
$query = $this->getItemListQuery( );
$this->item = $this->_getList( $query
,$this->getState('limitstart'),
$this->getState('limit'));
}
return $this->item;
}
public function getCategory($categoryId) {
if (empty($this->category)) {
$query = $this->getCategoriesQuery( $categoryId, FALSE );
$this->category = $this->_getList( $query, 0, 1 );
}
return $this->category;
}
public function getSubcategories($categoryId) {
if (empty($this->subcategories)) {
$query = $this->getCategoriesQuery( $categoryId, TRUE );
$this->subcategories = $this->_getList( $query );
}
return $this->subcategories;
}
protected function getItemListQuery($count = 0) {
$app = Factory::getApplication();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$params = $app->getParams();
$wheres = array();
$lefts = array();
$skip = array();
$skip['access'] =
$params->get('sql_products_skip_access', 0);
$skip['group'] =
$params->get('sql_products_skip_group', 0);
$skip['attributes'] =
$params->get('sql_products_skip_attributes', 0);
$skip['category_type'] =
$params->get('sql_products_skip_category_type', 0);
$skip['tax'] =
$params->get('sql_products_skip_tax', 0);
$p = array();
$p['hide_products_out_of_stock'] = $params->get(
'hide_products_out_of_stock', 0);
$p['switch_image_category_items'] = $params->get(
'switch_image_category_items', 0 );
$p['join_tag_label_filter'] = $params->get(
'join_tag_label_filter', 0 );
$p['search_matching_option'] = $params->get(
'search_matching_option', 'any' );
$p['search_deep'] = $params->get(
'search_deep', 0);
$p['sql_search_skip_id'] = $params->get(
'sql_search_skip_id', 1 );
$p['sql_search_skip_id_specific_type'] = 1;// POS or Online
Shop (Online Shop)
if ($p['sql_search_skip_id'] != 1 &&
$p['sql_search_skip_id'] != 2){
$p['sql_search_skip_id_specific_type'] = 0;
}
$wheres = array();
$wheres[] = ' a.published = 1';
$wheres[] = ' c.published = 1';
if (!$skip['category_type']) {
$wheres[] = " c.type IN (0,1)";// type: common,
onlineshop, pos
}
if ($this->getState('filter.language')) {
$lang = Factory::getLanguage()->getTag();
$wheres[] =
PhocacartUtilsSettings::getLangQuery('a.language', $lang);
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
$itemOrdering = $this->getItemOrdering();
if (!$skip['access']) {
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " a.access IN (".$userLevels.")";
}
if (!$skip['group']) {
$wheres[] = " (ga.group_id IN (".$userGroups.") OR
ga.group_id IS NULL)";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
}
if ($p['hide_products_out_of_stock'] == 1) {
$wheres[] = " a.stock > 0";
}
// =FILTER=
// -TAG- -LABEL-
if ($p['join_tag_label_filter'] == 1) {
// -TAG-
$wheresTL = array();
if ($this->getState('tag')) {
$s = PhocacartSearch::getSqlParts('int', 'tag',
$this->getState('tag'));
$wheresTL[] = $s['where'];
$lefts[] = $s['left'];
}
// -LABEL-
if ($this->getState('label')) {
$s = PhocacartSearch::getSqlParts('int', 'label',
$this->getState('label'));
$wheresTL[] = $s['where'];
$lefts[] = $s['left'];
}
if ($this->getState('tag') ||
$this->getState('label')) {
$startP = '';
$endP = '';
if (count($wheresTL) > 1) {
$startP = '(';
$endP = ')';
}
$wheres[] = $startP . implode(' OR ', $wheresTL) . $endP;
}
} else {
// -TAG-
if ($this->getState('tag')) {
$s = PhocacartSearch::getSqlParts('int', 'tag',
$this->getState('tag'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -LABEL-
if ($this->getState('label')) {
$s = PhocacartSearch::getSqlParts('int', 'label',
$this->getState('label'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
}
// -PARAMETER
// Custom parameters set by user in administrator
// All custom parameters are stored in one table so they are unique
// So we can use one left for all parameters
/*if ($this->getState('parameter')) {
$parameterValues = array();
foreach ($this->getState('parameter') as $k => $v) {
$alias = PhocacartText::filterValue($v->alias, 'url');
$parameter = $app->input->get($alias, '',
'string');
if($parameter != '') {
$parameterValues[] = $parameter;
}
}
if (!empty($parameterValues)) {
$parameterValuesString = implode(',',
$parameterValues);//Join all custom parameters together because of SQL
query - all should be in one IN(): AND pr.parameter_id IN (1,2,3)
if ($parameterValuesString != '') {
$s = PhocacartSearch::getSqlParts('int',
'parameter', $parameterValuesString);
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
}
}*/
if ($this->getState('parameter')) {
//$leftOnce = 0;
foreach ($this->getState('parameter') as $k => $v) {
$alias = trim(PhocacartText::filterValue($v->alias,
'alphanumeric'));
$parameter = $app->input->get($alias, '',
'string');
if($parameter != '') {
$s = PhocacartSearch::getSqlParts('int',
'parameter', $parameter, array(), $v->id);
$wheres[] = $s['where'];// There must be AND between custom
parameters
//if ($leftOnce < 1) {
$lefts[] = $s['left'];
//$leftOnce = 1;
//}
}
}
}
// -MANUFACTURER-
if ($this->getState('manufacturer')) {
$s = PhocacartSearch::getSqlParts('int',
'manufacturer', $this->getState('manufacturer'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -PRICE-
if ($this->getState('price_from')) {
$s = PhocacartSearch::getSqlParts('int',
'price_from', $this->getState('price_from'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
if ($this->getState('price_to')) {
$s = PhocacartSearch::getSqlParts('int', 'price_to',
$this->getState('price_to'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -CATEGORY-
if ($this->getState('id')) {
$s = PhocacartSearch::getSqlParts('int', 'id',
$this->getState('id'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -CATEGORY MORE-
if ($this->getState('c')) {
$s = PhocacartSearch::getSqlParts('int', 'c',
$this->getState('c'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -ATTRIBUTES-
if ($this->getState('a')) {
$s = PhocacartSearch::getSqlParts('array', 'a',
$this->getState('a'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -SPECIFICATIONS-
if ($this->getState('s')) {
$s = PhocacartSearch::getSqlParts('array', 's',
$this->getState('s'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// =SEARCH=
if ($this->getState('search')) {
$s = PhocacartSearch::getSqlParts('string',
'search', $this->getState('search'), $p);
$wheres[] = '('.$s['where'].')';
$lefts[] = $s['left'];
// Hit only one time
if ($count == 0) {
PhocacartStatisticsHits::searchHit($this->getState('search'));
}
}
// Additional Images
$leftImages = '';
$selImages = '';
if ($p['switch_image_category_items'] == 1) {
$leftImages = ' LEFT JOIN #__phocacart_product_images AS im ON a.id
= im.product_id';
$selImages = ' GROUP_CONCAT(im.image) as additional_image,';
}
// Items Layout Plugin can change ordering
// Items Layout Plugin can load additional columns
$additionalColumns = array();
if ($this->items_layout_plugin != '') {
$this->items_layout_plugin =
PhocacartText::filterValue($this->items_layout_plugin,
'alphanumeric2');
$pluginLayout = PluginHelper::importPlugin('pcl',
$this->items_layout_plugin);
if ($pluginLayout) {
$pluginOptions = array();
$eventData = array();
$eventData['pluginname'] = $this->items_layout_plugin;
Factory::getApplication()->triggerEvent('PCLonItemsGetOptions',
array('com_phocacart.items', &$pluginOptions, $eventData));
if (isset($pluginOptions['ordering']) &&
$pluginOptions['ordering'] != '') {
$pluginOrdering =
PhocacartText::filterValue($pluginOptions['ordering'],
'alphanumeric5');
if ($pluginOrdering != '') {
$itemOrdering = $pluginOrdering . ',' . $itemOrdering;
}
}
if (isset($pluginOptions['columns']) &&
$pluginOptions['columns'] != '') {
if (!empty($pluginOptions['columns'])) {
foreach ($pluginOptions['columns'] as $k => $v) {
$additionalColumns[] = PhocacartText::filterValue($v,
'alphanumeric3');
}
}
}
}
}
// Views Plugin can load additional columns
$pluginLayout = PluginHelper::importPlugin('pcv');
if ($pluginLayout) {
$pluginOptions = array();
$eventData = array();
Factory::getApplication()->triggerEvent('PCVonItemsBeforeLoadColumns',
array('com_phocacart.items', &$pluginOptions, $eventData));
if (isset($pluginOptions['columns']) &&
$pluginOptions['columns'] != '') {
if (!empty($pluginOptions['columns'])) {
foreach ($pluginOptions['columns'] as $k => $v) {
$additionalColumns[] = PhocacartText::filterValue($v,
'alphanumeric3');
}
}
}
}
$baseColumns = array('a.id', 'a.title',
'a.image', 'a.alias', 'a.unit_amount',
'a.unit_unit', 'a.description',
'a.sku', 'a.ean', 'a.upc',
'a.type', 'a.points_received',
'a.price_original',
'a.stock', 'a.stock_calculation',
'a.min_quantity', 'a.min_multiple_quantity',
'a.stockstatus_a_id',
'a.stockstatus_n_id','a.date', 'a.sales',
'a.featured',
'a.external_id', 'a.unit_amount',
'a.unit_unit', 'a.external_link',
'a.external_text', 'a.price',
'a.gift_types');
$col = array_merge($baseColumns, $additionalColumns);
$col = array_unique($col);
// Remove empty values:
$wheres = array_filter($wheres);
$lefts = array_filter($lefts);
if ($count == 1) {
//$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
a.catid';
$lefts[] = ' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = a.id';
$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id';
$lefts[] = ' LEFT JOIN #__phocacart_manufacturers AS m ON m.id =
a.manufacturer_id';
if ($p['sql_search_skip_id_specific_type'] == 0){
$lefts[] = ' LEFT JOIN #__phocacart_product_stock AS ps ON a.id =
ps.product_id';// search sku ean in advanced stock management
}
if (!$skip['attributes']) {
// see below for explanation
// LEFT JOIN (SELECT id, product_id, MAX(required) AS required FROM
jos_phocacart_attributes GROUP BY product_id) AS at ON a.id = at.product_id
AND at.id > 0
$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0 AND at.required = 1';
}
if (!$skip['group']) {
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id =
ga.item_id AND ga.type = 3';// type 3 is product
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id =
gc.item_id AND gc.type = 2';// type 2 is category
}
//$query = ' SELECT COUNT(DISTINCT a.id) AS count'; // 2.85ms
0.12mb
$q = ' SELECT a.id' // 2.42ms 0.12mb
. ' FROM #__phocacart_products AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres )
. ' GROUP BY a.id';
} else {
//$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
a.catid';
$lefts[] = ' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = a.id';
$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id';
$lefts[] = ' LEFT JOIN #__phocacart_reviews AS r ON a.id =
r.product_id AND r.id > 0';
$lefts[] = ' LEFT JOIN #__phocacart_manufacturers AS m ON m.id =
a.manufacturer_id';
if ($p['sql_search_skip_id_specific_type'] == 0){
$lefts[] = ' LEFT JOIN #__phocacart_product_stock AS ps ON a.id =
ps.product_id';// search sku ean in advanced stock management
}
if (!$skip['tax']) {
$lefts[] = ' LEFT JOIN #__phocacart_taxes AS t ON t.id =
a.tax_id';
}
if (!$skip['attributes']) {
// We need to get information if at least one of the attributes of
selected product is required
// 1) Select more rows - one product is displayed e.g. in two rows
//$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0';
// 2) right solution as it select only the maximal value and if maximal
value is 1 then one of product attribute is required
// LEFT JOIN (SELECT id, product_id, MAX(required) AS required FROM
jos_phocacart_attributes GROUP BY product_id) AS at ON a.id = at.product_id
AND at.id > 0
// 3) faster version of 2)
$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0 AND at.required = 1';
}
if (!$skip['group']) {
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id =
ga.item_id AND ga.type = 3';// type 3 is product
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id =
gc.item_id AND gc.type = 2';// type 2 is category
// user is in more groups, select lowest price by best group
$lefts[] = ' LEFT JOIN #__phocacart_product_price_groups AS ppg ON
a.id = ppg.product_id AND ppg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = a.id AND group_id IN (' .
$userGroups . ') AND type = 3)';
// user is in more groups, select highest points by best group
$lefts[] = ' LEFT JOIN #__phocacart_product_point_groups AS pptg
ON a.id = pptg.product_id AND pptg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = a.id AND group_id IN (' .
$userGroups . ') AND type = 3)';
}
$columns = implode(',', $col) . ','
.' GROUP_CONCAT(DISTINCT c.id) AS catid, GROUP_CONCAT(DISTINCT
c.title) AS cattitle,'
.' GROUP_CONCAT(DISTINCT c.alias) AS catalias,';
if (!$skip['tax']) {
$columns .= ' t.id as taxid, t.tax_rate as taxrate,
t.calculation_type as taxcalculationtype, t.title as taxtitle,';
} else {
$columns .= ' NULL as taxid, NULL as taxrate, NULL as
taxcalculationtype, NULL as taxtitle,';
}
if (!$skip['attributes']) {
$columns .= 'at.required AS attribute_required,
';
}
if (!$skip['group']) {
$columns .= ' MIN(ppg.price) as group_price,
MAX(pptg.points_received) as group_points_received,';
} else {
$columns .= ' NULL as group_price, NULL as
group_points_received,';
}
$columns .= ' m.id as manufacturerid, m.title as manufacturertitle,
m.alias as manufactureralias,'
. $selImages
.' AVG(r.rating) AS rating';
$groupsFull = implode(',', $col) ;
if (!$skip['tax']) {
$groupsFull .= ', t.id, t.tax_rate,
t.calculation_type, t.title';
}
if (!$skip['attributes']) {
$groupsFull .= ', at.required';
}
$groupsFast = 'a.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$q = ' SELECT '.$columns
. ' FROM #__phocacart_products AS a'
. implode( ' ', $lefts )
. $leftImages
. ' WHERE ' . implode( ' AND ', $wheres )
. ' GROUP BY '.$groups
. ' ORDER BY '.$itemOrdering;
}
//echo "<br><br>" .
nl2br(str_replace('#__', 'jos_', $q));
return $q;
}
protected function getCategoriesQuery( $categoryId, $subcategories = FALSE
) {
$wheres = array();
$app = Factory::getApplication();
$params = $app->getParams();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
// Get the current category or get parent categories of the current
category
if ($subcategories) {
$wheres[] = " c.parent_id = ".(int)$categoryId;
$categoryOrdering = $this->getCategoryOrdering();
} else {
$wheres[] = " c.id= ".(int)$categoryId;
}
$wheres[] = " c.published = 1";
$wheres[] = " c.type IN (0,1)";// type: common, onlineshop,
pos
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
if ($this->getState('filter.language')) {
$lang = Factory::getLanguage()->getTag();
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
if ($subcategories) {
$columns = 'c.id, c.title, c.alias, COUNT(c.id) AS numdoc';
$groupsFull = 'c.id, c.title, c.alias';
$groupsFast = 'c.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$query = "SELECT ".$columns
. " FROM #__phocacart_categories AS c"
. " LEFT JOIN #__phocacart_products AS a ON a.catid = c.id AND
a.published = 1"
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " GROUP BY ".$groups
. " ORDER BY ".$categoryOrdering;
} else {
$query = " SELECT c.id, c.title, c.alias, c.description,
c.metatitle, c.metakey, c.metadesc, c.metadata, cc.title as parenttitle,
c.parent_id as parentid, cc.alias as parentalias"
. " FROM #__phocacart_categories AS c"
. " LEFT JOIN #__phocacart_categories AS cc ON cc.id =
c.parent_id"
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " ORDER BY c.ordering";
}
return $query;
}
protected function getItemOrdering() {
if (empty($this->item_ordering)) {
$app = Factory::getApplication();
$params = $app->getParams();
//$ordering = $params->get( 'item_ordering', 1 );
$ordering = $this->getState('itemordering');
$this->item_ordering =
PhocacartOrdering::getOrderingText($ordering);
}
return $this->item_ordering;
}
protected function getCategoryOrdering() {
if (empty($this->category_ordering)) {
$app = Factory::getApplication();
$params = $app->getParams();
$ordering = $params->get( 'category_ordering', 1 );
$this->category_ordering =
PhocacartOrdering::getOrderingText($ordering, 1);
}
return $this->category_ordering;
}
}
?>
orders.php000064400000007445151165414670006577 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelOrders extends JModelLegacy
{
protected $orders = null;
protected $orders_ordering = null;
protected $pagination = null;
protected $total = null;
public function __construct() {
parent::__construct();
$app = JFactory::getApplication();
$config = JFactory::getConfig();
//$paramsC = PhocacartUtils::getComponentParameters() ;
$paramsC = $app->getParams();
$defaultP = $paramsC->get( 'default_pagination',
'20' );
$this->setState('limit',
$app->getUserStateFromRequest('com_phocacart.orders.limit',
'limit', $defaultP, 'int'));
$this->setState('limitstart',
$app->input->get('limitstart', 0, 'int'));
$this->setState('limitstart',
($this->getState('limit') != 0 ?
(floor($this->getState('limitstart') /
$this->getState('limit')) *
$this->getState('limit')) : 0));
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('filter_order',
JFactory::getApplication()->input->get('filter_order',
'ordering'));
$this->setState('filter_order_dir',
JFactory::getApplication()->input->get('filter_order_Dir',
'ASC'));
}
public function getPagination($userId) {
if (empty($this->pagination)) {
jimport('joomla.html.pagination');
$this->pagination = new PhocacartPagination(
$this->getTotal($userId), $this->getState('limitstart'),
$this->getState('limit') );
}
return $this->pagination;
}
public function getTotal() {
if (empty($this->total)) {
$query = $this->getOrderListQuery();
$this->total = $this->_getListCount($query);
}
return $this->total;
}
public function getOrderList() {
if (empty($this->orders)) {
$query = $this->getOrderListQuery();
$this->orders = $this->_getList( $query
,$this->getState('limitstart'),
$this->getState('limit'));
}
return $this->orders;
}
protected function getOrderListQuery() {
$app = JFactory::getApplication();
$params = $app->getParams();
$u = PhocacartUser::getUser();
$token = $app->input->get('o', '',
'string');
$orderGuestAccess = $params->get( 'order_guest_access', 0
);
if ($orderGuestAccess == 0) {
$token = '';
}
$wheres = array();
$wheres[] = ' o.published = 1';
if ($token != '') {
$wheres[] = ' o.order_token =
'.$this->_db->quote($token);
} else {
$wheres[] = ' o.user_id = '.(int)$u->id;
}
$wheres[] = ' t.type =
'.$this->_db->quote('brutto');
$ordering = $this->getOrderOrdering();
$query = ' SELECT o.*,'
.' os.title AS status_title,'
.' t.amount AS total_amount,'
.' s.id AS shippingid, s.title AS shippingtitle, s.tracking_link as
shippingtrackinglink, s.tracking_description as
shippingtrackingdescription, os.orders_view_display as
ordersviewdisplay'
.' FROM #__phocacart_orders AS o'
.' LEFT JOIN #__phocacart_order_statuses AS os ON os.id =
o.status_id'
.' LEFT JOIN #__phocacart_order_total AS t ON o.id =
t.order_id'
.' LEFT JOIN #__phocacart_shipping_methods AS s ON s.id =
o.shipping_id'
.' WHERE ' . implode( ' AND ', $wheres )
.' ORDER BY '.$ordering;
return $query;
}
protected function getOrderOrdering() {
if (empty($this->orders_ordering)) {
$app = JFactory::getApplication();
$params = $app->getParams();
$ordering = $params->get( 'order_ordering', 8 );
$this->orders_ordering =
PhocacartOrdering::getOrderingText($ordering, 2);
}
return $this->orders_ordering;
}
}
?>
pos.php000064400000072347151165414670006105 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
use Joomla\Utilities\ArrayHelper;
class PhocaCartModelPos extends JModelLegacy
{
protected $item = null;
protected $item_ordering = null;
protected $layout_type = null;
protected $category = null;
protected $subcategories = null;
protected $category_ordering = null;
protected $pagination = null;
protected $total = null;
protected $ordering = null;
public function __construct() {
parent::__construct();
$app = JFactory::getApplication();
$config = JFactory::getConfig();
$paramsC = $app->getParams();
$item_pagination = $paramsC->get( 'pos_pagination_default',
24 );
$item_ordering = $paramsC->get( 'pos_ordering', 1 );
$manufacturer_alias = $paramsC->get( 'manufacturer_alias',
'manufacturer');
$manufacturer_alias = $manufacturer_alias != '' ?
trim(PhocacartText::filterValue($manufacturer_alias,
'alphanumeric')) : 'manufacturer';
$this->setState('page',
$app->input->get('page',
'main.content.products'));
//$limit =
PhocacartPagination::getMaximumLimit($app->getUserStateFromRequest('com_phocacart.limit',
'limit', $item_pagination, 'int'), 1);
$toDay = date('Y-m-d');
$this->setState('date',
$app->input->get('date', $toDay, 'string'));
$limitId =
'com_phocacart.'.$this->getState('page').'.limit';
$limitStartId =
'com_phocacart.'.$this->getState('page').'.limitstart';
$orderingId =
'com_phocacart.'.$this->getState('page').'.itemordering';
switch($this->getState('page')){
case 'section':
$limit = 0;
$limitStart = 0;
break;
default:
//$limitStart = $app->getUserStateFromRequest($limitStartId,
'limit',0, 'int');
$limit =
PhocacartPagination::getMaximumLimit($app->getUserStateFromRequest($limitId,
'limit', $item_pagination, 'int'), 1);
break;
}
$this->setState('limit', $limit);
$this->setState('limitstart',
$app->input->get('limitstart', 0, 'int'));
$this->setState('limitstart',
($this->getState('limit') != 0 ?
(floor($this->getState('limitstart') /
$this->getState('limit')) *
$this->getState('limit')) : 0));
$this->setState('filter.language',$app->getLanguageFilter());
$this->setState('filter_order',
$app->input->get('filter_order', 'ordering'));
$this->setState('filter_order_dir',
$app->input->get('filter_order_Dir', 'ASC'));
$this->setState('itemordering',
$app->getUserStateFromRequest($orderingId, 'itemordering',
$item_ordering, 'int'));
// =FILTER=
$this->setState('tag',
$app->input->get('tag', '',
'string'));
$this->setState('label',
$app->input->get('label', '',
'string'));
$this->setState('manufacturer',
$app->input->get($manufacturer_alias, '',
'string'));
$this->setState('price_from',
$app->input->get('price_from', '',
'float'));
$this->setState('price_to',
$app->input->get('price_to', '',
'float'));
// Javascript update url has problems with "c", so changed to
"category"
//$this->setState('c', $app->input->get('c',
'', 'string')); // Category More (All Categories)
$this->setState('c',
$app->input->get('category', '',
'string')); // Category More (All Categories)
//$this->setState('id',
$app->input->get('id', '', 'int')); //
Category ID (Active Category) ID IS VARIABLE - different for different
pages
$this->setState('a', $app->input->get('a',
'', 'array')); // Attributes
$this->setState('s', $app->input->get('s',
'', 'array')); // Specifications
// =SEARCH=
$this->setState('search',
$app->input->get('search', '',
'string'));
}
public function getPagination() {
if (empty($this->pagination)) {
jimport('joomla.html.pagination');
$this->pagination = new PhocacartPagination( $this->getTotal(),
$this->getState('limitstart'),
$this->getState('limit') );
}
return $this->pagination;
}
function getOrdering() {
if(empty($this->ordering)) {
switch($this->getState('page')){
case 'section':
$this->ordering =
PhocacartOrdering::renderOrderingFront($this->getState('itemordering'),
8);
break;
case 'main.content.customers':
$this->ordering =
PhocacartOrdering::renderOrderingFront($this->getState('itemordering'),
7);
break;
case 'main.content.orders':
$this->ordering =
PhocacartOrdering::renderOrderingFront($this->getState('itemordering'),
11);
break;
case 'main.content.products':
default:
$this->ordering =
PhocacartOrdering::renderOrderingFront($this->getState('itemordering'),
0);
break;
}
}
return $this->ordering;
}
public function getTotal() {
if (empty($this->total)) {
switch($this->getState('page')){
case 'section':
$query = $this->getItemListQueryUnits(1);
break;
case 'main.content.customers':
$query = $this->getItemListQueryCustomers(1);
break;
case 'main.content.orders':
$query = $this->getItemListQueryOrders(1);
break;
case 'main.content.products':
default:
$query = $this->getItemListQuery(1);
break;
}
$this->total = $this->_getListCount($query);
}
return $this->total;
}
public function getItemList($userId = 0, $vendorId = 0, $ticketId = 0,
$unitId = 0, $sectionId = 0) {
// Section and Unit can be reset if not exists
$this->setState('ticketid', $ticketId);
$this->setState('sectionid', $sectionId);
$this->setState('unitid', $unitId);
$this->setState('vendorid', $vendorId);
$this->setState('userid', $userId);
if (empty($this->item)) {
switch($this->getState('page')){
case 'section':
$query = $this->getItemListQueryUnits();
break;
case 'main.content.customers':
$query = $this->getItemListQueryCustomers();
break;
case 'main.content.orders':
$query = $this->getItemListQueryOrders();
break;
case 'main.content.products':
default:
$query = $this->getItemListQuery();
break;
}
$this->item = $this->_getList( $query
,$this->getState('limitstart'),
$this->getState('limit'));
}
return $this->item;
}
public function getCategory($categoryId) {
if (empty($this->category)) {
$query = $this->getCategoriesQuery( $categoryId, FALSE );
$this->category = $this->_getList( $query, 0, 1 );
}
return $this->category;
}
public function getSubcategories($categoryId) {
if (empty($this->subcategories)) {
$query = $this->getCategoriesQuery( $categoryId, TRUE );
$this->subcategories = $this->_getList( $query );
}
return $this->subcategories;
}
protected function getItemListQuery($count = 0) {
$app = JFactory::getApplication();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$params = $app->getParams();
$wheres = array();
$lefts = array();
// POS FILTER
$p = array();
$p['pos_categories'] = $params->get(
'pos_categories', array(-1) );
$p['sql_search_skip_id'] = $params->get(
'sql_search_skip_id', 1 );
$p['search_deep'] = $params->get( 'search_deep',
0 );
$p['sql_search_skip_id_specific_type'] = 1;// POS or Online
Shop (POS)
if ($p['sql_search_skip_id'] != 1 &&
$p['sql_search_skip_id'] != 3){
$p['sql_search_skip_id_specific_type'] = 0;
}
if (in_array(-1, $p['pos_categories'])) {
// All categories selected
} else if (in_array(0, $p['pos_categories'])) {
// No category selected - dummy select to not break framework rules
$this->setState('limitstart', 0);
$this->setState('limit', 0);
return 'SELECT id FROM #__phocacart_products WHERE 1 <>
1;';
} else {
// Only some selected
$wheres[] = ' c.id IN ('.implode(',',
$p['pos_categories']).')';
}
//$p['switch_image_category_items'] = $params->get(
'switch_image_category_items', 0 );
$wheres[] = ' a.published = 1';
$wheres[] = ' c.published = 1';
$wheres[] = ' c.type IN (0,2)';// default categories or pos
categories only
if ($this->getState('filter.language')) {
$lang = JFactory::getLanguage()->getTag();
$wheres[] =
PhocacartUtilsSettings::getLangQuery('a.language', $lang);
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
$itemOrdering = $this->getItemOrdering();
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " a.access IN (".$userLevels.")";
$wheres[] = " (ga.group_id IN (".$userGroups.") OR
ga.group_id IS NULL)";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
// =FILTER=
// -TAG-
if ($this->getState('tag')) {
$s = PhocacartSearch::getSqlParts('int', 'tag',
$this->getState('tag'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -TAG-
if ($this->getState('label')) {
$s = PhocacartSearch::getSqlParts('int',
'label', $this->getState('label'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -MANUFACTURER-
if ($this->getState('manufacturer')) {
$s = PhocacartSearch::getSqlParts('int',
'manufacturer', $this->getState('manufacturer'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -PRICE-
if ($this->getState('price_from')) {
$s = PhocacartSearch::getSqlParts('int',
'price_from', $this->getState('price_from'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
if ($this->getState('price_to')) {
$s = PhocacartSearch::getSqlParts('int', 'price_to',
$this->getState('price_to'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -CATEGORY-
/* if ($this->getState('id')) {
$s = PhocacartSearch::getSqlParts('int', 'id',
$this->getState('id'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}*/
// -CATEGORY MORE-
if ($this->getState('c')) {
$s = PhocacartSearch::getSqlParts('int', 'c',
$this->getState('c'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -ATTRIBUTES-
if ($this->getState('a')) {
$s = PhocacartSearch::getSqlParts('array', 'a',
$this->getState('a'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// -SPECIFICATIONS-
if ($this->getState('s')) {
$s = PhocacartSearch::getSqlParts('array', 's',
$this->getState('s'));
$wheres[] = $s['where'];
$lefts[] = $s['left'];
}
// =SEARCH=
if ($this->getState('search')) {
$s = PhocacartSearch::getSqlParts('string',
'search', $this->getState('search'), $p);
$wheres[] = '('.$s['where'].')';
$lefts[] = $s['left'];
// Hit only one time
if ($count == 0) {
PhocacartStatisticsHits::searchHit($this->getState('search'));
}
}
// Additional Images
$leftImages = '';
$selImages = '';
/*if ($p['switch_image_category_items'] == 1) {
$leftImages = ' LEFT JOIN #__phocacart_product_images AS im ON a.id
= im.product_id';
$selImages = ' GROUP_CONCAT(im.image) as additional_image,';
}*/
// Remove empty values:
$wheres = array_filter($wheres);
$lefts = array_filter($lefts);
if ($count == 1) {
//$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
a.catid';
$lefts[] = ' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = a.id';
$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id';
if ($p['sql_search_skip_id_specific_type'] == 0){
$lefts[] = ' LEFT JOIN #__phocacart_product_stock AS ps ON a.id =
ps.product_id';// search sku ean in advanced stock management
}
$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0 AND at.required = 1';
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id =
ga.item_id AND ga.type = 3';// type 3 is product
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id =
gc.item_id AND gc.type = 2';// type 2 is category
//$query = ' SELECT COUNT(DISTINCT a.id) AS count'; // 2.85ms
0.12mb
$q = ' SELECT a.id' // 2.42ms 0.12mb
. ' FROM #__phocacart_products AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres )
. ' GROUP BY a.id';
} else {
//$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
a.catid';
$lefts[] = ' LEFT JOIN #__phocacart_product_categories AS pc ON
pc.product_id = a.id';
$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
pc.category_id';
if ($p['sql_search_skip_id_specific_type'] == 0){
$lefts[] = ' LEFT JOIN #__phocacart_product_stock AS ps ON a.id =
ps.product_id';// search sku ean in advanced stock management
}
$lefts[] = ' LEFT JOIN #__phocacart_taxes AS t ON t.id =
a.tax_id';
$lefts[] = ' LEFT JOIN #__phocacart_reviews AS r ON a.id =
r.product_id AND r.id > 0';
// We need to get information if at least one of the attributes of
selected product is required
// 1) Select more rows - one product is displayed e.g. in two rows
//$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0';
// 2) right solution as it select only the maximal value and if maximal
value is 1 then one of product attribute is required
// LEFT JOIN (SELECT id, product_id, MAX(required) AS required FROM
jos_phocacart_attributes GROUP BY product_id) AS at ON a.id = at.product_id
AND at.id > 0
// 3) faster version of 2)
$lefts[] = ' LEFT JOIN #__phocacart_attributes AS at ON a.id =
at.product_id AND at.id > 0 AND at.required = 1';
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS ga ON a.id =
ga.item_id AND ga.type = 3';// type 3 is product
$lefts[] = ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id =
gc.item_id AND gc.type = 2';// type 2 is category
// user is in more groups, select lowest price by best group
$lefts[] = ' LEFT JOIN #__phocacart_product_price_groups AS ppg ON
a.id = ppg.product_id AND ppg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = a.id AND group_id IN
('.$userGroups.') AND type = 3)';
// user is in more groups, select highest points by best group
$lefts[] = ' LEFT JOIN #__phocacart_product_point_groups AS pptg ON
a.id = pptg.product_id AND pptg.group_id IN (SELECT group_id FROM
#__phocacart_item_groups WHERE item_id = a.id AND group_id IN
('.$userGroups.') AND type = 3)';
$columns = 'a.id, a.title, a.image, a.alias, a.unit_amount,
a.unit_unit, a.description, a.type,'
.' GROUP_CONCAT(DISTINCT c.id) AS catid, GROUP_CONCAT(DISTINCT
c.title) AS cattitle,'
.' GROUP_CONCAT(DISTINCT c.alias) AS catalias, a.price,
MIN(ppg.price) as group_price,'
.' MAX(pptg.points_received) as group_points_received,
a.points_received, a.price_original,'
.' t.id as taxid, t.tax_rate as taxrate, t.calculation_type as
taxcalculationtype, t.title as taxtitle,'
.' a.stock, a.stock_calculation, a.min_quantity,
a.min_multiple_quantity, a.stockstatus_a_id, a.stockstatus_n_id,'
.' a.date, a.sales, a.featured, a.external_id, a.unit_amount,
a.unit_unit, a.external_link, a.external_text,'. $selImages
.' AVG(r.rating) AS rating, at.required AS
attribute_required';
$groupsFull = 'a.id, a.title, a.image, a.alias, a.description,
a.type, a.price, a.points_received, a.price_original, a.stock,
a.stock_calculation, a.min_quantity, a.min_multiple_quantity,
a.stockstatus_a_id, a.stockstatus_n_id, a.date, a.sales, a.featured,
a.external_id, a.unit_amount, a.unit_unit, a.external_link,
a.external_text, t.id, t.tax_rate, t.calculation_type, t.title,
at.required';
$groupsFast = 'a.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$q = ' SELECT '.$columns
. ' FROM #__phocacart_products AS a'
. implode( ' ', $lefts )
. $leftImages
. ' WHERE ' . implode( ' AND ', $wheres )
. ' GROUP BY '.$groups
. ' ORDER BY '.$itemOrdering;
}
//echo "<br><br>" .
nl2br(str_replace('#__', 'jos_', $q));
return $q;
}
protected function getItemListQueryCustomers($count = 0) {
$app = JFactory::getApplication();
$db = JFactory::getDBO();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$params = $app->getParams();
$pos_customers = $params->get('pos_customers',
'');
$customers = array();
if (!empty($pos_customers)) {
foreach($pos_customers as $k => $v) {
$customersA = JAccess::getUsersByGroup((int)$v);
$customers = array_merge($customers, $customersA);
}
}
$customers = ArrayHelper::toInteger($customers);
$customers = array_unique($customers);
$customerList = implode (',', $customers);
$wheres = array();
$lefts = array();
$phrase = 'any';
//$p['switch_image_category_items'] = $params->get(
'switch_image_category_items', 0 );
$wheres[] = ' a.block = 0';
$itemOrdering = $this->getItemOrdering();
// =FILTER=
// =SEARCH=
if ($this->getState('search')) {
$in = $this->getState('search');
$words = explode(' ', $in);
$wheresS = array();
foreach ($words as $word) {
if (!$word = trim($word)) {
continue;
}
$word = $db->quote('%'.$db->escape($word,
true).'%', false);
$wheresS2 = array();
$wheresS2[] = 'a.name LIKE '.$word;
$wheresS2[] = 'a.username LIKE '.$word;
$wheresS[] = implode(' OR ', $wheresS2);
}
$wheres[] = '(' . implode(($phrase == 'all' ?
') AND (' : ') OR ('), $wheresS) . ')';
$lefts[] = '';
}
// Customers
if ($customerList != '') {
$wheres[] = ' a.id IN ('.$customerList.')';
}
// Remove empty values:
$wheres = array_filter($wheres);
$lefts = array_filter($lefts);
if ($count == 1) {
//$query = ' SELECT COUNT(DISTINCT a.id) AS count'; // 2.85ms
0.12mb
$q = ' SELECT a.id' // 2.42ms 0.12mb
. ' FROM #__users AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres );
//. ' GROUP BY a.id';
} else {
//$lefts[] = ' LEFT JOIN #__phocacart_categories AS c ON c.id =
a.catid';
$columns = 'a.id, a.name, a.username';
$groupsFull = 'a.id, a.name, a.username';
$groupsFast = 'a.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$q = ' SELECT '.$columns
. ' FROM #__users AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres )
//. ' GROUP BY '.$groups
. ' ORDER BY '.$itemOrdering;
}
//echo "<br><br>" .
nl2br(str_replace('#__', 'jos_', $q));
return $q;
}
protected function getItemListQueryUnits($count = 0) {
$app = JFactory::getApplication();
$db = JFactory::getDBO();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$params = $app->getParams();
$wheres = array();
$lefts = array();
$phrase = 'any';
$itemOrdering = $this->getItemOrdering();
$wheres[] = 'a.section_id =
'.(int)$this->getState('sectionid');
$wheres[] = 'a.published = 1';
// Get info about cart for each unit
//$wheres[] = 'cm.vendor_id =
'.(int)$this->getState('vendorid');// we need to load
empty units too
$wheres[] = '';// ticket_id - no specific ticket - we get
ticket list
$wheres[] = '';// unit_id - set in ON
$wheres[] = 'a.section_id =
'.(int)$this->getState('sectionid');
$lefts[] = ' LEFT JOIN #__phocacart_cart_multiple AS cm ON
cm.unit_id = a.id AND cm.vendor_id =
'.(int)$this->getState('vendorid');
// Remove empty values:
$wheres = array_filter($wheres);
$lefts = array_filter($lefts);
if ($count == 1) {
$q = ' SELECT a.id' // 2.42ms 0.12mb
. ' FROM #__phocacart_units AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres );
} else {
$columns = 'a.id, a.title, cm.user_id, cm.vendor_id, cm.ticket_id,
cm.unit_id, cm.section_id, cm.cart';
$q = ' SELECT '.$columns
. ' FROM #__phocacart_units AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres )
. ' ORDER BY '.$itemOrdering;
}
// echo "<br><br>" .
nl2br(str_replace('#__', 'jos_', $q));
return $q;
}
protected function getItemListQueryOrders($count = 0) {
$app = JFactory::getApplication();
$db = JFactory::getDBO();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
$params = $app->getParams();
$wheres = array();
$lefts = array();
$phrase = 'any';
$itemOrdering = $this->getItemOrdering();
// =SEARCH=
if ($this->getState('date')) {
$wheres[] = 'DATE(a.date) =
DATE('.$db->quote($this->getState('date')).')';
}
$wheres[] = 'a.vendor_id =
'.(int)$this->getState('vendorid');
$wheres[] = 'a.published = 1';
$wheres[] = 't.type = '.$db->quote('brutto');
$lefts[] = ' LEFT JOIN #__phocacart_order_total AS t ON a.id =
t.order_id';
$lefts[] = ' LEFT JOIN #__phocacart_sections AS s ON s.id =
a.section_id';
$lefts[] = ' LEFT JOIN #__phocacart_units AS un ON un.id =
a.unit_id';
$lefts[] = ' LEFT JOIN #__users AS u1 ON u1.id = a.user_id';
$lefts[] = ' LEFT JOIN #__users AS u2 ON u2.id = a.vendor_id';
// Remove empty values:
$wheres = array_filter($wheres);
$lefts = array_filter($lefts);
if ($count == 1) {
$q = ' SELECT a.id' // 2.42ms 0.12mb
. ' FROM #__phocacart_orders AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres );
} else {
$columns = 'a.id, a.title, a.user_id, a.vendor_id, a.ticket_id,
a.unit_id, a.section_id, a.currency_id,'
.' s.title AS section_title, un.title AS unit_title, u1.name AS
user_title, u2.name AS vendor_title, a.date, t.amount AS total_amount,
t.amount_currency AS total_amount_currency';
$q = ' SELECT '.$columns
. ' FROM #__phocacart_orders AS a'
. implode( ' ', $lefts )
. ' WHERE ' . implode( ' AND ', $wheres )
. ' ORDER BY '.$itemOrdering;
}
//echo "<br><br>" .
nl2br(str_replace('#__', 'jos_', $q));
return $q;
}
protected function getCategoriesQuery( $categoryId, $subcategories = FALSE
) {
$wheres = array();
$app = JFactory::getApplication();
$params = $app->getParams();
$user = PhocacartUser::getUser();
$userLevels = implode (',',
$user->getAuthorisedViewLevels());
$userGroups = implode (',',
PhocacartGroup::getGroupsById($user->id, 1, 1));
// Get the current category or get parent categories of the current
category
if ($subcategories) {
$wheres[] = " c.parent_id = ".(int)$categoryId;
$categoryOrdering = $this->getCategoryOrdering();
} else {
$wheres[] = " c.id= ".(int)$categoryId;
}
$wheres[] = " c.published = 1";
$wheres[] = " c.type IN (0,2)";
$wheres[] = " c.access IN (".$userLevels.")";
$wheres[] = " (gc.group_id IN (".$userGroups.") OR
gc.group_id IS NULL)";
if ($this->getState('filter.language')) {
$lang = JFactory::getLanguage()->getTag();
$wheres[] =
PhocacartUtilsSettings::getLangQuery('c.language', $lang);
}
if ($subcategories) {
$columns = 'c.id, c.title, c.alias, COUNT(c.id) AS numdoc';
$groupsFull = 'c.id, c.title, c.alias';
$groupsFast = 'c.id';
$groups = PhocacartUtilsSettings::isFullGroupBy() ? $groupsFull :
$groupsFast;
$query = "SELECT ".$columns
. " FROM #__phocacart_categories AS c"
. " LEFT JOIN #__phocacart_products AS a ON a.catid = c.id AND
a.published = 1"
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " GROUP BY ".$groups
. " ORDER BY ".$categoryOrdering;
} else {
$query = " SELECT c.id, c.title, c.alias, c.description,
c.metatitle, c.metakey, c.metadesc, c.metadata, cc.title as parenttitle,
c.parent_id as parentid, cc.alias as parentalias"
. " FROM #__phocacart_categories AS c"
. " LEFT JOIN #__phocacart_categories AS cc ON cc.id =
c.parent_id"
. ' LEFT JOIN #__phocacart_item_groups AS gc ON c.id = gc.item_id
AND gc.type = 2'// type 2 is category
. " WHERE " . implode( " AND ", $wheres )
. " ORDER BY c.ordering";
}
return $query;
}
protected function getItemOrdering() {
if (empty($this->item_ordering)) {
$app = JFactory::getApplication();
$params = $app->getParams();
//$ordering = $params->get( 'item_ordering', 1 );
$ordering = $this->getState('itemordering');
switch($this->getState('page')){
case 'section':
$this->item_ordering =
PhocacartOrdering::getOrderingText($ordering, 8);
break;
case 'main.content.customers':
$this->item_ordering =
PhocacartOrdering::getOrderingText($ordering, 7);
break;
case 'main.content.orders':
$this->item_ordering =
PhocacartOrdering::getOrderingText($ordering, 11);
break;
case 'main.content.products':
default:
$this->item_ordering =
PhocacartOrdering::getOrderingText($ordering);
break;
}
}
return $this->item_ordering;
}
protected function getCategoryOrdering() {
if (empty($this->category_ordering)) {
$app = JFactory::getApplication();
$params = $app->getParams();
$ordering = $params->get( 'category_ordering', 1 );
$this->category_ordering =
PhocacartOrdering::getOrderingText($ordering, 1);
}
return $this->category_ordering;
}
// ACTIONS
public function saveShipping($shippingId) {
$app = JFactory::getApplication();
$user = $vendor = $ticket = $unit = $section = array();
$dUser = PhocacartUser::defineUser($user, $vendor, $ticket, $unit,
$section);
$data['shipping'] = (int)$shippingId;
$data['user_id'] = (int)$user->id;
$shipping = new PhocacartShipping();
$shipping->setType(array(0,2));
if ((int)$shippingId == 0) {
// Deselect Shipping
} else {
$isValidShipping =
$shipping->checkAndGetShippingMethod($shippingId);
if (!$isValidShipping) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_SHIPPING_METHOD_NOT_AVAILABLE'),
'error');
return false;
}
}
$row = $this->getTable('PhocacartCart', 'Table');
if (!$row->load(array('user_id' => (int)$user->id,
'vendor_id' => (int)$vendor->id, 'ticket_id'
=> (int)$ticket->id, 'unit_id' => (int)$unit->id,
'section_id' => (int)$section->id))) {}
if (empty($row->cart)) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_CART_IS_EMPTY_SHIPPING_METHOD_CANNOT_BE_SET'),
'error');
return false;
}
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$row->date = gmdate('Y-m-d H:i:s');
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if ((int)$shippingId == 0) {
$app->enqueueMessage(JText::_('COM_PHOCACART_SUCCESS_SHIPPING_METHOD_DESELECTED'),
'success');
} else {
$app->enqueueMessage(JText::_('COM_PHOCACART_SUCCESS_SHIPPING_METHOD_SELECTED'),
'success');
}
return true;
}
public function savePaymentAndCouponAndReward($paymentId, $couponId,
$reward) {
$app = JFactory::getApplication();
$user = $vendor = $ticket = $unit = $section = array();
$dUser = PhocacartUser::defineUser($user, $vendor, $ticket, $unit,
$section);
$data['payment'] = (int)$paymentId;
$data['coupon'] = (int)$couponId;
$data['user_id'] = (int)$user->id;
$data['reward'] = (int)$reward;
$payment = new PhocacartPayment();
$payment->setType(array(0,2));
if ((int)$paymentId == 0) {
// Deselect Payment
} else {
$isValidPayment = $payment->checkAndGetPaymentMethod($paymentId);
if (!$isValidPayment) {
$app->enqueueMessage( $paymentId .
JText::_('COM_PHOCACART_ERROR_PAYMENT_METHOD_NOT_AVAILABLE'),
'error');
return false;
}
}
$row = $this->getTable('PhocacartCart', 'Table');
if (!$row->load(array('user_id' => (int)$user->id,
'vendor_id' => (int)$vendor->id, 'ticket_id'
=> (int)$ticket->id, 'unit_id' => (int)$unit->id,
'section_id' => (int)$section->id))) {}
if (empty($row->cart)) {
$app->enqueueMessage(JText::_('COM_PHOCACART_ERROR_CART_IS_EMPTY_PAYMENT_METHOD_CANNOT_BE_SET'),
'error');
return false;
}
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
$row->date = gmdate('Y-m-d H:i:s');
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if ((int)$paymentId == 0) {
$app->enqueueMessage(JText::_('COM_PHOCACART_SUCCESS_PAYMENT_METHOD_DESELECTED'),
'success');
} else {
$app->enqueueMessage(JText::_('COM_PHOCACART_SUCCESS_PAYMENT_METHOD_SELECTED'),
'success');
}
return true;
}
}
?>
question.php000064400000012150151165414670007135 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
use Joomla\CMS\Uri\Uri;
jimport('joomla.application.component.model');
class PhocaCartModelQuestion extends JModelForm
{
function __construct() {
$app = JFactory::getApplication();
parent::__construct();
$this->setState('filter.language',$app->getLanguageFilter());
}
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_phocacart.question',
'question', array('control' => 'jform',
'load_data' => true));
if (empty($form)) {
return false;
}
$app = JFactory::getApplication();
$params = $app->getParams();
// Set required or not && disable if not available
if(!$params->get('display_name_form', 2)){
$form->removeField('name');
} else if ($params->get('display_name_form', 2) == 2){
$form->setFieldAttribute('name', 'required',
'true');
}
if(!$params->get('display_email_form', 2)){
$form->removeField('email');
} else if ($params->get('display_email_form', 2) == 2){
$form->setFieldAttribute('email', 'required',
'true');
}
if(!$params->get('display_phone_form', 2)){
$form->removeField('phone');
} else if ($params->get('display_phone_form', 2) == 2){
$form->setFieldAttribute('phone', 'required',
'true');
}
if(!$params->get('display_message_form', 2)){
$form->removeField('message');
} else if ($params->get('display_message_form', 2) == 2){
$form->setFieldAttribute('message', 'required',
'true');
}
if (!$params->get('enable_hidden_field_question', 0)){
$form->removeField('hidden_field');
} else {
$form->setFieldAttribute('hidden_field', 'id',
$params->get('hidden_field_id'));
$form->setFieldAttribute('hidden_field', 'class',
$params->get('hidden_field_class'));
$form->setFieldAttribute('hidden_field', 'name',
$params->get('hidden_field_name'));
}
if (!$params->get('enable_captcha_question', 2)) {
$form->removeField('phq_captcha');
} else {
$form->setFieldAttribute('phq_captcha', 'type',
'phocacaptcha');
$form->setFieldAttribute('phq_captcha',
'captcha_id', $params->get('captcha_id'));
$form->setFieldAttribute('phq_captcha',
'validate', 'phocacartcaptcha');
}
return $form;
}
protected function loadFormData() {
$data = (array)
JFactory::getApplication()->getUserState('com_phocacart.question.data',
array());
return $data;
}
function store(&$data) {
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$uri = \Joomla\CMS\Uri\Uri::getInstance();
$app = JFactory::getApplication();
$params = PhocacartUtils::getComponentParameters() ;
// Maximum of character, they will be saved in database
$data['message'] = substr($data['message'], 0,
$params->get('max_char_question', 3000));
$data['date'] = gmdate('Y-m-d H:i:s'); // Create
the timestamp for the date
$data['params'] = '';
$data['category_id'] =
PhocacartUtils::getIntFromString($data['category_id']);
$data['product_id'] =
PhocacartUtils::getIntFromString($data['product_id']);
$data['ordering'] = $this->increaseOrdering();
$row = $this->getTable('PhocaCartQuestion');
// Bind the form fields to the table
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Make sure the table is valid
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Store the Phoca guestbook table to the database
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
// Everything OK - send email
if ($params->get('send_email_question', 0) > 0 ||
$params->get('send_email_question_others', '') !=
'') {
$data['product'] = array();
$data['category'] = array();
$productId = 0;
if(isset($data['product_id']) &&
(int)$data['product_id'] > 0) {
if(isset($data['category_id']) &&
(int)$data['category_id'] > 0) {
$data['product'] =
PhocacartProduct::getProduct($data['product_id'],
$data['category_id']);
$data['category'] =
PhocacartCategory::getCategoryById($data['category_id']);
} else {
$data['product'] =
PhocacartProduct::getProduct($data['product_id']);
}
$productId = $data['product'];
}
$send = PhocacartEmail::sendQuestionMail($data,
Uri::getInstance()->toString(), $params);
if (!$send) {
$user = PhocacartUser::getUser();
PhocacartLog::add(2, 'Ask a Question - ERROR - Problems with
sending email', $productId, 'IP: '.
$data['ip'].', User ID: '.$user->id);
}
}
$data['id'] = $row->id;
return true;
}
public function increaseOrdering() {
$this->_db->setQuery('SELECT MAX(ordering) FROM
#__phocacart_questions');
$max = $this->_db->loadResult();
$ordering = $max + 1;
return $ordering;
}
}
?>
rules/Alphanumeric.php000064400000003040151165414670011026 0ustar00<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Form\FormRule;
use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
class JFormRuleAlphanumeric extends FormRule
{
protected $regex = '/[^a-zA-Z0-9]+/i';
public function test(\SimpleXMLElement $element, $value, $group = null,
Registry $input = null, Form $form = null){
// If the field is empty and not required, the field is valid.
$required = ((string) $element['required'] == 'true'
|| (string) $element['required'] == 'required');
if (!$required && empty($value)){
return true;
}
// Uncomment for Possible string length rule
/*
if (StringHelper::strlen($value) > 10) {
return new \UnexpectedValueException(\JText::_('The maximum
allowable string length is 10 characters'));
}
*/
if (empty($this->regex)) {
throw new \UnexpectedValueException(sprintf('%s has invalid
regex.', get_class($this)));
}
if (JCOMPAT_UNICODE_PROPERTIES) {
$this->modifiers = (strpos($this->modifiers, 'u') !==
false) ? $this->modifiers : $this->modifiers . 'u';
}
if (!preg_match( $this->regex . $this->modifiers , $value)) {
return true;
}
return new
\UnexpectedValueException(\JText::_('COM_PHOCACART_ONLY_ALPHANUMERIC_CHARACTERS_ARE_ALLOWED'));
}
}
rules/index.html000064400000000072151165414670007704
0ustar00<html><body style="background-color:
#000;"></body></html>rules/phocacartcaptcha.php000064400000002115151165414670011710
0ustar00<?php
/**
* @package phocaguestbook
* @subpackage Models
* @copyright Copyright (C) 2012 Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die;
class JFormRulePhocacartCaptcha extends JFormRule
{
public function test(SimpleXMLElement $element, $value, $group = null,
JRegistry $input = null, JForm $form = null)
{
$app = JFactory::getApplication();
//E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING,
E_USER_NOTICE.
$info = array();
$info['field'] = 'question_captcha';
$params = PhocacartUtils::getComponentParameters();
$session = JFactory::getSession();
$namespace =
'phccrt'.$params->get('session_suffix');
// Possible parameters in Options for different captchas
$captchaId = 1;
switch($captchaId) {
case 1:
default:
if (!PhocacartCaptchaRecaptcha::isValid()) {
// What happens when the CAPTCHA was entered incorrectly
$app->enqueueMessage(JText::_('COM_PHOCACART_WRONG_CAPTCHA'
), 'warning');
return false;
}
return true;
break;
}
return false;
}
}
rules/phocacartemail.php000064400000002217151165414670011377
0ustar00<?php
/**
* @package phocaguestbook
* @subpackage Models
* @copyright Copyright (C) 2012 Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die;
JFormHelper::loadRuleClass('email');
class JFormRulePhocaCartEmail extends JFormRuleEmail
{
public function test(SimpleXMLElement $element, $value, $group = null,
JRegistry $input = null, JForm $form = null)
{
$app = JFactory::getApplication();
//E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING,
E_USER_NOTICE.
$info = array();
$info['field'] = 'phocacart_email';
$params = PhocacartUtils::getComponentParameters();
//EMAIL FORMAT
if(!parent::test($element, $value, $group, $input, $form)){
$app->enqueueMessage(JText::_('COM_PHOCACART_BAD_EMAIL' ),
'warning');
return false;
}
//BANNED EMAIL
$banned = $params->get('banned_email');
foreach(explode(';', $banned) as $item){
if (trim($item) != '') {
if (\Joomla\String\StringHelper::stristr($item, $value) !== false){
$app->enqueueMessage(JText::_('COM_PHOCACART_BAD_EMAIL'
), 'warning');
return false;
}
}
return true;
}
}
}
rules/phocacartfile.php000064400000002215151165414670011225
0ustar00<?php
/**
* @package phocaguestbook
* @subpackage Models
* @copyright Copyright (C) 2012 Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die;
//JFormHelper::loadRuleClass('email');
class JFormRulePhocaCartFile extends JFormRule
{
public function test(SimpleXMLElement $element, $value, $group = null,
JRegistry $input = null, JForm $form = null)
{
$app = JFactory::getApplication();
//E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING,
E_USER_NOTICE.
$info = array();
$info['field'] = 'phocacart_email';
$params = PhocacartUtils::getComponentParameters();
//EMAIL FORMAT
if(!parent::test($element, $value, $group, $input, $form)){
$app->enqueueMessage(JText::_('COM_PHOCACART_BAD_EMAIL' ),
'warning');
return false;
}
//BANNED EMAIL
$banned = $params->get('banned_email');
foreach(explode(';', $banned) as $item){
if (trim($item) != '') {
if (\Joomla\String\StringHelper::stristr($item, $value) !== false){
$app->enqueueMessage(JText::_('COM_PHOCACART_BAD_EMAIL'
), 'warning');
return false;
}
}
return true;
}
}
}
rules/phocacarthidden.php000064400000001361151165414670011542
0ustar00<?php
/**
* @package phocacart
* @subpackage Models
* @copyright Copyright (C) 2012 Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die;
class JFormRulePhocaCartHidden extends JFormRule
{
public function test(SimpleXMLElement $element, $value, $group = null,
JRegistry $input = null, JForm $form = null)
{
$app = JFactory::getApplication();
//E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING,
E_USER_NOTICE.
$info = array();
$info['field'] = 'phocacart_hidden';
//Get POST Data - - - - - - - - -
if ($value != '') {
$app->enqueueMessage(JText::_('COM_PHOCACART_POSSIBLE_SPAM_DETECTED'
), 'error');
return false;
}
return true;
}
}
rules/phocacarttitle.php000064400000001500151165414670011423
0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
class JFormRulePhocaCartTitle extends JFormRule
{
public function test(&$element, $value, $group = null, &$input =
null, &$form = null)
{
$app = JFactory::getApplication();
//E_ERROR, E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING,
E_USER_NOTICE.
//$info = array();
//$info['field'] = 'guestbook_title';
//if (preg_match("~[<|>]~",$value)) {
//}
$app->enqueueMessage(JText::_('COM_PHOCACART_BAD_SUBJECT' ),
'warning');
return false;
return true;
}
}
submit.php000064400000033177151165414670006605 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
use Joomla\CMS\Uri\Uri;
jimport('joomla.application.component.model');
class PhocaCartModelSubmit extends JModelForm
{
function __construct() {
$app = JFactory::getApplication();
parent::__construct();
$this->setState('filter.language',$app->getLanguageFilter());
}
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_phocacart.submit',
'submit', array('control' => 'jform',
'load_data' => true));
if (empty($form)) {
return false;
}
$app = JFactory::getApplication();
$params = $app->getParams();
/*
// Set required or not && disable if not available
if(!$params->get('display_name_form', 2)){
$form->removeField('name');
} else if ($params->get('display_name_form', 2) == 2){
$form->setFieldAttribute('name', 'required',
'true');
}
if(!$params->get('display_email_form', 2)){
$form->removeField('email');
} else if ($params->get('display_email_form', 2) == 2){
$form->setFieldAttribute('email', 'required',
'true');
}
if(!$params->get('display_phone_form', 2)){
$form->removeField('phone');
} else if ($params->get('display_phone_form', 2) == 2){
$form->setFieldAttribute('phone', 'required',
'true');
}
if(!$params->get('display_message_form', 2)){
$form->removeField('message');
} else if ($params->get('display_message_form', 2) == 2){
$form->setFieldAttribute('message', 'required',
'true');
}*/
if (!$params->get('enable_hidden_field_submit_item', 0)){
$form->removeField('hidden_field');
} else {
$form->setFieldAttribute('hidden_field', 'id',
$params->get('hidden_field_id'));
$form->setFieldAttribute('hidden_field', 'class',
$params->get('hidden_field_class'));
$form->setFieldAttribute('hidden_field', 'name',
$params->get('hidden_field_name'));
}
if (!$params->get('enable_captcha_submit_item', 2)) {
$form->removeField('phq_captcha');
} else {
$form->setFieldAttribute('phq_captcha', 'type',
'phocacaptcha');
$form->setFieldAttribute('phq_captcha',
'captcha_id', $params->get('captcha_id'));
$form->setFieldAttribute('phq_captcha',
'validate', 'phocacartcaptcha');
}
return $form;
}
protected function loadFormData() {
$data = (array)
JFactory::getApplication()->getUserState('com_phocacart.submit.data',
array());
return $data;
}
function store(&$data, $file)
{
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$uri = \Joomla\CMS\Uri\Uri::getInstance();
$app = JFactory::getApplication();
$user = JFactory::getUser();
$path = PhocacartPath::getPath('submititem');
$params = PhocacartUtils::getComponentParameters();
$submit_item_max_char_textarea =
$params->get('submit_item_max_char_textarea', 5000);
$submit_item_form_fields =
$params->get('submit_item_form_fields', '');
$items = array_map('trim', explode(',',
$submit_item_form_fields));
$items = array_unique($items);
$submit_item_form_fields_contact =
$params->get('submit_item_form_fields_contact',
'');
$itemsC = array_map('trim', explode(',',
$submit_item_form_fields_contact));
$itemsC = array_unique($itemsC);
$submit_item_form_fields_parameters = $params->get(
'submit_item_form_fields_parameters', '' );
$itemsP = array_map('trim', explode(',',
$submit_item_form_fields_parameters));
$itemsP = array_unique($itemsP);
// Maximum of character, they will be saved in database
$data['items_item']['description'] =
isset($data['items_item']['description']) ?
substr($data['items_item']['description'], 0,
$submit_item_max_char_textarea) : '';
$data['items_item']['description_long'] =
isset($data['items_item']['description_long']) ?
substr($data['items_item']['description_long'], 0,
$submit_item_max_char_textarea) : '';
$data['items_item']['features'] =
isset($data['items_item']['features']) ?
substr($data['items_item']['features'], 0,
$submit_item_max_char_textarea) : '';
$data['items_item']['type_feed'] =
isset($data['items_item']['type_feed']) ?
substr($data['items_item']['type_feed'], 0,
$submit_item_max_char_textarea) : '';
$data['items_item']['type_category_feed'] =
isset($data['items_item']['type_category_feed']) ?
substr($data['items_item']['type_category_feed'], 0,
$submit_item_max_char_textarea) : '';
$data['items_item']['metakey'] =
isset($data['items_item']['metakey']) ?
substr($data['items_item']['metakey'], 0,
$submit_item_max_char_textarea) : '';
$data['items_item']['metadesc'] =
isset($data['items_item']['metadesc']) ?
substr($data['items_item']['metadesc'], 0,
$submit_item_max_char_textarea) : '';
$data['items_item']['message'] =
isset($data['items_item']['message']) ?
substr($data['items_item']['message'], 0,
$submit_item_max_char_textarea) : '';
$tempData = array();
$tempData['ip'] = $data['ip'];
$tempData['privacy'] = $data['privacy'];
$item = array();
$contact = array();
$parameter = array();
if (!empty($items)) {
foreach ($items as $k => $v) {
$v = trim(str_replace('*', '', $v));
if (isset($data['items_item'][$v]) &&
$data['items_item'][$v] != '') {
$item[$v] = $data['items_item'][$v];
}
}
}
if (!empty($itemsP)) {
$parameters = PhocacartParameter::getAllParameters('alias');
foreach ($itemsP as $k => $v) {
$v = trim(str_replace('*', '', $v));
$vId = 0;
if (isset($parameters[$v]->id) &&
$parameters[$v]->id > 0) {
$vId = (int)$parameters[$v]->id;
}
if (!empty($data['items_parameter'][$vId])) {
$parameter[$vId] =
$data['items_parameter'][$vId];
}
}
}
if (!empty($itemsC)) {
foreach ($itemsC as $k => $v) {
$v = trim(str_replace('*', '', $v));
if (isset($data['items_contact'][$v]) &&
$data['items_contact'][$v] != '') {
$contact[$v] = $data['items_contact'][$v];
}
}
}
$data = array();
$data = $tempData;
$data['items_item'] = $item;
$data['items_contact'] = $contact;
$data['items_parameter'] = $parameter;
$data['date_submit'] = gmdate('Y-m-d H:i:s'); //
Create the timestamp for the date
$data['user_id'] = (int)$user->id;
$data['title'] = isset($item['title']) &&
$item['title'] != '' ? $item['title'] :
$data['date_submit'];
$data['alias'] =
PhocacartUtils::getAliasName($data['title']);
$data['ordering'] = $this->increaseOrdering();
$data['published'] = 1;
$data['upload_token'] = PhocacartUtils::getToken();
$data['upload_folder'] =
PhocacartUtils::getToken('folder');
$folderPath = JPath::clean($path['orig_abs_ds'] .
$data['upload_folder']);
// Images upload
$fileData = array();
if (!empty($file['items_item']['image'])) {
if (!isset($file['items_item']['image'][0]) ||
(isset($file['items_item']['image'][0]) &&
$file['items_item']['image'][0]['error'] ==
4)){
// No file uploaded - is OK when not required
// If requried - this will be checkedn in form field and in controller
} else {
$filesUploaded =
PhocacartFileUpload::submitItemUpload($file['items_item']['image'],
$data, $fileData, 'image');
if (!$filesUploaded) {
// message set in app
if (JFolder::exists($folderPath)) {
JFolder::delete($folderPath);
}
return false;
} else {
$data['items_item']['image'] = $fileData;
}
}
}
$dataItem = $data['items_item'];
$dataContact = $data['items_contact'];
$dataParameter = $data['items_parameter'];
$data['items_item'] = json_encode($dataItem);
$data['items_contact'] = json_encode($dataContact);
$data['items_parameter'] = json_encode($dataParameter);
$row = $this->getTable('PhocaCartSubmitItem');
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
if (JFolder::exists($folderPath)) { JFolder::delete($folderPath); }
return false;
}
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
if (JFolder::exists($folderPath)) { JFolder::delete($folderPath); }
return false;
}
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
if (JFolder::exists($folderPath)) { JFolder::delete($folderPath); }
return false;
}
// Everything OK - send email
if ($params->get('send_email_submit_item', 0) > 0 ||
$params->get('send_email_submit_item_others', '') !=
'') {
$send = PhocacartEmail::sendSubmitItemMail($dataItem, $dataContact,
$dataParameter, Uri::getInstance()->toString(), $params);
if (!$send) {
$user = PhocacartUser::getUser();
PhocacartLog::add(2, 'Submit Item - ERROR - Problems with sending
email', 0, 'IP: '. $data['ip'].', User ID:
'.$user->id);
}
}
$data['id'] = $row->id;
return true;
}
protected function preprocessForm(JForm $form, $data, $group =
'content'){
// Load Parameter Values for Parameters
$parameters = PhocacartParameter::getAllParameters();
// Items and Items (Contact) are defined in view
// Items (Parameters) will be defined here
$pC = PhocacartUtils::getComponentParameters();
// Items and Items (Contact) are defined in this view
// Items (Parameters) will be defined model (when creating the form)
// ITEMS
// Preprocess form before saving - before validate the form - we
need to set required fields so validate can check them
$submit_item_form_fields =
$pC->get('submit_item_form_fields', '');
$submit_item_form_fields_contact =
$pC->get('submit_item_form_fields_contact', '');
$items = array();
if($submit_item_form_fields != '') {
$items = array_map('trim', explode(',',
$submit_item_form_fields));
$items = array_unique($items);
}
$itemsC = array();
if($submit_item_form_fields_contact != '') {
$itemsC = array_map('trim', explode(',',
$submit_item_form_fields_contact));
$itemsC = array_unique($itemsC);
}
$fieldSets = $form->getFieldsets();
foreach ($fieldSets as $name => $fieldSet) {
if (isset($fieldSet->name) && ($fieldSet->name ==
'items_item' || $fieldSet->name == 'items_contact'))
{
foreach ($form->getFieldset($name) as $field) {
$itemsCurrent = array();
if ($fieldSet->name == 'items_item') {
$itemsCurrent = $items;
}
if ($fieldSet->name == 'items_contact') {
$itemsCurrent = $itemsC;
}
$isIncluded = 0;
if (in_array($field->fieldname . '*',
$itemsCurrent)) {
$isIncluded = 2;// included and required
}
if ($isIncluded == 2) {
//$field->required = true;
//$field->addAttribute($field->fieldname,
'true');
//$field->__set('required', true);
// BE AWARE - GROUP NEEDS TO BE DEFINED
$form->setFieldAttribute($field->fieldname,
'required', 'true', $fieldSet->name);
}
}
}
}
$submit_item_form_fields_parameters = $pC->get(
'submit_item_form_fields_parameters', '' );
if($submit_item_form_fields_parameters != '') {
$itemsP = array_map('trim', explode(',',
$submit_item_form_fields_parameters));
$itemsP = array_unique($itemsP);
if (count($parameters) > 0 && !empty($itemsP)) {
$addform = new SimpleXMLElement('<form />');
$fields = $addform->addChild('fields');
$fields->addAttribute('name',
'items_parameter');
$fieldset = $fields->addChild('fieldset');
$fieldset->addAttribute('name',
'items_parameter');
foreach ($parameters as $k => $v) {
$isIncluded = 0;
if (in_array($v->alias, $itemsP)) {
$isIncluded = 1;// included
}
if (in_array($v->alias . '*', $itemsP)) {
$isIncluded = 2;// included and required
}
if ($isIncluded > 0) {
$field = $fieldset->addChild('field');
$field->addAttribute('name', $v->id);
$field->addAttribute('parameterid', $v->id);
$field->addAttribute('parameteralias',
$v->alias);
$field->addAttribute('type',
'PhocaCartParameterValues');
//$field->addAttribute('language',
$language->lang_code);
$field->addAttribute('label', $v->title);
$field->addAttribute('class',
'chosen-select');
$field->addAttribute('multiple', 'true');
$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');
$field->addAttribute('filter', 'int_array');
if ($isIncluded == 2) {
$field->addAttribute('required', 'true');
}
}
}
$form->load($addform, false);
}
}
parent::preprocessForm($form, $data, $group);
}
public function increaseOrdering() {
$this->_db->setQuery('SELECT MAX(ordering) FROM
#__phocacart_submit_items');
$max = $this->_db->loadResult();
$ordering = $max + 1;
return $ordering;
}
}
?>
wishlist.php000064400000001016151165414670007133 0ustar00<?php
/* @package Joomla
* @copyright Copyright (C) Open Source Matters. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* @extension Phoca Extension
* @copyright Copyright (C) Jan Pavelka www.phoca.cz
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class PhocaCartModelWishList extends JModelForm
{
public function getForm($data = array(), $loadData = true) {
return false;
}
}
?>
forms/frontend.xml000064400000001700151165506420010236 0ustar00<?xml
version="1.0" encoding="utf-8"?>
<form>
<fields name="params">
<!-- Basic user account settings. -->
<fieldset name="params"
label="COM_USERS_SETTINGS_FIELDSET_LABEL">
<field
name="editor"
type="plugins"
label="COM_USERS_USER_FIELD_EDITOR_LABEL"
description="COM_USERS_USER_FIELD_EDITOR_DESC"
folder="editors"
useaccess="true"
>
<option value="">JOPTION_USE_DEFAULT</option>
</field>
<field
name="timezone"
type="timezone"
label="COM_USERS_USER_FIELD_TIMEZONE_LABEL"
description="COM_USERS_USER_FIELD_TIMEZONE_DESC"
>
<option value="">JOPTION_USE_DEFAULT</option>
</field>
<field
name="language"
type="language"
label="COM_USERS_USER_FIELD_FRONTEND_LANGUAGE_LABEL"
description="COM_USERS_USER_FIELD_FRONTEND_LANGUAGE_DESC"
client="site"
filter="cmd"
>
<option value="">JOPTION_USE_DEFAULT</option>
</field>
</fieldset>
</fields>
</form>
forms/frontend_admin.xml000064400000001426151165506420011413
0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
<fields name="params">
<!-- Backend user account settings. -->
<fieldset name="params"
label="COM_USERS_SETTINGS_FIELDSET_LABEL">
<field
name="admin_style"
type="templatestyle"
label="COM_USERS_USER_FIELD_BACKEND_TEMPLATE_LABEL"
description="COM_USERS_USER_FIELD_BACKEND_TEMPLATE_DESC"
client="administrator"
filter="uint"
>
<option value="">JOPTION_USE_DEFAULT</option>
</field>
<field
name="admin_language"
type="language"
label="COM_USERS_USER_FIELD_BACKEND_LANGUAGE_LABEL"
description="COM_USERS_USER_FIELD_BACKEND_LANGUAGE_DESC"
client="administrator"
filter="cmd"
>
<option value="">JOPTION_USE_DEFAULT</option>
</field>
</fieldset>
</fields>
</form>
forms/login.xml000064400000001337151165506420007535 0ustar00<?xml
version="1.0" encoding="utf-8"?>
<form>
<fieldset name="credentials"
label="COM_USERS_LOGIN_DEFAULT_LABEL">
<field
name="username"
type="text"
label="COM_USERS_LOGIN_USERNAME_LABEL"
class="validate-username"
filter="username"
size="25"
required="true"
validate="username"
autofocus="true"
/>
<field
name="password"
type="password"
label="JGLOBAL_PASSWORD"
class="validate-password"
required="true"
filter="raw"
size="25"
/>
</fieldset>
<field
name="secretkey"
type="text"
label="JGLOBAL_SECRETKEY"
autocomplete="one-time-code"
class=""
filter="int"
size="25"
/>
<fieldset>
<field
name="return"
type="hidden"
/>
</fieldset>
</form>
forms/profile.xml000064400000003561151165506420010066 0ustar00<?xml
version="1.0" encoding="utf-8"?>
<form>
<fieldset name="core"
label="COM_USERS_PROFILE_DEFAULT_LABEL">
<field
name="id"
type="hidden"
filter="integer"
/>
<field
name="name"
type="text"
label="COM_USERS_PROFILE_NAME_LABEL"
description="COM_USERS_PROFILE_NAME_DESC"
filter="string"
required="true"
size="30"
/>
<field
name="username"
type="text"
label="COM_USERS_PROFILE_USERNAME_LABEL"
description="COM_USERS_DESIRED_USERNAME"
class="validate-username"
filter="username"
message="COM_USERS_PROFILE_USERNAME_MESSAGE"
required="true"
size="30"
validate="username"
/>
<field
name="password1"
type="password"
label="COM_USERS_PROFILE_PASSWORD1_LABEL"
description="COM_USERS_DESIRED_PASSWORD"
autocomplete="off"
class="validate-password"
filter="raw"
size="30"
validate="password"
/>
<field
name="password2"
type="password"
label="COM_USERS_PROFILE_PASSWORD2_LABEL"
description="COM_USERS_PROFILE_PASSWORD2_DESC"
autocomplete="off"
class="validate-password"
field="password1"
filter="raw"
message="COM_USERS_PROFILE_PASSWORD1_MESSAGE"
size="30"
validate="equals"
/>
<field
name="email1"
type="email"
label="COM_USERS_PROFILE_EMAIL1_LABEL"
description="COM_USERS_PROFILE_EMAIL1_DESC"
filter="string"
required="true"
size="30"
unique="true"
validate="email"
validDomains="com_users.domains"
autocomplete="email"
/>
<field
name="email2"
type="email"
label="COM_USERS_PROFILE_EMAIL2_LABEL"
description="COM_USERS_PROFILE_EMAIL2_DESC"
field="email1"
filter="string"
message="COM_USERS_PROFILE_EMAIL2_MESSAGE"
required="true"
size="30"
validate="equals"
/>
</fieldset>
<!-- Used to get the two factor authentication configuration -->
<field
name="twofactor"
type="hidden"
/>
</form>
forms/registration.xml000064400000004024151165506420011133 0ustar00<?xml
version="1.0" encoding="utf-8"?>
<form>
<fieldset name="default"
label="COM_USERS_REGISTRATION_DEFAULT_LABEL">
<field
name="spacer"
type="spacer"
label="COM_USERS_REGISTER_REQUIRED"
class="text"
/>
<field
name="name"
type="text"
label="COM_USERS_REGISTER_NAME_LABEL"
description="COM_USERS_REGISTER_NAME_DESC"
filter="string"
required="true"
size="30"
/>
<field
name="username"
type="text"
label="COM_USERS_REGISTER_USERNAME_LABEL"
description="COM_USERS_DESIRED_USERNAME"
class="validate-username"
filter="username"
message="COM_USERS_REGISTER_USERNAME_MESSAGE"
required="true"
size="30"
validate="username"
/>
<field
name="password1"
type="password"
label="COM_USERS_PROFILE_PASSWORD1_LABEL"
description="COM_USERS_DESIRED_PASSWORD"
autocomplete="off"
class="validate-password"
field="password1"
filter="raw"
size="30"
validate="password"
required="true"
/>
<field
name="password2"
type="password"
label="COM_USERS_PROFILE_PASSWORD2_LABEL"
description="COM_USERS_PROFILE_PASSWORD2_DESC"
autocomplete="off"
class="validate-password"
field="password1"
filter="raw"
message="COM_USERS_PROFILE_PASSWORD1_MESSAGE"
size="30"
validate="equals"
required="true"
/>
<field
name="email1"
type="email"
label="COM_USERS_REGISTER_EMAIL1_LABEL"
description="COM_USERS_REGISTER_EMAIL1_DESC"
field="id"
filter="string"
required="true"
size="30"
unique="true"
validate="email"
validDomains="com_users.domains"
autocomplete="email"
/>
<field
name="email2"
type="email"
label="COM_USERS_REGISTER_EMAIL2_LABEL"
description="COM_USERS_REGISTER_EMAIL2_DESC"
field="email1"
filter="string"
message="COM_USERS_REGISTER_EMAIL2_MESSAGE"
required="true"
size="30"
validate="equals"
/>
<field
name="captcha"
type="captcha"
label="COM_USERS_CAPTCHA_LABEL"
description="COM_USERS_CAPTCHA_DESC"
validate="captcha"
/>
</fieldset>
</form>
forms/remind.xml000064400000000765151165506420007707 0ustar00<?xml
version="1.0" encoding="utf-8"?>
<form>
<fieldset name="default"
label="COM_USERS_REMIND_DEFAULT_LABEL">
<field
name="email"
type="email"
label="COM_USERS_FIELD_REMIND_EMAIL_LABEL"
description="COM_USERS_FIELD_REMIND_EMAIL_DESC"
required="true"
size="30"
validate="email"
autocomplete="email"
/>
<field
name="captcha"
type="captcha"
label="COM_USERS_CAPTCHA_LABEL"
description="COM_USERS_CAPTCHA_DESC"
validate="captcha"
/>
</fieldset>
</form>forms/reset_complete.xml000064400000001370151165506420011434
0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset name="default"
label="COM_USERS_RESET_COMPLETE_LABEL">
<field
name="password1"
type="password"
label="COM_USERS_FIELD_RESET_PASSWORD1_LABEL"
description="COM_USERS_FIELD_RESET_PASSWORD1_DESC"
autocomplete="off"
class="validate-password"
field="password2"
filter="raw"
message="COM_USERS_FIELD_RESET_PASSWORD1_MESSAGE"
required="true"
size="30"
validate="equals"
/>
<field
name="password2"
type="password"
label="COM_USERS_FIELD_RESET_PASSWORD2_LABEL"
description="COM_USERS_FIELD_RESET_PASSWORD2_DESC"
autocomplete="off"
class="validate-password"
filter="raw"
required="true"
size="30"
validate="password"
/>
</fieldset>
</form>forms/reset_confirm.xml000064400000001055151165506420011261
0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset name="default"
label="COM_USERS_RESET_CONFIRM_LABEL">
<field
name="username"
type="text"
label="COM_USERS_FIELD_RESET_CONFIRM_USERNAME_LABEL"
description="COM_USERS_FIELD_RESET_CONFIRM_USERNAME_DESC"
filter="username"
required="true"
size="30"
/>
<field
name="token"
type="text"
label="COM_USERS_FIELD_RESET_CONFIRM_TOKEN_LABEL"
description="COM_USERS_FIELD_RESET_CONFIRM_TOKEN_DESC"
filter="alnum"
required="true"
size="32"
/>
</fieldset>
</form>
forms/reset_request.xml000064400000000771151165506420011320
0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset name="default"
label="COM_USERS_RESET_REQUEST_LABEL">
<field
name="email"
type="text"
label="COM_USERS_FIELD_PASSWORD_RESET_LABEL"
description="COM_USERS_FIELD_PASSWORD_RESET_DESC"
class="validate-username"
filter="email"
required="true"
size="30"
/>
<field
name="captcha"
type="captcha"
label="COM_USERS_CAPTCHA_LABEL"
description="COM_USERS_CAPTCHA_DESC"
validate="captcha"
/>
</fieldset>
</form>forms/sitelang.xml000064400000000622151165506420010227
0ustar00<?xml version="1.0" encoding="utf-8"?>
<form>
<fields name="params">
<fieldset name="params"
label="COM_USERS_SETTINGS_FIELDSET_LABEL">
<field
name="language"
type="language"
label="COM_USERS_USER_FIELD_FRONTEND_LANGUAGE_LABEL"
description="COM_USERS_USER_FIELD_FRONTEND_LANGUAGE_DESC"
client="site"
filter="cmd"
default="active"
/>
</fieldset>
</fields>
</form>login.php000064400000005262151165506420006377 0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Rest model class for Users.
*
* @since 1.6
*/
class UsersModelLogin extends JModelForm
{
/**
* Method to get the login 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 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_users.login',
'login', 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 1.6
*/
protected function loadFormData()
{
// Check the session for previously entered login form data.
$app = JFactory::getApplication();
$data = $app->getUserState('users.login.form.data',
array());
$input = $app->input->getInputForRequestMethod();
// Check for return URL from the request first
if ($return = $input->get('return', '',
'BASE64'))
{
$data['return'] = base64_decode($return);
if (!JUri::isInternal($data['return']))
{
$data['return'] = '';
}
}
$app->setUserState('users.login.form.data', $data);
$this->preprocessData('com_users.login', $data);
return $data;
}
/**
* Method to auto-populate the model state.
*
* Calling getState in this method will result in recursion.
*
* @return void
*
* @since 1.6
*/
protected function populateState()
{
// Get the application object.
$params =
JFactory::getApplication()->getParams('com_users');
// Load the parameters.
$this->setState('params', $params);
}
/**
* Override JModelAdmin::preprocessForm to ensure the correct plugin group
is loaded.
*
* @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 =
'user')
{
parent::preprocessForm($form, $data, $group);
}
}
profile.php000064400000025670151165506420006734 0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\Registry\Registry;
/**
* Profile model class for Users.
*
* @since 1.6
*/
class UsersModelProfile extends JModelForm
{
/**
* @var object The user profile data.
* @since 1.6
*/
protected $data;
/**
* Constructor
*
* @param array $config An array of configuration options (name,
state, dbo, table_path, ignore_request).
*
* @since 3.2
*
* @throws Exception
*/
public function __construct($config = array())
{
$config = array_merge(
array(
'events_map' => array('validate' =>
'user')
), $config
);
parent::__construct($config);
// Load the helper and model used for two factor authentication
JLoader::register('UsersModelUser', JPATH_ADMINISTRATOR .
'/components/com_users/models/user.php');
JLoader::register('UsersHelper', JPATH_ADMINISTRATOR .
'/components/com_users/helpers/users.php');
}
/**
* Method to check in a user.
*
* @param integer $userId The id of the row to check out.
*
* @return boolean True on success, false on failure.
*
* @since 1.6
*/
public function checkin($userId = null)
{
// Get the user id.
$userId = (!empty($userId)) ? $userId : (int)
$this->getState('user.id');
if ($userId)
{
// Initialise the table with JUser.
$table = JTable::getInstance('User');
// Attempt to check the row in.
if (!$table->checkin($userId))
{
$this->setError($table->getError());
return false;
}
}
return true;
}
/**
* Method to check out a user for editing.
*
* @param integer $userId The id of the row to check out.
*
* @return boolean True on success, false on failure.
*
* @since 1.6
*/
public function checkout($userId = null)
{
// Get the user id.
$userId = (!empty($userId)) ? $userId : (int)
$this->getState('user.id');
if ($userId)
{
// Initialise the table with JUser.
$table = JTable::getInstance('User');
// Get the current user object.
$user = JFactory::getUser();
// Attempt to check the row out.
if (!$table->checkout($user->get('id'), $userId))
{
$this->setError($table->getError());
return false;
}
}
return true;
}
/**
* Method to get the profile form data.
*
* The base form data is loaded and then an event is fired
* for users plugins to extend the data.
*
* @return mixed Data object on success, false on failure.
*
* @since 1.6
*/
public function getData()
{
if ($this->data === null)
{
$userId = $this->getState('user.id');
// Initialise the table with JUser.
$this->data = new JUser($userId);
// Set the base user data.
$this->data->email1 = $this->data->get('email');
$this->data->email2 = $this->data->get('email');
// Override the base user data with any data in the session.
$temp = (array)
JFactory::getApplication()->getUserState('com_users.edit.profile.data',
array());
foreach ($temp as $k => $v)
{
$this->data->$k = $v;
}
// Unset the passwords.
unset($this->data->password1, $this->data->password2);
$registry = new Registry($this->data->params);
$this->data->params = $registry->toArray();
}
return $this->data;
}
/**
* Method to get the profile 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 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_users.profile',
'profile', array('control' => 'jform',
'load_data' => $loadData));
if (empty($form))
{
return false;
}
// Check for username compliance and parameter set
$isUsernameCompliant = true;
$username = $loadData ? $form->getValue('username') :
$this->loadFormData()->username;
if ($username)
{
$isUsernameCompliant =
!(preg_match('#[<>"\'%;()&\\\\]|\\.\\./#',
$username) || strlen(utf8_decode($username)) < 2
|| trim($username) !== $username);
}
$this->setState('user.username.compliant',
$isUsernameCompliant);
if ($isUsernameCompliant &&
!JComponentHelper::getParams('com_users')->get('change_login_name'))
{
$form->setFieldAttribute('username', 'class',
'');
$form->setFieldAttribute('username', 'filter',
'');
$form->setFieldAttribute('username',
'description',
'COM_USERS_PROFILE_NOCHANGE_USERNAME_DESC');
$form->setFieldAttribute('username', 'validate',
'');
$form->setFieldAttribute('username', 'message',
'');
$form->setFieldAttribute('username', 'readonly',
'true');
$form->setFieldAttribute('username', 'required',
'false');
}
// When multilanguage is set, a user's default site language should
also be a Content Language
if (JLanguageMultilang::isEnabled())
{
$form->setFieldAttribute('language', 'type',
'frontend_language', 'params');
}
// If the user needs to change their password, mark the password fields
as required
if (JFactory::getUser()->requireReset)
{
$form->setFieldAttribute('password1', 'required',
'true');
$form->setFieldAttribute('password2', 'required',
'true');
}
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->getData();
$this->preprocessData('com_users.profile', $data,
'user');
return $data;
}
/**
* Override preprocessForm to load the user plugin group instead of
content.
*
* @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
*
* @throws Exception if there is an error in the form event.
*
* @since 1.6
*/
protected function preprocessForm(JForm $form, $data, $group =
'user')
{
if
(JComponentHelper::getParams('com_users')->get('frontend_userparams'))
{
$form->loadFile('frontend', false);
if (JFactory::getUser()->authorise('core.login.admin'))
{
$form->loadFile('frontend_admin', false);
}
}
parent::preprocessForm($form, $data, $group);
}
/**
* 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()
{
// Get the application object.
$params =
JFactory::getApplication()->getParams('com_users');
// Get the user id.
$userId =
JFactory::getApplication()->getUserState('com_users.edit.profile.id');
$userId = !empty($userId) ? $userId : (int)
JFactory::getUser()->get('id');
// Set the user id.
$this->setState('user.id', $userId);
// Load the parameters.
$this->setState('params', $params);
}
/**
* Method to save the form data.
*
* @param array $data The form data.
*
* @return mixed The user id on success, false on failure.
*
* @since 1.6
*/
public function save($data)
{
$userId = (!empty($data['id'])) ? $data['id'] : (int)
$this->getState('user.id');
$user = new JUser($userId);
// Prepare the data for the user object.
$data['email'] =
JStringPunycode::emailToPunycode($data['email1']);
$data['password'] = $data['password1'];
// Unset the username if it should not be overwritten
$isUsernameCompliant =
$this->getState('user.username.compliant');
if ($isUsernameCompliant &&
!JComponentHelper::getParams('com_users')->get('change_login_name'))
{
unset($data['username']);
}
// Unset block and sendEmail so they do not get overwritten
unset($data['block'], $data['sendEmail']);
// Handle the two factor authentication setup
if (array_key_exists('twofactor', $data))
{
$model = new UsersModelUser;
$twoFactorMethod = $data['twofactor']['method'];
// Get the current One Time Password (two factor auth) configuration
$otpConfig = $model->getOtpConfig($userId);
if ($twoFactorMethod !== 'none')
{
// Run the plugins
FOFPlatform::getInstance()->importPlugin('twofactorauth');
$otpConfigReplies =
FOFPlatform::getInstance()->runPlugins('onUserTwofactorApplyConfiguration',
array($twoFactorMethod));
// Look for a valid reply
foreach ($otpConfigReplies as $reply)
{
if (!is_object($reply) || empty($reply->method) ||
($reply->method != $twoFactorMethod))
{
continue;
}
$otpConfig->method = $reply->method;
$otpConfig->config = $reply->config;
break;
}
// Save OTP configuration.
$model->setOtpConfig($userId, $otpConfig);
// Generate one time emergency passwords if required (depleted or not
set)
if (empty($otpConfig->otep))
{
$model->generateOteps($userId);
}
}
else
{
$otpConfig->method = 'none';
$otpConfig->config = array();
$model->setOtpConfig($userId, $otpConfig);
}
// Unset the raw data
unset($data['twofactor']);
// Reload the user record with the updated OTP configuration
$user->load($userId);
}
// Bind the data.
if (!$user->bind($data))
{
$this->setError(JText::sprintf('COM_USERS_PROFILE_BIND_FAILED',
$user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Retrieve the user groups so they don't get overwritten
unset($user->groups);
$user->groups = JAccess::getGroupsByUser($user->id, false);
// Store the data.
if (!$user->save())
{
$this->setError($user->getError());
return false;
}
return $user->id;
}
/**
* Gets the configuration forms for all two-factor authentication methods
* in an array.
*
* @param integer $userId The user ID to load the forms for (optional)
*
* @return array
*
* @since 3.2
*/
public function getTwofactorform($userId = null)
{
$userId = (!empty($userId)) ? $userId : (int)
$this->getState('user.id');
$model = new UsersModelUser;
$otpConfig = $model->getOtpConfig($userId);
FOFPlatform::getInstance()->importPlugin('twofactorauth');
return
FOFPlatform::getInstance()->runPlugins('onUserTwofactorShowConfiguration',
array($otpConfig, $userId));
}
/**
* Returns the one time password (OTP) – a.k.a. two factor
authentication –
* configuration for a particular user.
*
* @param integer $userId The numeric ID of the user
*
* @return stdClass An object holding the OTP configuration for this
user
*
* @since 3.2
*/
public function getOtpConfig($userId = null)
{
$userId = (!empty($userId)) ? $userId : (int)
$this->getState('user.id');
$model = new UsersModelUser;
return $model->getOtpConfig($userId);
}
}
registration.php000064400000043504151165506420010002 0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\CMS\Router\Route;
/**
* Registration model class for Users.
*
* @since 1.6
*/
class UsersModelRegistration extends JModelForm
{
/**
* @var object The user registration data.
* @since 1.6
*/
protected $data;
/**
* Constructor
*
* @param array $config An array of configuration options (name,
state, dbo, table_path, ignore_request).
*
* @since 3.6
*
* @throws Exception
*/
public function __construct($config = array())
{
$config = array_merge(
array(
'events_map' => array('validate' =>
'user')
), $config
);
parent::__construct($config);
}
/**
* Method to get the user ID from the given token
*
* @param string $token The activation token.
*
* @return mixed False on failure, id of the user on success
*
* @since 3.8.13
*/
public function getUserIdFromToken($token)
{
$db = $this->getDbo();
// Get the user id based on the token.
$query = $db->getQuery(true);
$query->select($db->quoteName('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('activation') . ' = ' .
$db->quote($token))
->where($db->quoteName('block') . ' = ' . 1)
->where($db->quoteName('lastvisitDate') . ' =
' . $db->quote($db->getNullDate()));
$db->setQuery($query);
try
{
return (int) $db->loadResult();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
return false;
}
}
/**
* Method to activate a user account.
*
* @param string $token The activation token.
*
* @return mixed False on failure, user object on success.
*
* @since 1.6
*/
public function activate($token)
{
$config = JFactory::getConfig();
$userParams = JComponentHelper::getParams('com_users');
$userId = $this->getUserIdFromToken($token);
// Check for a valid user id.
if (!$userId)
{
$this->setError(JText::_('COM_USERS_ACTIVATION_TOKEN_NOT_FOUND'));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Activate the user.
$user = JFactory::getUser($userId);
// Admin activation is on and user is verifying their email
if (($userParams->get('useractivation') == 2) &&
!$user->getParam('activate', 0))
{
$linkMode = $config->get('force_ssl', 0) == 2 ?
Route::TLS_FORCE : Route::TLS_IGNORE;
// Compile the admin notification mail values.
$data = $user->getProperties();
$data['activation'] =
JApplicationHelper::getHash(JUserHelper::genRandomPassword());
$user->set('activation', $data['activation']);
$data['siteurl'] = JUri::base();
$data['activate'] = JRoute::link(
'site',
'index.php?option=com_users&task=registration.activate&token='
. $data['activation'],
false,
$linkMode,
true
);
$data['fromname'] = $config->get('fromname');
$data['mailfrom'] = $config->get('mailfrom');
$data['sitename'] = $config->get('sitename');
$user->setParam('activate', 1);
$emailSubject = JText::sprintf(
'COM_USERS_EMAIL_ACTIVATE_WITH_ADMIN_ACTIVATION_SUBJECT',
$data['name'],
$data['sitename']
);
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_ACTIVATE_WITH_ADMIN_ACTIVATION_BODY',
$data['sitename'],
$data['name'],
$data['email'],
$data['username'],
$data['activate']
);
// Get all admin users
$db = $this->getDbo();
$query = $db->getQuery(true)
->select($db->quoteName(array('name',
'email', 'sendEmail', 'id')))
->from($db->quoteName('#__users'))
->where($db->quoteName('sendEmail') . ' = 1')
->where($db->quoteName('block') . ' = 0');
$db->setQuery($query);
try
{
$rows = $db->loadObjectList();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
return false;
}
// Send mail to all users with users creating permissions and receiving
system emails
foreach ($rows as $row)
{
$usercreator = JFactory::getUser($row->id);
if ($usercreator->authorise('core.create',
'com_users') &&
$usercreator->authorise('core.manage', 'com_users'))
{
$return =
JFactory::getMailer()->sendMail($data['mailfrom'],
$data['fromname'], $row->email, $emailSubject, $emailBody);
// Check for an error.
if ($return !== true)
{
$this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED'));
return false;
}
}
}
}
// Admin activation is on and admin is activating the account
elseif (($userParams->get('useractivation') == 2) &&
$user->getParam('activate', 0))
{
$user->set('activation', '');
$user->set('block', '0');
// Compile the user activated notification mail values.
$data = $user->getProperties();
$user->setParam('activate', 0);
$data['fromname'] = $config->get('fromname');
$data['mailfrom'] = $config->get('mailfrom');
$data['sitename'] = $config->get('sitename');
$data['siteurl'] = JUri::base();
$emailSubject = JText::sprintf(
'COM_USERS_EMAIL_ACTIVATED_BY_ADMIN_ACTIVATION_SUBJECT',
$data['name'],
$data['sitename']
);
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_ACTIVATED_BY_ADMIN_ACTIVATION_BODY',
$data['name'],
$data['siteurl'],
$data['username']
);
$return =
JFactory::getMailer()->sendMail($data['mailfrom'],
$data['fromname'], $data['email'], $emailSubject,
$emailBody);
// Check for an error.
if ($return !== true)
{
$this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED'));
return false;
}
}
else
{
$user->set('activation', '');
$user->set('block', '0');
}
// Store the user object.
if (!$user->save())
{
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_ACTIVATION_SAVE_FAILED',
$user->getError()));
return false;
}
return $user;
}
/**
* Method to get the registration form data.
*
* The base form data is loaded and then an event is fired
* for users plugins to extend the data.
*
* @return mixed Data object on success, false on failure.
*
* @since 1.6
*/
public function getData()
{
if ($this->data === null)
{
$this->data = new stdClass;
$app = JFactory::getApplication();
$params = JComponentHelper::getParams('com_users');
// Override the base user data with any data in the session.
$temp = (array)
$app->getUserState('com_users.registration.data', array());
// Don't load the data in this getForm call, or we'll call
ourself
$form = $this->getForm(array(), false);
foreach ($temp as $k => $v)
{
// Here we could have a grouped field, let's check it
if (is_array($v))
{
$this->data->$k = new stdClass;
foreach ($v as $key => $val)
{
if ($form->getField($key, $k) !== false)
{
$this->data->$k->$key = $val;
}
}
}
// Only merge the field if it exists in the form.
elseif ($form->getField($k) !== false)
{
$this->data->$k = $v;
}
}
// Get the groups the user should be added to after registration.
$this->data->groups = array();
// Get the default new user group, guest or public group if not
specified.
$system = $params->get('new_usertype',
$params->get('guest_usergroup', 1));
$this->data->groups[] = $system;
// Unset the passwords.
unset($this->data->password1, $this->data->password2);
// Get the dispatcher and load the users plugins.
$dispatcher = JEventDispatcher::getInstance();
JPluginHelper::importPlugin('user');
// Trigger the data preparation event.
$results = $dispatcher->trigger('onContentPrepareData',
array('com_users.registration', $this->data));
// Check for errors encountered while preparing the data.
if (count($results) && in_array(false, $results, true))
{
$this->setError($dispatcher->getError());
$this->data = false;
}
}
return $this->data;
}
/**
* Method to get the registration 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 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_users.registration',
'registration', array('control' =>
'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
// When multilanguage is set, a user's default site language should
also be a Content Language
if (JLanguageMultilang::isEnabled())
{
$form->setFieldAttribute('language', 'type',
'frontend_language', 'params');
}
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->getData();
if (JLanguageMultilang::isEnabled() && empty($data->language))
{
$data->language = JFactory::getLanguage()->getTag();
}
$this->preprocessData('com_users.registration', $data);
return $data;
}
/**
* Override preprocessForm to load the user plugin group instead of
content.
*
* @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 =
'user')
{
$userParams = JComponentHelper::getParams('com_users');
// Add the choice for site language at registration time
if ($userParams->get('site_language') == 1 &&
$userParams->get('frontend_userparams') == 1)
{
$form->loadFile('sitelang', false);
}
parent::preprocessForm($form, $data, $group);
}
/**
* 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()
{
// Get the application object.
$app = JFactory::getApplication();
$params = $app->getParams('com_users');
// Load the parameters.
$this->setState('params', $params);
}
/**
* Method to save the form data.
*
* @param array $temp The form data.
*
* @return mixed The user id on success, false on failure.
*
* @since 1.6
*/
public function register($temp)
{
$params = JComponentHelper::getParams('com_users');
// Initialise the table with JUser.
$user = new JUser;
$data = (array) $this->getData();
// Merge in the registration data.
foreach ($temp as $k => $v)
{
$data[$k] = $v;
}
// Prepare the data for the user object.
$data['email'] =
JStringPunycode::emailToPunycode($data['email1']);
$data['password'] = $data['password1'];
$useractivation = $params->get('useractivation');
$sendpassword = $params->get('sendpassword', 1);
// Check if the user needs to activate their account.
if (($useractivation == 1) || ($useractivation == 2))
{
$data['activation'] =
JApplicationHelper::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
// Bind the data.
if (!$user->bind($data))
{
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_BIND_FAILED',
$user->getError()));
return false;
}
// Load the users plugin group.
JPluginHelper::importPlugin('user');
// Store the data.
if (!$user->save())
{
$this->setError(JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED',
$user->getError()));
return false;
}
$config = JFactory::getConfig();
$db = $this->getDbo();
$query = $db->getQuery(true);
// Compile the notification mail values.
$data = $user->getProperties();
$data['fromname'] = $config->get('fromname');
$data['mailfrom'] = $config->get('mailfrom');
$data['sitename'] = $config->get('sitename');
$data['siteurl'] = JUri::root();
// Handle account activation/confirmation emails.
if ($useractivation == 2)
{
// Set the link to confirm the user email.
$linkMode = $config->get('force_ssl', 0) == 2 ?
Route::TLS_FORCE : Route::TLS_IGNORE;
$data['activate'] = JRoute::link(
'site',
'index.php?option=com_users&task=registration.activate&token='
. $data['activation'],
false,
$linkMode,
true
);
$emailSubject = JText::sprintf(
'COM_USERS_EMAIL_ACCOUNT_DETAILS',
$data['name'],
$data['sitename']
);
if ($sendpassword)
{
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY',
$data['name'],
$data['sitename'],
$data['activate'],
$data['siteurl'],
$data['username'],
$data['password_clear']
);
}
else
{
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_REGISTERED_WITH_ADMIN_ACTIVATION_BODY_NOPW',
$data['name'],
$data['sitename'],
$data['activate'],
$data['siteurl'],
$data['username']
);
}
}
elseif ($useractivation == 1)
{
// Set the link to activate the user account.
$linkMode = $config->get('force_ssl', 0) == 2 ?
Route::TLS_FORCE : Route::TLS_IGNORE;
$data['activate'] = JRoute::link(
'site',
'index.php?option=com_users&task=registration.activate&token='
. $data['activation'],
false,
$linkMode,
true
);
$emailSubject = JText::sprintf(
'COM_USERS_EMAIL_ACCOUNT_DETAILS',
$data['name'],
$data['sitename']
);
if ($sendpassword)
{
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY',
$data['name'],
$data['sitename'],
$data['activate'],
$data['siteurl'],
$data['username'],
$data['password_clear']
);
}
else
{
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_REGISTERED_WITH_ACTIVATION_BODY_NOPW',
$data['name'],
$data['sitename'],
$data['activate'],
$data['siteurl'],
$data['username']
);
}
}
else
{
$emailSubject = JText::sprintf(
'COM_USERS_EMAIL_ACCOUNT_DETAILS',
$data['name'],
$data['sitename']
);
if ($sendpassword)
{
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_REGISTERED_BODY',
$data['name'],
$data['sitename'],
$data['siteurl'],
$data['username'],
$data['password_clear']
);
}
else
{
$emailBody = JText::sprintf(
'COM_USERS_EMAIL_REGISTERED_BODY_NOPW',
$data['name'],
$data['sitename'],
$data['siteurl']
);
}
}
// Send the registration email.
$return = JFactory::getMailer()->sendMail($data['mailfrom'],
$data['fromname'], $data['email'], $emailSubject,
$emailBody);
// Send Notification mail to administrators
if (($params->get('useractivation') < 2) &&
($params->get('mail_to_admin') == 1))
{
$emailSubject = JText::sprintf(
'COM_USERS_EMAIL_ACCOUNT_DETAILS',
$data['name'],
$data['sitename']
);
$emailBodyAdmin = JText::sprintf(
'COM_USERS_EMAIL_REGISTERED_NOTIFICATION_TO_ADMIN_BODY',
$data['name'],
$data['username'],
$data['siteurl']
);
// Get all admin users
$query->clear()
->select($db->quoteName(array('name',
'email', 'sendEmail')))
->from($db->quoteName('#__users'))
->where($db->quoteName('sendEmail') . ' = 1')
->where($db->quoteName('block') . ' = 0');
$db->setQuery($query);
try
{
$rows = $db->loadObjectList();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
return false;
}
// Send mail to all superadministrators id
foreach ($rows as $row)
{
$return =
JFactory::getMailer()->sendMail($data['mailfrom'],
$data['fromname'], $row->email, $emailSubject,
$emailBodyAdmin);
// Check for an error.
if ($return !== true)
{
$this->setError(JText::_('COM_USERS_REGISTRATION_ACTIVATION_NOTIFY_SEND_MAIL_FAILED'));
return false;
}
}
}
// Check for an error.
if ($return !== true)
{
$this->setError(JText::_('COM_USERS_REGISTRATION_SEND_MAIL_FAILED'));
// Send a system message to administrators receiving system mails
$db = $this->getDbo();
$query->clear()
->select($db->quoteName('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('block') . ' = ' .
(int) 0)
->where($db->quoteName('sendEmail') . ' = ' .
(int) 1);
$db->setQuery($query);
try
{
$userids = $db->loadColumn();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
return false;
}
if (count($userids) > 0)
{
$jdate = new JDate;
// Build the query to add the messages
foreach ($userids as $userid)
{
$values = array(
$db->quote($userid),
$db->quote($userid),
$db->quote($jdate->toSql()),
$db->quote(JText::_('COM_USERS_MAIL_SEND_FAILURE_SUBJECT')),
$db->quote(JText::sprintf('COM_USERS_MAIL_SEND_FAILURE_BODY',
$return, $data['username']))
);
$query->clear()
->insert($db->quoteName('#__messages'))
->columns($db->quoteName(array('user_id_from',
'user_id_to', 'date_time', 'subject',
'message')))
->values(implode(',', $values));
$db->setQuery($query);
try
{
$db->execute();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
return false;
}
}
}
return false;
}
if ($useractivation == 1)
{
return 'useractivate';
}
elseif ($useractivation == 2)
{
return 'adminactivate';
}
else
{
return $user->id;
}
}
}
remind.php000064400000011100151165506420006531 0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\Utilities\ArrayHelper;
/**
* Remind model class for Users.
*
* @since 1.5
*/
class UsersModelRemind extends JModelForm
{
/**
* Method to get the username remind request 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 JFor 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_users.remind',
'remind', array('control' => 'jform',
'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
/**
* Override preprocessForm to load the user plugin group instead of
content.
*
* @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
*
* @throws Exception if there is an error in the form event.
*
* @since 1.6
*/
protected function preprocessForm(JForm $form, $data, $group =
'user')
{
parent::preprocessForm($form, $data, 'user');
}
/**
* 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()
{
// Get the application object.
$app = JFactory::getApplication();
$params = $app->getParams('com_users');
// Load the parameters.
$this->setState('params', $params);
}
/**
* Send the remind username email
*
* @param array $data Array with the data received from the form
*
* @return boolean
*
* @since 1.6
*/
public function processRemindRequest($data)
{
// Get the form.
$form = $this->getForm();
$data['email'] =
JStringPunycode::emailToPunycode($data['email']);
// Check for an error.
if (empty($form))
{
return false;
}
// Validate the data.
$data = $this->validate($form, $data);
// Check for an error.
if ($data instanceof Exception)
{
return false;
}
// Check the validation results.
if ($data === false)
{
// Get the validation messages from the form.
foreach ($form->getErrors() as $formError)
{
$this->setError($formError->getMessage());
}
return false;
}
// Find the user id for the given email address.
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('*')
->from($db->quoteName('#__users'))
->where('LOWER(' . $db->quoteName('email') .
') = LOWER(' . $db->quote($data['email']) .
')');
// Get the user id.
$db->setQuery($query);
try
{
$user = $db->loadObject();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
return false;
}
// Check for a user.
if (empty($user))
{
$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
return false;
}
// Make sure the user isn't blocked.
if ($user->block)
{
$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
return false;
}
$config = JFactory::getConfig();
// Assemble the login link.
$link = 'index.php?option=com_users&view=login';
$mode = $config->get('force_ssl', 0) == 2 ? 1 : (-1);
// Put together the email template data.
$data = ArrayHelper::fromObject($user);
$data['fromname'] = $config->get('fromname');
$data['mailfrom'] = $config->get('mailfrom');
$data['sitename'] = $config->get('sitename');
$data['link_text'] = JRoute::_($link, false, $mode);
$data['link_html'] = JRoute::_($link, true, $mode);
$subject = JText::sprintf(
'COM_USERS_EMAIL_USERNAME_REMINDER_SUBJECT',
$data['sitename']
);
$body = JText::sprintf(
'COM_USERS_EMAIL_USERNAME_REMINDER_BODY',
$data['sitename'],
$data['username'],
$data['link_text']
);
// Send the password reset request email.
$return = JFactory::getMailer()->sendMail($data['mailfrom'],
$data['fromname'], $user->email, $subject, $body);
// Check for an error.
if ($return !== true)
{
$this->setError(JText::_('COM_USERS_MAIL_FAILED'), 500);
return false;
}
$dispatcher = \JEventDispatcher::getInstance();
$dispatcher->trigger('onUserAfterRemind', array($user));
return true;
}
}
reset.php000064400000030516151165506420006411 0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Rest model class for Users.
*
* @since 1.5
*/
class UsersModelReset extends JModelForm
{
/**
* Method to get the password reset request 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 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_users.reset_request',
'reset_request', array('control' =>
'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
/**
* Method to get the password reset complete 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 getResetCompleteForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_users.reset_complete',
'reset_complete', $options = array('control' =>
'jform'));
if (empty($form))
{
return false;
}
return $form;
}
/**
* Method to get the password reset confirm 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 getResetConfirmForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_users.reset_confirm',
'reset_confirm', $options = array('control' =>
'jform'));
if (empty($form))
{
return false;
}
else
{
$form->setValue('token', '',
JFactory::getApplication()->input->get('token'));
}
return $form;
}
/**
* Override preprocessForm to load the user plugin group instead of
content.
*
* @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
*
* @throws Exception if there is an error in the form event.
*
* @since 1.6
*/
protected function preprocessForm(JForm $form, $data, $group =
'user')
{
parent::preprocessForm($form, $data, $group);
}
/**
* 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()
{
// Get the application object.
$params =
JFactory::getApplication()->getParams('com_users');
// Load the parameters.
$this->setState('params', $params);
}
/**
* Save the new password after reset is done
*
* @param array $data The data expected for the form.
*
* @return mixed Exception | JException | boolean
*
* @since 1.6
*/
public function processResetComplete($data)
{
// Get the form.
$form = $this->getResetCompleteForm();
// 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 token and user id from the confirmation process.
$app = JFactory::getApplication();
$token = $app->getUserState('com_users.reset.token', null);
$userId = $app->getUserState('com_users.reset.user', null);
// Check the token and user id.
if (empty($token) || empty($userId))
{
return new
JException(JText::_('COM_USERS_RESET_COMPLETE_TOKENS_MISSING'),
403);
}
// Get the user object.
$user = JUser::getInstance($userId);
// Check for a user and that the tokens match.
if (empty($user) || $user->activation !== $token)
{
$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
return false;
}
// Make sure the user isn't blocked.
if ($user->block)
{
$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
return false;
}
// Check if the user is reusing the current password if required to reset
their password
if ($user->requireReset == 1 &&
JUserHelper::verifyPassword($data['password1'],
$user->password))
{
$this->setError(JText::_('JLIB_USER_ERROR_CANNOT_REUSE_PASSWORD'));
return false;
}
// Prepare user data.
$data['password'] = $data['password1'];
$data['activation'] = '';
// Update the user object.
if (!$user->bind($data))
{
return new \Exception($user->getError(), 500);
}
// Save the user to the database.
if (!$user->save(true))
{
return new
JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED',
$user->getError()), 500);
}
// Flush the user data from the session.
$app->setUserState('com_users.reset.token', null);
$app->setUserState('com_users.reset.user', null);
return true;
}
/**
* Receive the reset password request
*
* @param array $data The data expected for the form.
*
* @return mixed Exception | JException | boolean
*
* @since 1.6
*/
public function processResetConfirm($data)
{
// Get the form.
$form = $this->getResetConfirmForm();
// 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;
}
// Find the user id for the given token.
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('activation')
->select('id')
->select('block')
->from($db->quoteName('#__users'))
->where($db->quoteName('username') . ' = ' .
$db->quote($data['username']));
// Get the user id.
$db->setQuery($query);
try
{
$user = $db->loadObject();
}
catch (RuntimeException $e)
{
return new
JException(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
}
// Check for a user.
if (empty($user))
{
$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
return false;
}
if (!$user->activation)
{
$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
return false;
}
// Verify the token
if (!JUserHelper::verifyPassword($data['token'],
$user->activation))
{
$this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
return false;
}
// Make sure the user isn't blocked.
if ($user->block)
{
$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
return false;
}
// Push the user data into the session.
$app = JFactory::getApplication();
$app->setUserState('com_users.reset.token',
$user->activation);
$app->setUserState('com_users.reset.user', $user->id);
return true;
}
/**
* Method to start the password reset process.
*
* @param array $data The data expected for the form.
*
* @return mixed Exception | JException | boolean
*
* @since 1.6
*/
public function processResetRequest($data)
{
$config = JFactory::getConfig();
// 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;
}
// Find the user id for the given email address.
$db = $this->getDbo();
$query = $db->getQuery(true)
->select('id')
->from($db->quoteName('#__users'))
->where('LOWER(' . $db->quoteName('email') .
') = LOWER(' . $db->quote($data['email']) .
')');
// Get the user object.
$db->setQuery($query);
try
{
$userId = $db->loadResult();
}
catch (RuntimeException $e)
{
$this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR',
$e->getMessage()), 500);
return false;
}
// Check for a user.
if (empty($userId))
{
$this->setError(JText::_('COM_USERS_INVALID_EMAIL'));
return false;
}
// Get the user object.
$user = JUser::getInstance($userId);
// Make sure the user isn't blocked.
if ($user->block)
{
$this->setError(JText::_('COM_USERS_USER_BLOCKED'));
return false;
}
// Make sure the user isn't a Super Admin.
if ($user->authorise('core.admin'))
{
$this->setError(JText::_('COM_USERS_REMIND_SUPERADMIN_ERROR'));
return false;
}
// Make sure the user has not exceeded the reset limit
if (!$this->checkResetLimit($user))
{
$resetLimit = (int)
JFactory::getApplication()->getParams()->get('reset_time');
$this->setError(JText::plural('COM_USERS_REMIND_LIMIT_ERROR_N_HOURS',
$resetLimit));
return false;
}
// Set the confirmation token.
$token = JApplicationHelper::getHash(JUserHelper::genRandomPassword());
$hashedToken = JUserHelper::hashPassword($token);
$user->activation = $hashedToken;
// Save the user to the database.
if (!$user->save(true))
{
return new
JException(JText::sprintf('COM_USERS_USER_SAVE_FAILED',
$user->getError()), 500);
}
// Assemble the password reset confirmation link.
$mode = $config->get('force_ssl', 0) == 2 ? 1 : (-1);
$link =
'index.php?option=com_users&view=reset&layout=confirm&token='
. $token;
// Put together the email template data.
$data = $user->getProperties();
$data['fromname'] = $config->get('fromname');
$data['mailfrom'] = $config->get('mailfrom');
$data['sitename'] = $config->get('sitename');
$data['link_text'] = JRoute::_($link, false, $mode);
$data['link_html'] = JRoute::_($link, true, $mode);
$data['token'] = $token;
$subject = JText::sprintf(
'COM_USERS_EMAIL_PASSWORD_RESET_SUBJECT',
$data['sitename']
);
$body = JText::sprintf(
'COM_USERS_EMAIL_PASSWORD_RESET_BODY',
$data['sitename'],
$data['token'],
$data['link_text']
);
// Send the password reset request email.
$return = JFactory::getMailer()->sendMail($data['mailfrom'],
$data['fromname'], $user->email, $subject, $body);
// Check for an error.
if ($return !== true)
{
return new JException(JText::_('COM_USERS_MAIL_FAILED'), 500);
}
return true;
}
/**
* Method to check if user reset limit has been exceeded within the
allowed time period.
*
* @param JUser $user User doing the password reset
*
* @return boolean true if user can do the reset, false if limit exceeded
*
* @since 2.5
*/
public function checkResetLimit($user)
{
$params = JFactory::getApplication()->getParams();
$maxCount = (int) $params->get('reset_count');
$resetHours = (int) $params->get('reset_time');
$result = true;
$lastResetTime = strtotime($user->lastResetTime) ?: 0;
$hoursSinceLastReset = (strtotime(JFactory::getDate()->toSql()) -
$lastResetTime) / 3600;
if ($hoursSinceLastReset > $resetHours)
{
// If it's been long enough, start a new reset count
$user->lastResetTime = JFactory::getDate()->toSql();
$user->resetCount = 1;
}
elseif ($user->resetCount < $maxCount)
{
// If we are under the max count, just increment the counter
++$user->resetCount;
}
else
{
// At this point, we know we have exceeded the maximum resets for the
time period
$result = false;
}
return $result;
}
}
rules/loginuniquefield.php000064400000004126151165506420011762
0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('JPATH_PLATFORM') or die;
use Joomla\Registry\Registry;
/**
* JFormRule for com_users to be sure only one redirect login field has a
value
*
* @since 3.6
*/
class JFormRuleLoginUniqueField extends JFormRule
{
/**
* Method to test if two fields have a value in order to use only one
field.
* To use this rule, the form
* XML needs a validate attribute of loginuniquefield and a field
attribute
* that is equal to the field to test against.
*
* @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.
*
* @since 3.6
*/
public function test(SimpleXMLElement $element, $value, $group = null,
Registry $input = null, JForm $form = null)
{
$loginRedirectUrl =
$input['params']->login_redirect_url;
$loginRedirectMenuitem =
$input['params']->login_redirect_menuitem;
if ($form === null)
{
throw new InvalidArgumentException(sprintf('The value for $form
must not be null in %s', get_class($this)));
}
if ($input === null)
{
throw new InvalidArgumentException(sprintf('The value for $input
must not be null in %s', get_class($this)));
}
return true;
}
}
rules/logoutuniquefield.php000064400000004133151165506420012161
0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('JPATH_PLATFORM') or die;
use Joomla\Registry\Registry;
/**
* JFormRule for com_users to be sure only one redirect logout field has a
value
*
* @since 3.6
*/
class JFormRuleLogoutUniqueField extends JFormRule
{
/**
* Method to test if two fields have a value in order to use only one
field.
* To use this rule, the form
* XML needs a validate attribute of logoutuniquefield and a field
attribute
* that is equal to the field to test against.
*
* @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.
*
* @since 3.6
*/
public function test(SimpleXMLElement $element, $value, $group = null,
Registry $input = null, JForm $form = null)
{
$logoutRedirectUrl =
$input['params']->logout_redirect_url;
$logoutRedirectMenuitem =
$input['params']->logout_redirect_menuitem;
if ($form === null)
{
throw new InvalidArgumentException(sprintf('The value for $form
must not be null in %s', get_class($this)));
}
if ($input === null)
{
throw new InvalidArgumentException(sprintf('The value for $input
must not be null in %s', get_class($this)));
}
return true;
}
}
invoice.php000064400000017241151165531150006721 0ustar00<?php
/*------------------------------------------------------------------------
# com_invoices - Invoice Manager for Joomla
# ------------------------------------------------------------------------
# author Germinal Camps
# copyright Copyright (C) 2012 - 2016 JoomlaThat.com. All Rights
Reserved.
# @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.joomlathat.com
# Technical Support: Forum - http://www.joomlathat.com/support
-------------------------------------------------------------------------*/
//no direct access
defined('_JEXEC') or die('Restricted access.');
jimport('joomla.application.component.model');
class InvoicesModelInvoice extends JModelLegacy
{
function __construct()
{
parent::__construct();
$id = JRequest::getInt('id');
$this->setId((int)$id);
}
function setId($id)
{
// Set id and wipe data
$this->_id = $id;
$this->_data = null;
}
function &getData()
{
// Load the data
$query = ' SELECT i.* '.
' FROM #__invoices_invoices as i '.
' WHERE i.id = ' . $this->_id
;
$this->_db->setQuery( $query );
$this->_data = $this->_db->loadObject();
return $this->_data;
}
function &getTemplate()
{
$query = ' SELECT te.* '.
' FROM #__invoices_templates as te '.
' WHERE te.id = ' . $this->_data->template_id
;
$this->_db->setQuery( $query );
$this->template = $this->_db->loadObject();
return $this->template;
}
function &getItems()
{
$query = ' SELECT it.*, tax.name AS tax_name FROM #__invoices_items
AS it '.
' LEFT JOIN #__invoices_taxes AS tax ON tax.id = it.tax_id
'.
' WHERE it.invoice_id = ' . $this->_data->id .
' ORDER BY it.ordering ';
$this->_db->setQuery( $query );
$this->items = $this->_db->loadObjectList();
return $this->items;
}
function &getPayments()
{
$query = ' SELECT pa.* '.
' FROM #__invoices_payments as pa '.
' WHERE pa.invoice_id = ' . $this->_data->id .
' AND pa.payment_status = 1 '.
' ORDER BY ordering '
;
$this->_db->setQuery( $query );
$this->payments = $this->_db->loadObjectList();
return $this->payments;
}
function &getPayments2()
{
$query = ' SELECT pa.* '.
' FROM #__invoices_payments as pa '.
' WHERE pa.invoice_id = ' . $this->_data->id .
' AND pa.payment_status = 0 '.
' ORDER BY ordering '
;
$this->_db->setQuery( $query );
$this->payments2 = $this->_db->loadObjectList();
return $this->payments2;
}
function &getTaxes()
{
if($this->_data->taxes){
$query = ' SELECT tax.*, tai.value AS value '
.' FROM #__invoices_taxes AS tax '
.' LEFT JOIN #__invoices_tax_invoice AS tai ON (tai.tax_id =
tax.id AND tai.reference_id = ' . $this->_data->id . ' AND
tai.type = 1) '
.' WHERE tai.active = 1 '
.' ORDER BY ordering, name ' ;
$this->_db->setQuery( $query );
$this->taxes = $this->_db->loadObjectList();
}
return $this->taxes;
}
function store()
{
$row = $this->getTable();
$data = JRequest::get( 'post' );
// Bind the form fields to the album table
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}
if (!$row->store()) {
$this->setError( $this->_db->getErrorMsg() );
return false;
}
return $row->id;
}
function delete()
{
$id = JRequest::getInt( 'id' );
$row = $this->getTable();
if ( $id ) {
if (!$row->delete( $id )) {
$this->setError( $this->_db->getErrorMsg() );
return false;
}
}
return true;
}
function sendMail(){
$data = $this->getData();
$params = JComponentHelper::getParams( 'com_invoices' );
$from = $params->get('email_email') ;
$from_name = $params->get('email_name') ;
$subject = $params->get('email_subject') ;
if($data->type == 2){//quote
$subject = $params->get('email_subject_quote') ;
}
$subject = str_replace("{invoice_num}", $data->invoice_num,
$subject) ;
$view = $this->getInvoiceView();
$view->invoice = $data;
$view->template = $this->getTemplate();
$view->items = $this->getItems();
$view->taxes = $this->getTaxes();
$view->payments = $this->getPayments();
$view->payments2 = $this->getPayments2();
$view->params = $params;
if($view->template->content_email) $view->template->content =
$view->template->content_email ;
$view->_path['template'][1] =
JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'tmpl'
;
$plantilla = 'email' ;
$message = $view->loadTemplate( $plantilla );
$styles =
"<style>".$view->template->styles."</style>"
;
$message = $styles . $message ;
$to = $data->to_email;
$toBlock = str_replace(" ", "", $to); //Delete spaces
between emails
$toMails = explode(",", $toBlock);
$mail = JFactory::getMailer();
$mail->addRecipient($toMails);
$mail->setsender(array($from, $from_name));
$mail->setSubject($subject);
$mail->setbody($message);
$mail->isHTML(true);
if($params->get('pdfemail') &&
InvoicesHelper::PDFavailable()){
//create PDF
$viewpdf = $this->getInvoiceView('dompdf');
$viewpdf->invoice = $view->invoice ;
$viewpdf->template = $this->getTemplate();
$viewpdf->items = $view->items ;
$viewpdf->taxes = $view->taxes ;
$viewpdf->payments = $view->payments;
$viewpdf->payments2 = $view->payments2;
$viewpdf->params = $params;
if($viewpdf->template->content_pdf)
$viewpdf->template->content = $viewpdf->template->content_pdf ;
$viewpdf->_path['template'][1] =
JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'tmpl'
;
if($viewpdf->invoice->invoice_num) $pdfname =
$viewpdf->invoice->invoice_num;
else $pdfname = rand();
$location =
JPATH_SITE.DS.$params->get('pdffolder','pdfinvoices').DS.$pdfname
. ".pdf" ;
$pdf = InvoicesHelper::storepdf($location, $viewpdf);
if($pdf) $mail->addAttachment($location,
$viewpdf->invoice->invoice_num . ".pdf") ;
}
$sent = $mail->Send();
if($sent && $to){
InvoicesHelper::updateSentDate($data->id);
//trigger event
$import = JPluginHelper::importPlugin( 'invoices' );
$dispatcher = JDispatcher::getInstance();
$dispatcher->trigger( 'onAfterSendInvoice', array( $data )
);
}
return $sent ;
}
function getInvoiceView($type = "html")
{
if (!class_exists( 'InvoicesViewInvoice' ))
{
// Build the path to the model based upon a supplied base path
$path =
JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'view.'.$type.'.php';
$false = false;
// If the model file exists include it and try to instantiate the object
if (file_exists( $path )) {
require_once( $path );
if (!class_exists( 'InvoicesViewInvoice' )) {
JError::raiseWarning( 0, 'View class InvoicesViewInvoice not
found in file.' );
return $false;
}
} else {
JError::raiseWarning( 0, 'View InvoicesViewInvoice not supported.
File not found.' );
return $false;
}
}
$view = new InvoicesViewInvoice();
return $view;
}
function accept_quote(){
$query = ' UPDATE #__invoices_invoices SET status =
"accepted_client" WHERE id = '. $this->_id ;
$this->_db->setQuery($query);
$this->_db->query();
$import = JPluginHelper::importPlugin( 'invoices' );
$dispatcher = JDispatcher::getInstance();
$dispatcher->trigger( 'onAcceptQuote', array( $this->_id
) );
return true;
}
function reject_quote(){
$query = ' UPDATE #__invoices_invoices SET status =
"rejected_client" WHERE id = '. $this->_id ;
$this->_db->setQuery($query);
$this->_db->query();
$import = JPluginHelper::importPlugin( 'invoices' );
$dispatcher = JDispatcher::getInstance();
$dispatcher->trigger( 'onRejectQuote', array( $this->_id
) );
return true;
}
}
invoices.php000064400000016465151165531150007113 0ustar00<?php
/*------------------------------------------------------------------------
# com_invoices - Invoice Manager for Joomla
# ------------------------------------------------------------------------
# author Germinal Camps
# copyright Copyright (C) 2012 - 2016 JoomlaThat.com. All Rights
Reserved.
# @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.joomlathat.com
# Technical Support: Forum - http://www.joomlathat.com/support
-------------------------------------------------------------------------*/
//no direct access
defined('_JEXEC') or die('Restricted access.');
jimport('joomla.application.component.model');
class InvoicesModelInvoices extends JModelLegacy
{
function __construct()
{
parent::__construct();
$mainframe = JFactory::getApplication();
$params = JComponentHelper::getParams( 'com_invoices' );
$this->params = $params ;
$this->keywords = JRequest::getVar('searchword');
$this->orderby = JRequest::getVar('orderby');
$date_in =
$mainframe->getUserStateFromRequest('invoices.date_in','date_in','','date_in');
$date_out =
$mainframe->getUserStateFromRequest('invoices.date_out','date_out','','date_out');
$default_list_limit = 30 ;
// Get pagination request variables
$limit =
$mainframe->getUserStateFromRequest('invoices.items.limit',
'limit', $default_list_limit, 'int');
//$limitstart =
$mainframe->getUserStateFromRequest('muscol.search.limitstart',
'limitstart', 0, 'int');
$limitstart = JRequest::getVar('limitstart',0);
// In case limit has been changed, adjust it
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('date_in', $date_in);
$this->setState('date_out', $date_out);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
function getTotal(){
// Load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
function getDateIn(){
if (empty($this->date_in)) {
$this->date_in = $this->getState('date_in') ;
}
return $this->date_in;
}
function getDateOut(){
if (empty($this->date_out)) {
$this->date_out = $this->getState('date_out') ;
}
return $this->date_out;
}
function getPagination()
{
// Load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(),
$this->getState('limitstart'),
$this->getState('limit') );
}
return $this->_pagination;
}
function _buildContentOrderBy(){
$mainframe = JFactory::getApplication();
$filter_order = $mainframe->getUserStateFromRequest(
'invoices.items.order', 'filter_order',
'i.invoice_date', 'cmd' );
$filter_order_Dir = $mainframe->getUserStateFromRequest(
'invoices.items.order_Dir', 'filter_order_Dir',
'desc', 'word' );
if(!$filter_order) $filter_order = "i.invoice_date";
if(!$filter_order_Dir) $filter_order_Dir = "desc";
$orderby = ' ORDER BY '.$filter_order.'
'.$filter_order_Dir ;
$orderby .= ' , i.id DESC ' ;
return $orderby;
}
function _buildQuery($type = 1){
$user = JFactory::getUser();
//echo $user->id; die();
$keywords = $this->keywords;
$date_in = $this->getDateIn();
$date_out = $this->getDateOut();
$where_clause = array();
if ($keywords != "") $where_clause[] = ' ( i.notes LIKE
"%'.$keywords.'%" OR i.invoice_num LIKE
"%'.$keywords.'%" )';
if ($date_in) {
$where_clause[] = ' i.invoice_date >= "'. $date_in
.'" ' ;
}
if ($date_out) {
$where_clause[] = ' i.invoice_date <= "'. $date_out
.' 23:59:59" ' ;
}
$now = date('Y-m-d H:i:s') ;
$where_clause[] = ' u.id = ' . $user->id ;
$where_clause[] = ' ( i.start_publish <= "'. $now
.'" OR i.start_publish = "0000-00-00 00:00:00") '
;
$where_clause[] = ' ( i.end_publish >= "'. $now
.'" OR i.end_publish = "0000-00-00 00:00:00") ' ;
$where_clause[] = ' i.publish = 1 ' ;
if($user->id) $where_clause[] = ' u.id = ' . $user->id ;
else $where_clause[] = ' 1 = 0 '; //return nothing
$where_clause[] = ' i.type = '. $type ;
// Build the where clause of the content record query
$where = (count($where_clause) ? ' WHERE '.implode(' AND
', $where_clause) : '');
$order = $this->_buildContentOrderBy();
$this->query = ' SELECT i.*, u.name as username, co.name as
contact_name, co.user_id as joomla_user_id '
.' FROM #__invoices_invoices as i '
.' LEFT JOIN #__invoices_contacts as co ON co.id = i.user_id '
.' LEFT JOIN #__users as u ON u.id = co.user_id '
.$where
.' GROUP BY i.id '
.$order
;
return $this->query;
}
function getData(){
if (empty( $this->_data )) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query,
$this->getState('limitstart'),
$this->getState('limit'));
for($i = 0; $i < count($this->_data) ; $i++){
$row =& $this->_data[$i] ;
$row->subtotal = InvoicesHelper::get_subtotal($row->id);
$row->subtotal_items =
InvoicesHelper::get_subtotal_items($row->id);
$row->display_taxes = InvoicesHelper::get_display_taxes($row);
$row->total = InvoicesHelper::get_total($row);
$row->subtotal = $row->subtotal_items ;
//the payments
$query = ' SELECT pa.* ' .
' FROM #__invoices_payments as pa '.
' WHERE pa.invoice_id = ' . $this->_data[$i]->id .
' ORDER BY ordering, pa.payment_duedate '
;
$this->_db->setQuery($query);
$this->_data[$i]->payments = $this->_db->loadObjectList() ;
//payments
$query = ' SELECT SUM(pa.payment_amount) AS total_paid,
COUNT(DISTINCT pa.id) AS paid_payments FROM #__invoices_payments AS pa
WHERE pa.invoice_id = '.$this->_data[$i]->id.' AND
pa.payment_status = 1 ' ;
$this->_db->setQuery($query);
$paid_temp = $this->_db->loadObject();
$this->_data[$i]->total_paid = $paid_temp->total_paid;
$this->_data[$i]->paid_payments = $paid_temp->paid_payments;
$query = ' SELECT SUM(pa.payment_amount) AS total_unpaid,
COUNT(DISTINCT pa.id) AS unpaid_payments FROM #__invoices_payments AS pa
WHERE pa.invoice_id = '.$this->_data[$i]->id.' AND
pa.payment_status = 0 ' ;
$this->_db->setQuery($query);
$unpaid_temp = $this->_db->loadObject();
$this->_data[$i]->total_unpaid = $unpaid_temp->total_unpaid;
$this->_data[$i]->unpaid_payments =
$unpaid_temp->unpaid_payments;
$query = ' SELECT SUM(pa.payment_amount) AS total_unpaid_ontime,
COUNT(DISTINCT pa.id) AS unpaid_payments_ontime FROM #__invoices_payments
AS pa WHERE pa.invoice_id = '.$this->_data[$i]->id.' AND
pa.payment_status = 0 AND (pa.payment_duedate > NOW() OR
pa.payment_duedate = "0000-00-00 00:00:00") ' ;
$this->_db->setQuery($query);
$unpaidontime_temp = $this->_db->loadObject();
$this->_data[$i]->total_unpaid_ontime =
$unpaidontime_temp->total_unpaid_ontime;
$this->_data[$i]->unpaid_payments_ontime =
$unpaidontime_temp->unpaid_payments_ontime;
}
}
return $this->_data;
}
function getQuotes(){
if (empty( $this->quotes )) {
$query = $this->_buildQuery(2);
$this->quotes = $this->_getList($query,
$this->getState('limitstart'),
$this->getState('limit'));
for($i = 0; $i < count($this->quotes) ; $i++){
$this->quotes[$i]->subtotal =
InvoicesHelper::get_subtotal($this->quotes[$i]->id);
$this->quotes[$i]->total =
InvoicesHelper::get_total($this->quotes[$i]);
}
}
return $this->quotes;
}
}
payment.php000064400000007175151165531150006747 0ustar00<?php
/*------------------------------------------------------------------------
# com_invoices - Invoice Manager for Joomla
# ------------------------------------------------------------------------
# author Germinal Camps
# copyright Copyright (C) 2012 - 2016 JoomlaThat.com. All Rights
Reserved.
# @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.joomlathat.com
# Technical Support: Forum - http://www.joomlathat.com/support
-------------------------------------------------------------------------*/
//no direct access
defined('_JEXEC') or die('Restricted access.');
jimport('joomla.application.component.model');
class InvoicesModelPayment extends JModelLegacy
{
function __construct()
{
parent::__construct();
$id = JRequest::getVar('id');
$this->setId((int)$id);
}
function setId($id)
{
// Set id and wipe data
$this->_id = $id;
$this->_data = null;
}
function &getData()
{
// Load the data
$query = ' SELECT pa.*, i.*, pa.id AS id, u.username, u.name AS
theusername '.
' FROM #__invoices_payments AS pa '.
' LEFT JOIN #__invoices_invoices AS i ON i.id = pa.invoice_id
'.
' LEFT JOIN #__invoices_contacts AS co ON co.id = i.user_id
'.
' LEFT JOIN #__users AS u ON u.id = co.user_id '.
' WHERE pa.id = ' . $this->_id
;
$this->_db->setQuery( $query );
$this->_data = $this->_db->loadObject();
//$this->_data->taxes = explode(",",
$this->_data->taxes );
return $this->_data;
}
function sendMail(){
$data = $this->getData();
$params = JComponentHelper::getParams( 'com_invoices' );
$from = $params->get('email_email') ;
$from_name = $params->get('email_name') ;
$subject = $params->get('email_subject_payment') ;
$view = $this->getPaymentView();
$view->payment = $this->getData();
$view->params = $params;
$view->_path['template'][1] =
JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'payment'.DS.'tmpl'
;
$plantilla = 'email' ;
//email to the admin
$view->payment->towho = "admin" ;
$message = $view->loadTemplate( $plantilla );
$to = $from;
jimport('joomla.mail.mail');
$mail = JFactory::getMailer();
$mail->setsender(array($from, $from_name));
$mail->addRecipient($to);
$mail->setSubject($subject);
$mail->setbody($message);
$mail->isHTML(true);
$success = $mail->Send();
//email to the user
$view->payment->towho = "user" ;
$message = $view->loadTemplate( $plantilla );
$to = $view->payment->to_email;
$toBlock = str_replace(" ", "", $to); //Delete spaces
between emails
$toMails = explode(",", $toBlock);
$mail = JFactory::getMailer();
$mail->setsender(array($from, $from_name));
$mail->addRecipient($toMails);
$mail->setSubject($subject);
$mail->setbody($message);
$mail->isHTML(true);
$success2 = $mail->Send();
if($success && $success2) return true;
else return false;
}
function getPaymentView()
{
if (!class_exists( 'InvoicesViewPayment' ))
{
// Build the path to the model based upon a supplied base path
$path =
JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'payment'.DS.'view.html.php';
$false = false;
// If the model file exists include it and try to instantiate the object
if (file_exists( $path )) {
require_once( $path );
if (!class_exists( 'InvoicesViewPayment' )) {
JError::raiseWarning( 0, 'View class InvoicesViewPayment not
found in file.' );
return $false;
}
} else {
JError::raiseWarning( 0, 'View InvoicesViewPayment not supported.
File not found.' );
return $false;
}
}
$view = new InvoicesViewPayment();
return $view;
}
}list.php000064400000012716151165627430006251 0ustar00<?php
/**
* @package Joomla.Administrator
* @subpackage com_media
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
/**
* Media Component List Model
*
* @since 1.5
*/
class MediaModelList extends JModelLegacy
{
/**
* Method to get model state variables
*
* @param string $property Optional parameter name
* @param mixed $default Optional default value
*
* @return object The property where specified, the state object where
omitted
*
* @since 1.5
*/
public function getState($property = null, $default = null)
{
static $set;
if (!$set)
{
$input = JFactory::getApplication()->input;
$folder = $input->get('folder', '',
'path');
$this->setState('folder', $folder);
$parent = str_replace("\\", '/', dirname($folder));
$parent = ($parent == '.') ? null : $parent;
$this->setState('parent', $parent);
$set = true;
}
return parent::getState($property, $default);
}
/**
* Get the images on the current folder
*
* @return array
*
* @since 1.5
*/
public function getImages()
{
$list = $this->getList();
return $list['images'];
}
/**
* Get the folders on the current folder
*
* @return array
*
* @since 1.5
*/
public function getFolders()
{
$list = $this->getList();
return $list['folders'];
}
/**
* Get the documents on the current folder
*
* @return array
*
* @since 1.5
*/
public function getDocuments()
{
$list = $this->getList();
return $list['docs'];
}
/**
* Build imagelist
*
* @return array
*
* @since 1.5
*/
public function getList()
{
static $list;
// Only process the list once per request
if (is_array($list))
{
return $list;
}
// Get current path from request
$current = (string) $this->getState('folder');
$basePath = COM_MEDIA_BASE . ((strlen($current) > 0) ? '/'
. $current : '');
$mediaBase = str_replace(DIRECTORY_SEPARATOR, '/',
COM_MEDIA_BASE . '/');
// Reset base path
if (strpos(realpath($basePath), JPath::clean(realpath(COM_MEDIA_BASE)))
!== 0)
{
$basePath = COM_MEDIA_BASE;
}
$images = array ();
$folders = array ();
$docs = array ();
$videos = array ();
$fileList = false;
$folderList = false;
if (file_exists($basePath))
{
// Get the list of files and folders from the given folder
$fileList = JFolder::files($basePath);
$folderList = JFolder::folders($basePath);
}
// Iterate over the files if they exist
if ($fileList !== false)
{
$tmpBaseObject = new JObject;
foreach ($fileList as $file)
{
if (is_file($basePath . '/' . $file) && substr($file,
0, 1) != '.' && strtolower($file) !==
'index.html')
{
$tmp = clone $tmpBaseObject;
$tmp->name = $file;
$tmp->title = $file;
$tmp->path = str_replace(DIRECTORY_SEPARATOR, '/',
JPath::clean($basePath . '/' . $file));
$tmp->path_relative = str_replace($mediaBase, '',
$tmp->path);
$tmp->size = filesize($tmp->path);
$ext = strtolower(JFile::getExt($file));
switch ($ext)
{
// Image
case 'jpg':
case 'png':
case 'gif':
case 'xcf':
case 'odg':
case 'bmp':
case 'jpeg':
case 'ico':
$info = @getimagesize($tmp->path);
$tmp->width = @$info[0];
$tmp->height = @$info[1];
$tmp->type = @$info[2];
$tmp->mime = @$info['mime'];
if (($info[0] > 60) || ($info[1] > 60))
{
$dimensions = MediaHelper::imageResize($info[0], $info[1], 60);
$tmp->width_60 = $dimensions[0];
$tmp->height_60 = $dimensions[1];
}
else
{
$tmp->width_60 = $tmp->width;
$tmp->height_60 = $tmp->height;
}
if (($info[0] > 16) || ($info[1] > 16))
{
$dimensions = MediaHelper::imageResize($info[0], $info[1], 16);
$tmp->width_16 = $dimensions[0];
$tmp->height_16 = $dimensions[1];
}
else
{
$tmp->width_16 = $tmp->width;
$tmp->height_16 = $tmp->height;
}
$images[] = $tmp;
break;
// Video
case 'mp4':
$tmp->icon_32 = 'media/mime-icon-32/' . $ext .
'.png';
$tmp->icon_16 = 'media/mime-icon-16/' . $ext .
'.png';
$videos[] = $tmp;
break;
// Non-image document
default:
$tmp->icon_32 = 'media/mime-icon-32/' . $ext .
'.png';
$tmp->icon_16 = 'media/mime-icon-16/' . $ext .
'.png';
$docs[] = $tmp;
break;
}
}
}
}
// Iterate over the folders if they exist
if ($folderList !== false)
{
$tmpBaseObject = new JObject;
foreach ($folderList as $folder)
{
$tmp = clone $tmpBaseObject;
$tmp->name = basename($folder);
$tmp->path = str_replace(DIRECTORY_SEPARATOR, '/',
JPath::clean($basePath . '/' . $folder));
$tmp->path_relative = str_replace($mediaBase, '',
$tmp->path);
$count = MediaHelper::countFiles($tmp->path);
$tmp->files = $count[0];
$tmp->folders = $count[1];
$folders[] = $tmp;
}
}
$list = array('folders' => $folders, 'docs' =>
$docs, 'images' => $images, 'videos' => $videos);
return $list;
}
/**
* Get the videos on the current folder
*
* @return array
*
* @since 3.5
*/
public function getVideos()
{
$list = $this->getList();
return $list['videos'];
}
}
manager.php000064400000011035151165627430006701 0ustar00<?php
/**
* @package Joomla.Administrator
* @subpackage com_media
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Media Component Manager Model
*
* @since 1.5
*/
class MediaModelManager extends JModelLegacy
{
/**
* Method to get model state variables
*
* @param string $property Optional parameter name
* @param mixed $default Optional default value
*
* @return object The property where specified, the state object where
omitted
*
* @since 1.5
*/
public function getState($property = null, $default = null)
{
static $set;
if (!$set)
{
$input = JFactory::getApplication()->input;
$folder = $input->get('folder', '',
'path');
$this->setState('folder', $folder);
$fieldid = $input->get('fieldid', '');
$this->setState('field.id', $fieldid);
$parent = str_replace("\\", '/', dirname($folder));
$parent = ($parent == '.') ? null : $parent;
$this->setState('parent', $parent);
$set = true;
}
return parent::getState($property, $default);
}
/**
* Get a select field with a list of available folders
*
* @param string $base The image directory to display
*
* @return html
*
* @since 1.5
*/
public function getFolderList($base = null)
{
// Get some paths from the request
if (empty($base))
{
$base = COM_MEDIA_BASE;
}
// Corrections for windows paths
$base = str_replace(DIRECTORY_SEPARATOR, '/', $base);
$com_media_base_uni = str_replace(DIRECTORY_SEPARATOR, '/',
COM_MEDIA_BASE);
// Get the list of folders
jimport('joomla.filesystem.folder');
$folders = JFolder::folders($base, '.', true, true);
$document = JFactory::getDocument();
$document->setTitle(JText::_('COM_MEDIA_INSERT_IMAGE'));
// Build the array of select options for the folder list
$options[] = JHtml::_('select.option', '',
'/');
foreach ($folders as $folder)
{
$folder = str_replace($com_media_base_uni, '',
str_replace(DIRECTORY_SEPARATOR, '/', $folder));
$value = substr($folder, 1);
$text = str_replace(DIRECTORY_SEPARATOR, '/', $folder);
$options[] = JHtml::_('select.option', $value, $text);
}
// Sort the folder list array
if (is_array($options))
{
sort($options);
}
// Get asset and author id (use integer filter)
$input = JFactory::getApplication()->input;
$asset = $input->get('asset', 0, 'integer');
// For new items the asset is a string. JAccess always checks type first
// so both string and integer are supported.
if ($asset == 0)
{
$asset =
htmlspecialchars(json_encode(trim($input->get('asset', 0,
'cmd'))), ENT_COMPAT, 'UTF-8');
}
$author = $input->get('author', 0, 'integer');
// Create the dropdown folder select list
$attribs = 'size="1"
onchange="ImageManager.setFolder(this.options[this.selectedIndex].value,
' . $asset . ', ' . $author . ')" ';
$list = JHtml::_('select.genericlist', $options,
'folderlist', $attribs, 'value', 'text',
$base);
return $list;
}
/**
* Get the folder tree
*
* @param mixed $base Base folder | null for using base media folder
*
* @return array
*
* @since 1.5
*/
public function getFolderTree($base = null)
{
// Get some paths from the request
if (empty($base))
{
$base = COM_MEDIA_BASE;
}
$mediaBase = str_replace(DIRECTORY_SEPARATOR, '/',
COM_MEDIA_BASE . '/');
// Get the list of folders
jimport('joomla.filesystem.folder');
$folders = JFolder::folders($base, '.', true, true);
$tree = array();
foreach ($folders as $folder)
{
$folder = str_replace(DIRECTORY_SEPARATOR, '/', $folder);
$name = substr($folder, strrpos($folder, '/') + 1);
$relative = str_replace($mediaBase, '', $folder);
$absolute = $folder;
$path = explode('/', $relative);
$node = (object) array('name' => $name,
'relative' => $relative, 'absolute' =>
$absolute);
$tmp = &$tree;
for ($i = 0, $n = count($path); $i < $n; $i++)
{
if (!isset($tmp['children']))
{
$tmp['children'] = array();
}
if ($i == $n - 1)
{
// We need to place the node
$tmp['children'][$relative] = array('data' =>
$node, 'children' => array());
break;
}
if (array_key_exists($key = implode('/', array_slice($path,
0, $i + 1)), $tmp['children']))
{
$tmp = &$tmp['children'][$key];
}
}
}
$tree['data'] = (object) array('name' =>
JText::_('COM_MEDIA_MEDIA'), 'relative' =>
'', 'absolute' => $base);
return $tree;
}
}
forms/mailto.xml000064400000001532151165727450007717 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>
mailto.php000064400000005240151165727450006560 0ustar00<?php
/**
* @package Joomla.Site
* @subpackage com_users
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All
rights reserved.
* @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;
}
}
properties.php000064400000030251151166762230007463 0ustar00<?php
/**
* This file is part of Joomla Estate Agency - Joomla! extension for real
estate agency
*
* @package Joomla.Site
* @subpackage com_jea
* @copyright Copyright (C) 2008 - 2020 PHILIP Sylvain. All rights
reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\Utilities\ArrayHelper;
/**
* Properties model class.
*
* @package Joomla.Site
* @subpackage com_jea
*
* @see JModelList
*
* @since 2.0
*/
class JeaModelProperties extends JModelList
{
/**
* Model context string.
*
* @var string
*/
protected $context = 'com_jea.properties';
/**
* Filters and their default values used in the query
*
* @var array
*/
protected $filters = array(
'search' => '',
'transaction_type' => '',
'type_id' => 0,
'department_id' => 0,
'town_id' => 0,
'area_id' => 0,
'zip_codes' => '',
'budget_min' => 0,
'budget_max' => 0,
'living_space_min' => 0,
'living_space_max' => 0,
'land_space_min' => 0,
'land_space_max' => 0,
'rooms_min' => 0,
'bedrooms_min' => 0,
'bathrooms_min' => 0,
'floor' => '',
'hotwatertype' => 0,
'heatingtype' => 0,
'condition' => 0,
'orientation' => 0,
'amenities' => array()
);
/**
* Constructor.
*
* @param array $config An optional associative array of configuration
settings.
*
* @see JModelList
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
// This fields concern the ordering
$config['filter_fields'] = array(
'p.id',
'p.price',
'p.created',
'p.ordering',
'p.living_space',
'p.land_space',
'p.hits',
'p.ref',
'type',
'departement',
'town',
'area'
);
}
// Add a context by Itemid
$itemId =
JFactory::getApplication()->input->getInt('Itemid', 0);
if ($itemId > 0)
{
$this->context .= '.menuitem' . $itemId;
}
parent::__construct($config);
}
/**
* Overrides parent method
*
* @param string $ordering An optional ordering field.
* @param string $direction An optional direction (asc|desc).
*
* @return void
*
* @see JModelList::populateState()
*/
protected function populateState($ordering = null, $direction = null)
{
$app = JFactory::getApplication('site');
// Load the parameters.
$params = $app->getParams();
$this->setState('params', $params);
$searchContext = false;
foreach ($this->filters as $name => $defaultValue)
{
$state = $this->getUserStateFromRequest($this->context .
'.filter.' . $name, 'filter_' . $name, $defaultValue,
'none', false);
if (! $searchContext && ! empty($state))
{
/*
This flag indiquate that some filters are set by an user, so the
context is a search.
* It will be usefull in the view to retrieve this flag.
*/
$searchContext = true;
}
else
{
// Get component menuitem parameters
$state2 = $params->get('filter_' . $name, $defaultValue);
if (! empty($state2))
{
$state = $state2;
}
}
// If the state is an array, check if it not contains only a zero value
if (is_array($state) && in_array(0, $state))
{
$key = array_search(0, $state);
unset($state[$key]);
}
$this->setState('filter.' . $name, $state);
}
$this->setState('filter.language',
$app->getLanguageFilter());
$this->setState('searchcontext', $searchContext);
// List state information
$limit = $this->getUserStateFromRequest($this->context .
'.filter.limit', 'limit',
$params->get('list_limit', 10), 'uint');
$this->setState('list.limit', $limit);
$orderCol = $app->getUserStateFromRequest($this->context .
'.ordercol', 'filter_order', $ordering);
if ($orderCol)
{
$this->setState('list.ordering', $orderCol);
}
$orderDirn = $app->getUserStateFromRequest($this->context .
'.orderdirn', 'filter_order_Dir', $direction);
if ($orderDirn)
{
$this->setState('list.direction', $orderDirn);
}
$value = $app->input->get('limitstart', 0,
'uint');
$limitstart = ($limit != 0 ? (floor($value / $limit) * $limit) : 0);
$this->setState('list.start', $limitstart);
}
/**
* Return the model filters
*
* @return array
*/
public function getFilters()
{
return $this->filters;
}
/**
* Overrides parent method
*
* @return JDatabaseQuery A JDatabaseQuery object to retrieve the data
set.
*
* @see JModelList::getListQuery()
*/
protected function getListQuery()
{
$dispatcher = JDispatcher::getInstance();
// Include the jea plugins for the onBeforeSearchQuery event.
JPluginHelper::importPlugin('jea');
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('p.*');
$query->from('#__jea_properties AS p');
// Join properties types
$query->select('t.value AS `type`');
$query->join('LEFT', '#__jea_types AS t ON t.id =
p.type_id');
// Join departments
$query->select('d.value AS department');
$query->join('LEFT', '#__jea_departments AS d ON d.id =
p.department_id');
// Join towns
$query->select('town.value AS town');
$query->join('LEFT', '#__jea_towns AS town ON town.id =
p.town_id');
// Join areas
$query->select('area.value AS area');
$query->join('LEFT', '#__jea_areas AS area ON area.id =
p.area_id');
// Join conditions
$query->select('c.value AS `condition`');
$query->join('LEFT', '#__jea_conditions AS c ON c.id =
p.condition_id');
// Join users
$query->select('u.username AS author');
$query->join('LEFT', '#__users AS u ON u.id =
p.created_by');
// Join slogans
$query->select('s.value AS slogan');
$query->join('LEFT', '#__jea_slogans AS s ON s.id =
p.slogan_id');
if ($this->getState('manage') == true)
{
$lang = $this->getUserStateFromRequest($this->context .
'.filter.language', 'filter_language', '');
if ($lang)
{
$query->where('p.language =' .
$db->Quote($db->escape($lang)));
}
$this->setState('filter.language', $lang);
$user = JFactory::getUser();
$canEdit = $user->authorise('core.edit',
'com_jea');
$canEditOwn = $user->authorise('core.edit.own',
'com_jea');
if (!$canEdit && $canEditOwn)
{
// Get only the user properties
$query->where('p.created_by =' . (int) $user->id);
}
if (!$canEditOwn)
{
throw new
\RuntimeException(JText::_('JERROR_ALERTNOAUTHOR'));
}
}
else
{
if ($this->getState('filter.language'))
{
$query->where('p.language in (' .
$db->quote(JFactory::getLanguage()->getTag()) . ',' .
$db->quote('*') . ')');
}
$query->where('p.published=1');
// Filter by access level
$user = JFactory::getUser();
$groups = implode(',', $user->getAuthorisedViewLevels());
$query->where('p.access IN (' . $groups . ')');
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toSql());
$query->where('(p.publish_up = ' . $nullDate . ' OR
p.publish_up <= ' . $nowDate . ')');
$query->where('(p.publish_down = ' . $nullDate . ' OR
p.publish_down >= ' . $nowDate . ')');
}
// Filter by search
if ($value = $this->getState('filter.search'))
{
$value = $db->Quote('%' . $db->escape($value, true) .
'%');
$search = '(p.ref LIKE ' . $value . ' OR p.title LIKE
' . $value . ')';
$query->where($search);
}
// Filter by transaction type
if ($value = $this->getState('filter.transaction_type'))
{
$query->where('p.transaction_type =' .
$db->Quote($db->escape($value)));
}
// Filter by property type
if ($value = $this->getState('filter.type_id'))
{
if (is_array($value))
{
$value = ArrayHelper::toInteger($value);
$query->where('p.type_id IN(' . implode(',',
$value) . ')');
}
else
{
$query->where('p.type_id =' . (int) $value);
}
}
// Filter by departments
if ($value = $this->getState('filter.department_id'))
{
$query->where('p.department_id =' . (int) $value);
}
// Filter by town
if ($value = $this->getState('filter.town_id'))
{
$query->where('p.town_id =' . (int) $value);
}
// Filter by area
if ($value = $this->getState('filter.area_id'))
{
$query->where('p.area_id =' . (int) $value);
}
// Filter by zip codes
if ($value = $this->getState('filter.zip_codes'))
{
$zip_codes = explode(',', $value);
foreach ($zip_codes as &$v)
{
$v = $db->Quote($db->escape(trim($v)));
}
$query->where('p.zip_code IN(' . implode(',',
$zip_codes) . ')');
}
// Filter by budget min
if ($value = $this->getState('filter.budget_min'))
{
$query->where('p.price >=' . (int) $value);
}
// Filter by budget max
if ($value = $this->getState('filter.budget_max'))
{
$query->where('p.price <=' . (int) $value);
}
// Filter by living space min
if ($value = $this->getState('filter.living_space_min'))
{
$query->where('p.living_space >=' . (int) $value);
}
// Filter by living space max
if ($value = $this->getState('filter.living_space_max'))
{
$query->where('p.living_space <=' . (int) $value);
}
// Filter by land space min
if ($value = $this->getState('filter.land_space_min'))
{
$query->where('p.land_space >=' . (int) $value);
}
// Filter by land space max
if ($value = $this->getState('filter.land_space_max'))
{
$query->where('p.land_space <=' . (int) $value);
}
// Filter by rooms min
if ($value = $this->getState('filter.rooms_min'))
{
$query->where('p.rooms >=' . (int) $value);
}
// Filter by bedrooms
if ($value = $this->getState('filter.bedrooms_min'))
{
$query->where('p.bedrooms >=' . (int) $value);
}
// Filter by bathrooms
if ($value = $this->getState('filter.bathrooms_min'))
{
$query->where('p.bathrooms >=' . (int) $value);
}
// Filter by floor
// 0 is a valid value as it corresponds to ground floor
if ($value = $this->getState('filter.floor') !=
'')
{
$query->where('p.floor =' . (int) $value);
}
// Filter by hot water type
if ($value = $this->getState('filter.hotwatertype'))
{
$query->where('p.hot_water_type =' . (int) $value);
}
// Filter by heating type condition
if ($value = $this->getState('filter.heatingtype'))
{
$query->where('p.heating_type =' . (int) $value);
}
// Filter by condition
if ($value = $this->getState('filter.condition'))
{
$query->where('p.condition_id =' . (int) $value);
}
// Filter by orientation
if ($value = $this->getState('filter.orientation'))
{
$query->where('p.orientation =' .
$db->Quote($db->escape($value)));
}
// Filter by amenities
if ($value = $this->getState('filter.amenities'))
{
$amenities = ArrayHelper::toInteger((array) $value);
foreach ($amenities as $id)
{
if ($id > 0)
{
$query->where("p.amenities LIKE '%-{$id}-%'");
}
}
}
// Add the list ordering clause.
$params = $this->state->get('params');
if ($params != null)
{
$orderCol = $this->state->get('list.ordering',
$params->get('orderby', 'p.id'));
$orderDirn = $this->state->get('list.direction',
$params->get('orderby_direction', 'DESC'));
}
else
{
$orderCol = $this->state->get('list.ordering',
'p.id');
$orderDirn = $this->state->get('list.direction',
'DESC');
}
$query->order($db->escape($orderCol . ' ' . $orderDirn));
$dispatcher->trigger('onBeforeSearch', array(&$query,
&$this->state));
return $query;
}
/**
* Retrieve the list of items which can be managed
*
* @return multitype:array|boolean
*/
public function getMyItems()
{
$this->setState('manage', true);
return $this->getItems();
}
/**
* Return the min max values for a column
*
* @param string $fieldName The column name
* @param string $transaction_type Optional transaction type to filter
on
*
* @return integer[]
*/
public function getFieldLimit($fieldName = '', $transaction_type
= '')
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$col = '`' . $db->escape($fieldName) . '`';
$query->select("MIN($col) AS min_value, MAX($col) AS
max_value");
$query->from('#__jea_properties');
if ($transaction_type)
{
$query->where('transaction_type =' .
$db->Quote($db->escape($transaction_type)));
}
$db->setQuery($query);
$row = $db->loadObject();
if (empty($row))
{
return array(0, 0);
}
return array((int) $row->min_value, (int) $row->max_value);
}
}
property.php000064400000024223151166762230007155 0ustar00<?php
/**
* This file is part of Joomla Estate Agency - Joomla! extension for real
estate agency
*
* @package Joomla.Site
* @subpackage com_jea
* @copyright Copyright (C) 2008 - 2020 PHILIP Sylvain. All rights
reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\CMS\Mail\MailHelper;
/**
* Property model class.
*
* @package Joomla.Site
* @subpackage com_jea
*
* @see JModelLegacy
*
* @since 2.0
*/
class JeaModelProperty extends JModelLegacy
{
/**
* Overrides parent method
*
* @return void
*
* @see JModelLegacy::populateState()
*/
protected function populateState()
{
$app = JFactory::getApplication('site');
$this->setState('property.id',
$app->input->get('id', 0, 'int'));
// Load the parameters.
$params = $app->getParams();
$this->setState('params', $params);
// Load the contact form informations
$this->setState('contact.name',
$app->getUserStateFromRequest('contact.name',
'name'));
$this->setState('contact.email',
$app->getUserStateFromRequest('contact.email',
'email'));
$this->setState('contact.telephone',
$app->getUserStateFromRequest('contact.telephone',
'telephone'));
$this->setState('contact.subject',
$app->getUserStateFromRequest('contact.subject',
'subject'));
$this->setState('contact.message',
$app->getUserStateFromRequest('contact.message',
'message'));
$propertyURL = $app->input->get('propertyURL',
'', 'base64');
$this->setState('contact.propertyURL',
base64_decode($propertyURL));
}
/**
* Get the property object
*
* @return stdClass
*
* @throws Exception
*/
public function getItem()
{
static $data;
if ($data != null)
{
return $data;
}
$dispatcher = JDispatcher::getInstance();
// Include the jea plugins for the onBeforeLoadProperty event.
JPluginHelper::importPlugin('jea');
$pk = $this->getState('property.id');
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('p.*');
$query->from('#__jea_properties AS p');
// Join properties types
$query->select('t.value AS `type`');
$query->join('LEFT', '#__jea_types AS t ON t.id =
p.type_id');
// Join departments
$query->select('d.value AS department');
$query->join('LEFT', '#__jea_departments AS d ON d.id =
p.department_id');
// Join towns
$query->select('town.value AS town');
$query->join('LEFT', '#__jea_towns AS town ON town.id =
p.town_id');
// Join areas
$query->select('area.value AS area');
$query->join('LEFT', '#__jea_areas AS area ON area.id =
p.area_id');
// Join conditions
$query->select('c.value AS `condition`');
$query->join('LEFT', '#__jea_conditions AS c ON c.id =
p.condition_id');
// Join heating types
$query->select('ht.value AS `heating_type_name`');
$query->join('LEFT', '#__jea_heatingtypes AS ht ON
ht.id = p.heating_type');
// Join hot water types
$query->select('hwt.value AS `hot_water_type_name`');
$query->join('LEFT', '#__jea_hotwatertypes AS hwt ON
hwt.id = p.hot_water_type');
// Join users
$query->select('u.username AS author');
$query->join('LEFT', '#__users AS u ON u.id =
p.created_by');
// Join slogans
$query->select('s.value AS slogan');
$query->join('LEFT', '#__jea_slogans AS s ON s.id =
p.slogan_id');
$query->where('p.id =' . (int) $pk);
$query->where('p.published = 1');
// Filter by access level
$user = JFactory::getUser();
$groups = implode(',', $user->getAuthorisedViewLevels());
$query->where('p.access IN (' . $groups . ')');
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->toSql());
$query->where('(p.publish_up = ' . $nullDate . ' OR
p.publish_up <= ' . $nowDate . ')');
$query->where('(p.publish_down = ' . $nullDate . ' OR
p.publish_down >= ' . $nowDate . ')');
$dispatcher->trigger('onBeforeLoadProperty',
array(&$query, &$this->state));
$db->setQuery($query);
$data = $db->loadObject();
if ($error = $db->getErrorMsg())
{
throw new Exception($error);
}
if ($data == null)
{
return false;
}
// Convert images field
$images = json_decode($data->images);
if (! empty($images) && is_array($images))
{
$imagePath = JPATH_ROOT . '/images/com_jea';
$baseURL = JURI::root(true);
foreach ($images as $k => $image)
{
if (file_exists($imagePath . '/images/' . $data->id .
'/' . $image->name))
{
$image->URL = $baseURL . '/images/com_jea/images/' .
$data->id . '/' . $image->name;
// Get thumb min URL
if (file_exists($imagePath . '/thumb-min/' . $data->id .
'-' . $image->name))
{
// If the thumbnail already exists, display it directly
$image->minURL = $baseURL . '/images/com_jea/thumb-min/'
. $data->id . '-' . $image->name;
}
else
{
// If the thumbnail doesn't exist, generate it and output it on
the fly
$image->minURL =
'index.php?option=com_jea&task=thumbnail.create&size=min&id='
. $data->id . '&image=' . $image->name;
}
// Get thumb medium URL
if (file_exists($imagePath . '/thumb-medium/' . $data->id
. '-' . $image->name))
{
// If the thumbnail already exists, display it directly
$image->mediumURL = $baseURL .
'/images/com_jea/thumb-medium/' . $data->id . '-' .
$image->name;
}
else
{
// If the thumbnail doesn't exist, generate it and output it on
the fly
$image->mediumURL =
'index.php?option=com_jea&task=thumbnail.create&size=medium&id='
. $data->id . '&image=' . $image->name;
}
}
else
{
unset($images[$k]);
}
}
$data->images = $images;
}
return $data;
}
/**
* Get the previous and next item relative to the current
*
* @return array
*/
public function getPreviousAndNext()
{
$item = $this->getItem();
$properties = JModelLegacy::getInstance('Properties',
'JeaModel');
$state = $properties->getState();
$state->set('list.limit', 0);
$state->set('list.start', 0);
$items = $properties->getItems();
$result = array('prev' => null, 'next' =>
null);
$currentIndex = 0;
foreach ($items as $k => $row)
{
if ($row->id == $item->id)
{
$currentIndex = $k;
}
}
if (isset($items[$currentIndex - 1]))
{
$result['prev'] = $items[$currentIndex - 1];
}
if (isset($items[$currentIndex + 1]))
{
$result['next'] = $items[$currentIndex + 1];
}
return $result;
}
/**
* Increment the hit counter for the property.
*
* @param integer $pk Optional primary key of the article to
increment.
*
* @return boolean True if successful; false otherwise and internal error
set.
*/
public function hit($pk = 0)
{
$pk = empty($pk) ? $this->getState('property.id') : (int)
$pk;
$db = $this->getDbo();
$db->setQuery('UPDATE #__jea_properties SET hits = hits + 1 WHERE
id = ' . (int) $pk);
try
{
$db->execute();
}
catch (\RuntimeException $e)
{
JLog::add($e->getMessage(), JLog::ERROR, 'com_jea');
return false;
}
return true;
}
/**
* Send property contact form
*
* @return boolean
*/
public function sendContactForm()
{
$app = JFactory::getApplication();
// Get a JMail instance
$mailer = JFactory::getMailer();
$params = $app->getParams();
$defaultFrom = $mailer->From;
$defaultFromname = $mailer->FromName;
$data = array(
'name' =>
MailHelper::cleanLine($this->getState('contact.name')),
'email' =>
MailHelper::cleanAddress($this->getState('contact.email')),
'telephone' =>
MailHelper::cleanLine($this->getState('contact.telephone')),
'subject' =>
MailHelper::cleanSubject($this->getState('contact.subject')) .
' [' . $defaultFromname . ']',
'message' =>
MailHelper::cleanText($this->getState('contact.message')),
'propertyURL' =>
$this->getState('contact.propertyURL')
);
$dispatcher = JDispatcher::getInstance();
JPluginHelper::importPlugin('jea');
if ($params->get('use_captcha'))
{
$plugin = JFactory::getConfig()->get('captcha');
if ($plugin == '0')
{
$plugin = 'recaptcha';
}
$captcha = JCaptcha::getInstance($plugin);
// Test the value.
if (! $captcha->checkAnswer(''))
{
$error = $captcha->getError();
if ($error instanceof Exception)
{
$this->setError($error->getMessage());
}
else
{
$this->setError($error);
}
}
}
// Check data
if (empty($data['name']))
{
$this->setError(JText::_('COM_JEA_YOU_MUST_TO_ENTER_YOUR_NAME'));
}
if (empty($data['message']))
{
$this->setError(JText::_('COM_JEA_YOU_MUST_TO_ENTER_A_MESSAGE'));
}
if (!MailHelper::isEmailAddress($data['email']))
{
$this->setError(JText::sprintf('COM_JEA_INVALID_EMAIL_ADDRESS',
$data['email']));
}
$result = $dispatcher->trigger('onBeforeSendContactForm',
array($data, &$this));
if (in_array(false, $result, true))
{
return false;
}
if ($this->getErrors())
{
return false;
}
$recipients = array();
$defaultMail = $params->get('default_mail');
$agentMail = '';
if ($params->get('send_form_to_agent') == 1)
{
$item = $this->getItem();
$db = $this->getDbo();
$q = 'SELECT `email` FROM `#__users` WHERE `id`=' . (int)
$item->created_by;
$db->setQuery($q);
$agentMail = $db->loadResult();
}
if (! empty($defaultMail) && ! empty($agentMail))
{
$recipients[] = $defaultMail;
$recipients[] = $agentMail;
}
elseif (! empty($defaultMail))
{
$recipients[] = $defaultMail;
}
elseif (! empty($agentMail))
{
$recipients[] = $agentMail;
}
else
{
// Send to the webmaster email
$recipients[] = $defaultFrom;
}
$body = $data['message'] . "\n";
if (!empty($data['telephone']))
{
$body .= "\n" . JText::_('COM_JEA_TELEPHONE') .
' : ' . $data['telephone'];
}
$body .= "\n" . JText::_('COM_JEA_PROPERTY_URL') .
' : ' . $data['propertyURL'];
$mailer->setBody($body);
$ret = $mailer->sendMail($data['email'],
$data['name'], $recipients, $data['subject'], $body,
false);
if ($ret == true)
{
$app->setUserState('contact.name', '');
$app->setUserState('contact.email', '');
$app->setUserState('contact.telephone', '');
$app->setUserState('contact.subject', '');
$app->setUserState('contact.message', '');
return true;
}
return false;
}
}
form.php000064400000002625151166762230006236 0ustar00<?php
/**
* This file is part of Joomla Estate Agency - Joomla! extension for real
estate agency
*
* @package Joomla.Site
* @subpackage com_jea
* @copyright Copyright (C) 2008 - 2020 PHILIP Sylvain. All rights
reserved.
* @license GNU General Public License version 2 or later; see
LICENSE.txt
*/
defined('_JEXEC') or die;
// Base this model on the backend version.
require_once JPATH_COMPONENT_ADMINISTRATOR .
'/models/property.php';
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR .
'/tables');
/**
* Property form model class.
*
* @package Joomla.Site
* @subpackage com_jea
*
* @see JeaModelProperty
*
* @since 2.0
*/
class JeaModelForm extends JeaModelProperty
{
/**
* The model (base) name should be the same as parent
*
* @var string
*/
protected $name = 'property';
/**
* Overrides parent method
*
* @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
*
* @see JeaModelProperty::getForm()
*/
public function getForm($data = array(), $loadData = true)
{
JForm::addFormPath(JPATH_COMPONENT_ADMINISTRATOR .
'/models/forms');
JForm::addFieldPath(JPATH_COMPONENT_ADMINISTRATOR .
'/models/fields');
$form = parent::getForm($data, $loadData);
return $form;
}
}