Spade
Mini Shell
blank.php000064400000107015151165262530006356 0ustar00<?php
/*----------------------------------------------------------------------------------|
www.vdm.io |----/
Lmskaran
/-------------------------------------------------------------------------------------------------------/
@version 1.0.0
@build 10th April, 2021
@created 10th April, 2021
@package Blank
@subpackage blank.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\CMS\Filesystem\File;
use Joomla\CMS\Language\Language;
use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;
/**
* Blank component helper
*/
abstract class BlankHelper
{
/**
* Composer Switch
*
* @var array
*/
protected static $composer = array();
/**
* The Main Active Language
*
* @var string
*/
public static $langTag;
/**
* Load the Composer Vendors
*/
public static function composerAutoload($target)
{
// insure we load the composer vendor only once
if (!isset(self::$composer[$target]))
{
// get the function name
$functionName = self::safeString('compose' . $target);
// check if method exist
if (method_exists(__CLASS__, $functionName))
{
return self::{$functionName}();
}
return false;
}
return self::$composer[$target];
}
/**
* Convert it into a string
*/
public static function jsonToString($value, $sperator = ", ",
$table = null, $id = 'id', $name = 'name')
{
// do some table foot work
$external = false;
if (strpos($table, '#__') !== false)
{
$external = true;
$table = str_replace('#__', '', $table);
}
// check if string is JSON
$result = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE)
{
// is JSON
if (self::checkArray($result))
{
if (self::checkString($table))
{
$names = array();
foreach ($result as $val)
{
if ($external)
{
if ($_name = self::getVar(null, $val, $id, $name, '=',
$table))
{
$names[] = $_name;
}
}
else
{
if ($_name = self::getVar($table, $val, $id, $name))
{
$names[] = $_name;
}
}
}
if (self::checkArray($names))
{
return (string) implode($sperator,$names);
}
}
return (string) implode($sperator,$result);
}
return (string) json_decode($value);
}
return $value;
}
/**
* Load the Component xml manifest.
*/
public static function manifest()
{
$manifestUrl =
JPATH_ADMINISTRATOR."/components/com_blank/blank.xml";
return simplexml_load_file($manifestUrl);
}
/**
* Joomla version object
*/
protected static $JVersion;
/**
* set/get Joomla version
*/
public static function jVersion()
{
// check if set
if (!self::checkObject(self::$JVersion))
{
self::$JVersion = new JVersion();
}
return self::$JVersion;
}
/**
* Load the Contributors details.
*/
public static function getContributors()
{
// get params
$params = JComponentHelper::getParams('com_blank');
// start contributors array
$contributors = array();
// get all Contributors (max 20)
$searchArray = range('0','20');
foreach($searchArray as $nr)
{
if ((NULL !== $params->get("showContributor".$nr))
&& ($params->get("showContributor".$nr) == 2 ||
$params->get("showContributor".$nr) == 3))
{
// set link based of selected option
if($params->get("useContributor".$nr) == 1)
{
$link_front = '<a
href="mailto:'.$params->get("emailContributor".$nr).'"
target="_blank">';
$link_back = '</a>';
}
elseif($params->get("useContributor".$nr) == 2)
{
$link_front = '<a
href="'.$params->get("linkContributor".$nr).'"
target="_blank">';
$link_back = '</a>';
}
else
{
$link_front = '';
$link_back = '';
}
$contributors[$nr]['title'] =
self::htmlEscape($params->get("titleContributor".$nr));
$contributors[$nr]['name'] =
$link_front.self::htmlEscape($params->get("nameContributor".$nr)).$link_back;
}
}
return $contributors;
}
/**
* Can be used to build help urls.
**/
public static function getHelpUrl($view)
{
return false;
}
/**
* Get any component's model
*/
public static function getModel($name, $path = JPATH_COMPONENT_SITE,
$Component = 'Blank', $config = array())
{
// fix the name
$name = self::safeString($name);
// full path to models
$fullPathModels = $path . '/models';
// load the model file
JModelLegacy::addIncludePath($fullPathModels, $Component .
'Model');
// make sure the table path is loaded
if (!isset($config['table_path']) ||
!self::checkString($config['table_path']))
{
// This is the JCB default path to tables in Joomla 3.x
$config['table_path'] = JPATH_ADMINISTRATOR .
'/components/com_' . strtolower($Component) .
'/tables';
}
// get instance
$model = JModelLegacy::getInstance($name, $Component . 'Model',
$config);
// if model not found (strange)
if ($model == false)
{
jimport('joomla.filesystem.file');
// get file path
$filePath = $path . '/' . $name . '.php';
$fullPathModel = $fullPathModels . '/' . $name .
'.php';
// check if it exists
if (File::exists($filePath))
{
// get the file
require_once $filePath;
}
elseif (File::exists($fullPathModel))
{
// get the file
require_once $fullPathModel;
}
// build class names
$modelClass = $Component . 'Model' . $name;
if (class_exists($modelClass))
{
// initialize the model
return new $modelClass($config);
}
}
return $model;
}
/**
* Add to asset Table
*/
public static function setAsset($id, $table, $inherit = true)
{
$parent = JTable::getInstance('Asset');
$parent->loadByName('com_blank');
$parentId = $parent->id;
$name = 'com_blank.'.$table.'.'.$id;
$title = '';
$asset = JTable::getInstance('Asset');
$asset->loadByName($name);
// Check for an error.
$error = $asset->getError();
if ($error)
{
return false;
}
else
{
// Specify how a new or moved node asset is inserted into the tree.
if ($asset->parent_id != $parentId)
{
$asset->setLocation($parentId, 'last-child');
}
// Prepare the asset to be stored.
$asset->parent_id = $parentId;
$asset->name = $name;
$asset->title = $title;
// get the default asset rules
$rules = self::getDefaultAssetRules('com_blank', $table,
$inherit);
if ($rules instanceof JAccessRules)
{
$asset->rules = (string) $rules;
}
if (!$asset->check() || !$asset->store())
{
JFactory::getApplication()->enqueueMessage($asset->getError(),
'warning');
return false;
}
else
{
// Create an asset_id or heal one that is corrupted.
$object = new stdClass();
// Must be a valid primary key value.
$object->id = $id;
$object->asset_id = (int) $asset->id;
// Update their asset_id to link to the asset table.
return
JFactory::getDbo()->updateObject('#__blank_'.$table, $object,
'id');
}
}
return false;
}
/**
* Gets the default asset Rules for a component/view.
*/
protected static function getDefaultAssetRules($component, $view, $inherit
= true)
{
// if new or inherited
$assetId = 0;
// Only get the actual item rules if not inheriting
if (!$inherit)
{
// Need to find the asset id by the name of the component.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__assets'))
->where($db->quoteName('name') . ' = ' .
$db->quote($component));
$db->setQuery($query);
$db->execute();
// check that there is a value
if ($db->getNumRows())
{
// asset already set so use saved rules
$assetId = (int) $db->loadResult();
}
}
// get asset rules
$result = JAccess::getAssetRules($assetId);
if ($result instanceof JAccessRules)
{
$_result = (string) $result;
$_result = json_decode($_result);
foreach ($_result as $name => &$rule)
{
$v = explode('.', $name);
if ($view !== $v[0])
{
// remove since it is not part of this view
unset($_result->$name);
}
elseif ($inherit)
{
// clear the value since we inherit
$rule = array();
}
}
// check if there are any view values remaining
if (count((array) $_result))
{
$_result = json_encode($_result);
$_result = array($_result);
// Instantiate and return the JAccessRules object for the asset rules.
$rules = new JAccessRules($_result);
// return filtered rules
return $rules;
}
}
return $result;
}
/**
* xmlAppend
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param mixed $node A SimpleXMLElement node to append
to the XML element reference, or a stdClass object containing a comment
attribute to be injected before the XML node and a fieldXML attribute
containing a SimpleXMLElement
*
* @return null
*
*/
public static function xmlAppend(&$xml, $node)
{
if (!$node)
{
// element was not returned
return;
}
switch (get_class($node))
{
case 'stdClass':
if (property_exists($node, 'comment'))
{
self::xmlComment($xml, $node->comment);
}
if (property_exists($node, 'fieldXML'))
{
self::xmlAppend($xml, $node->fieldXML);
}
break;
case 'SimpleXMLElement':
$domXML = dom_import_simplexml($xml);
$domNode = dom_import_simplexml($node);
$domXML->appendChild($domXML->ownerDocument->importNode($domNode,
true));
$xml = simplexml_import_dom($domXML);
break;
}
}
/**
* xmlComment
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param string $comment The comment to inject
*
* @return null
*
*/
public static function xmlComment(&$xml, $comment)
{
$domXML = dom_import_simplexml($xml);
$domComment = new DOMComment($comment);
$nodeTarget = $domXML->ownerDocument->importNode($domComment,
true);
$domXML->appendChild($nodeTarget);
$xml = simplexml_import_dom($domXML);
}
/**
* xmlAddAttributes
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param array $attributes The attributes to apply to
the XML element
*
* @return null
*
*/
public static function xmlAddAttributes(&$xml, $attributes = array())
{
foreach ($attributes as $key => $value)
{
$xml->addAttribute($key, $value);
}
}
/**
* xmlAddOptions
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param array $options The options to apply to the
XML element
*
* @return void
*
*/
public static function xmlAddOptions(&$xml, $options = array())
{
foreach ($options as $key => $value)
{
$addOption = $xml->addChild('option');
$addOption->addAttribute('value', $key);
$addOption[] = $value;
}
}
/**
* get the field object
*
* @param array $attributes The array of attributes
* @param string $default The default of the field
* @param array $options The options to apply to the XML
element
*
* @return object
*
*/
public static function getFieldObject(&$attributes, $default =
'', $options = null)
{
// make sure we have attributes and a type value
if (self::checkArray($attributes) &&
isset($attributes['type']))
{
// make sure the form helper class is loaded
if (!method_exists('JFormHelper', 'loadFieldType'))
{
jimport('joomla.form.form');
}
// get field type
$field = JFormHelper::loadFieldType($attributes['type'],
true);
// get field xml
$XML = self::getFieldXML($attributes, $options);
// setup the field
$field->setup($XML, $default);
// return the field object
return $field;
}
return false;
}
/**
* get the field xml
*
* @param array $attributes The array of attributes
* @param array $options The options to apply to the XML
element
*
* @return object
*
*/
public static function getFieldXML(&$attributes, $options = null)
{
// make sure we have attributes and a type value
if (self::checkArray($attributes))
{
// start field xml
$XML = new SimpleXMLElement('<field/>');
// load the attributes
self::xmlAddAttributes($XML, $attributes);
// check if we have options
if (self::checkArray($options))
{
// load the options
self::xmlAddOptions($XML, $options);
}
// return the field xml
return $XML;
}
return false;
}
/**
* Render Bool Button
*
* @param array $args All the args for the button
* 0) name
* 1) additional (options class) // not used
at this time
* 2) default
* 3) yes (name)
* 4) no (name)
*
* @return string The input html of the button
*
*/
public static function renderBoolButton()
{
$args = func_get_args();
// check if there is additional button class
$additional = isset($args[1]) ? (string) $args[1] : ''; // not
used at this time
// button attributes
$buttonAttributes = array(
'type' => 'radio',
'name' => isset($args[0]) ? self::htmlEscape($args[0]) :
'bool_button',
'label' => isset($args[0]) ?
self::safeString(self::htmlEscape($args[0]), 'Ww') : 'Bool
Button', // not seen anyway
'class' => 'btn-group',
'filter' => 'INT',
'default' => isset($args[2]) ? (int) $args[2] : 0);
// set the button options
$buttonOptions = array(
'1' => isset($args[3]) ? self::htmlEscape($args[3]) :
'JYES',
'0' => isset($args[4]) ? self::htmlEscape($args[4]) :
'JNO');
// return the input
return self::getFieldObject($buttonAttributes,
$buttonAttributes['default'], $buttonOptions)->input;
}
/**
* Get a variable
*
* @param string $table The table from which to get the
variable
* @param string $where The value where
* @param string $whereString The target/field string where/name
* @param string $what The return field
* @param string $operator The operator between $whereString/field
and $where/value
* @param string $main The component in which the table is
found
*
* @return mix string/int/float
*
*/
public static function getVar($table, $where = null, $whereString =
'user', $what = 'id', $operator = '=', $main
= 'blank')
{
if(!$where)
{
$where = JFactory::getUser()->id;
}
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query->select($db->quoteName(array($what)));
if (empty($table))
{
$query->from($db->quoteName('#__'.$main));
}
else
{
$query->from($db->quoteName('#__'.$main.'_'.$table));
}
if (is_numeric($where))
{
$query->where($db->quoteName($whereString) . '
'.$operator.' '.(int) $where);
}
elseif (is_string($where))
{
$query->where($db->quoteName($whereString) . '
'.$operator.' '. $db->quote((string)$where));
}
else
{
return false;
}
$db->setQuery($query);
$db->execute();
if ($db->getNumRows())
{
return $db->loadResult();
}
return false;
}
/**
* Get array of variables
*
* @param string $table The table from which to get the
variables
* @param string $where The value where
* @param string $whereString The target/field string where/name
* @param string $what The return field
* @param string $operator The operator between $whereString/field
and $where/value
* @param string $main The component in which the table is
found
* @param bool $unique The switch to return a unique array
*
* @return array
*
*/
public static function getVars($table, $where = null, $whereString =
'user', $what = 'id', $operator = 'IN', $main
= 'blank', $unique = true)
{
if(!$where)
{
$where = JFactory::getUser()->id;
}
if (!self::checkArray($where) && $where > 0)
{
$where = array($where);
}
if (self::checkArray($where))
{
// prep main <-- why? well if $main='' is empty then $table
can be categories or users
if (self::checkString($main))
{
$main = '_'.ltrim($main, '_');
}
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query->select($db->quoteName(array($what)));
if (empty($table))
{
$query->from($db->quoteName('#__'.$main));
}
else
{
$query->from($db->quoteName('#_'.$main.'_'.$table));
}
// add strings to array search
if ('IN_STRINGS' === $operator || 'NOT IN_STRINGS'
=== $operator)
{
$query->where($db->quoteName($whereString) . ' ' .
str_replace('_STRINGS', '', $operator) . '
("' . implode('","',$where) .
'")');
}
else
{
$query->where($db->quoteName($whereString) . ' ' .
$operator . ' (' . implode(',',$where) .
')');
}
$db->setQuery($query);
$db->execute();
if ($db->getNumRows())
{
if ($unique)
{
return array_unique($db->loadColumn());
}
return $db->loadColumn();
}
}
return false;
}
public static function isPublished($id,$type)
{
if ($type == 'raw')
{
$type = 'item';
}
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array('a.published'));
$query->from('#__blank_'.$type.' AS a');
$query->where('a.id = '. (int) $id);
$query->where('a.published = 1');
$db->setQuery($query);
$db->execute();
$found = $db->getNumRows();
if($found)
{
return true;
}
return false;
}
public static function getGroupName($id)
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(array('a.title'));
$query->from('#__usergroups AS a');
$query->where('a.id = '. (int) $id);
$db->setQuery($query);
$db->execute();
$found = $db->getNumRows();
if($found)
{
return $db->loadResult();
}
return $id;
}
/**
* Get the action permissions
*
* @param string $view The related view name
* @param int $record The item to act upon
* @param string $views The related list view name
* @param mixed $target Only get this permission (like edit,
create, delete)
* @param string $component The target component
* @param object $user The user whose permissions we are loading
*
* @return object The JObject of permission/authorised actions
*
*/
public static function getActions($view, &$record = null, $views =
null, $target = null, $component = 'blank', $user =
'null')
{
// load the user if not given
if (!self::checkObject($user))
{
// get the user object
$user = JFactory::getUser();
}
// load the JObject
$result = new JObject;
// make view name safe (just incase)
$view = self::safeString($view);
if (self::checkString($views))
{
$views = self::safeString($views);
}
// get all actions from component
$actions = JAccess::getActionsFromFile(
JPATH_ADMINISTRATOR . '/components/com_' . $component .
'/access.xml',
"/access/section[@name='component']/"
);
// if non found then return empty JObject
if (empty($actions))
{
return $result;
}
// get created by if not found
if (self::checkObject($record) && !isset($record->created_by)
&& isset($record->id))
{
$record->created_by = self::getVar($view, $record->id,
'id', 'created_by', '=', $component);
}
// set actions only set in component settings
$componentActions = array('core.admin',
'core.manage', 'core.options',
'core.export');
// check if we have a target
$checkTarget = false;
if ($target)
{
// convert to an array
if (self::checkString($target))
{
$target = array($target);
}
// check if we are good to go
if (self::checkArray($target))
{
$checkTarget = true;
}
}
// loop the actions and set the permissions
foreach ($actions as $action)
{
// check target action filter
if ($checkTarget && self::filterActions($view, $action->name,
$target))
{
continue;
}
// set to use component default
$fallback = true;
// reset permission per/action
$permission = false;
$catpermission = false;
// set area
$area = 'comp';
// check if the record has an ID and the action is item related (not a
component action)
if (self::checkObject($record) && isset($record->id)
&& $record->id > 0 && !in_array($action->name,
$componentActions) &&
(strpos($action->name, 'core.') !== false ||
strpos($action->name, $view . '.') !== false))
{
// we are in item
$area = 'item';
// The record has been set. Check the record permissions.
$permission = $user->authorise($action->name, 'com_' .
$component . '.' . $view . '.' . (int) $record->id);
// if no permission found, check edit own
if (!$permission)
{
// With edit, if the created_by matches current user then dig deeper.
if (($action->name === 'core.edit' || $action->name
=== $view . '.edit') && $record->created_by > 0
&& ($record->created_by == $user->id))
{
// the correct target
$coreCheck = (array) explode('.', $action->name);
// check that we have both local and global access
if ($user->authorise($coreCheck[0] . '.edit.own',
'com_' . $component . '.' . $view . '.' .
(int) $record->id) &&
$user->authorise($coreCheck[0] . '.edit.own',
'com_' . $component))
{
// allow edit
$result->set($action->name, true);
// set not to use global default
// because we already validated it
$fallback = false;
}
else
{
// do not allow edit
$result->set($action->name, false);
$fallback = false;
}
}
}
elseif (self::checkString($views) && isset($record->catid)
&& $record->catid > 0)
{
// we are in item
$area = 'category';
// set the core check
$coreCheck = explode('.', $action->name);
$core = $coreCheck[0];
// make sure we use the core. action check for the categories
if (strpos($action->name, $view) !== false &&
strpos($action->name, 'core.') === false )
{
$coreCheck[0] = 'core';
$categoryCheck = implode('.', $coreCheck);
}
else
{
$categoryCheck = $action->name;
}
// The record has a category. Check the category permissions.
$catpermission = $user->authorise($categoryCheck, 'com_'
. $component . '.' . $views . '.category.' . (int)
$record->catid);
if (!$catpermission && !is_null($catpermission))
{
// With edit, if the created_by matches current user then dig deeper.
if (($action->name === 'core.edit' || $action->name
=== $view . '.edit') && $record->created_by > 0
&& ($record->created_by == $user->id))
{
// check that we have both local and global access
if ($user->authorise('core.edit.own', 'com_'
. $component . '.' . $views . '.category.' . (int)
$record->catid) &&
$user->authorise($core . '.edit.own', 'com_'
. $component))
{
// allow edit
$result->set($action->name, true);
// set not to use global default
// because we already validated it
$fallback = false;
}
else
{
// do not allow edit
$result->set($action->name, false);
$fallback = false;
}
}
}
}
}
// if allowed then fallback on component global settings
if ($fallback)
{
// if item/category blocks access then don't fall back on global
if ((($area === 'item') && !$permission) || (($area
=== 'category') && !$catpermission))
{
// do not allow
$result->set($action->name, false);
}
// Finally remember the global settings have the final say. (even if
item allow)
// The local item permissions can block, but it can't open and
override of global permissions.
// Since items are created by users and global permissions is set by
system admin.
else
{
$result->set($action->name,
$user->authorise($action->name, 'com_' . $component));
}
}
}
return $result;
}
/**
* Filter the action permissions
*
* @param string $action The action to check
* @param array $targets The array of target actions
*
* @return boolean true if action should be filtered out
*
*/
protected static function filterActions(&$view, &$action,
&$targets)
{
foreach ($targets as $target)
{
if (strpos($action, $view . '.' . $target) !== false ||
strpos($action, 'core.' . $target) !== false)
{
return false;
break;
}
}
return true;
}
/**
* Check if have an json string
*
* @input string The json string to check
*
* @returns bool true on success
*/
public static function checkJson($string)
{
if (self::checkString($string))
{
json_decode($string);
return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}
/**
* Check if have an object with a length
*
* @input object The object to check
*
* @returns bool true on success
*/
public static function checkObject($object)
{
if (isset($object) && is_object($object))
{
return count((array)$object) > 0;
}
return false;
}
/**
* Check if have an array with a length
*
* @input array The array to check
*
* @returns bool/int number of items in array on success
*/
public static function checkArray($array, $removeEmptyString = false)
{
if (isset($array) && is_array($array) && ($nr =
count((array)$array)) > 0)
{
// also make sure the empty strings are removed
if ($removeEmptyString)
{
foreach ($array as $key => $string)
{
if (empty($string))
{
unset($array[$key]);
}
}
return self::checkArray($array, false);
}
return $nr;
}
return false;
}
/**
* Check if have a string with a length
*
* @input string The string to check
*
* @returns bool true on success
*/
public static function checkString($string)
{
if (isset($string) && is_string($string) &&
strlen($string) > 0)
{
return true;
}
return false;
}
/**
* Check if we are connected
* Thanks https://stackoverflow.com/a/4860432/1429677
*
* @returns bool true on success
*/
public static function isConnected()
{
// If example.com is down, then probably the whole internet is down,
since IANA maintains the domain. Right?
$connected = @fsockopen("www.example.com", 80);
// website, port (try 80 or 443)
if ($connected)
{
//action when connected
$is_conn = true;
fclose($connected);
}
else
{
//action in connection failure
$is_conn = false;
}
return $is_conn;
}
/**
* Merge an array of array's
*
* @input array The arrays you would like to merge
*
* @returns array on success
*/
public static function mergeArrays($arrays)
{
if(self::checkArray($arrays))
{
$arrayBuket = array();
foreach ($arrays as $array)
{
if (self::checkArray($array))
{
$arrayBuket = array_merge($arrayBuket, $array);
}
}
return $arrayBuket;
}
return false;
}
// typo sorry!
public static function sorten($string, $length = 40, $addTip = true)
{
return self::shorten($string, $length, $addTip);
}
/**
* Shorten a string
*
* @input string The you would like to shorten
*
* @returns string on success
*/
public static function shorten($string, $length = 40, $addTip = true)
{
if (self::checkString($string))
{
$initial = strlen($string);
$words = preg_split('/([\s\n\r]+)/', $string, null,
PREG_SPLIT_DELIM_CAPTURE);
$words_count = count((array)$words);
$word_length = 0;
$last_word = 0;
for (; $last_word < $words_count; ++$last_word)
{
$word_length += strlen($words[$last_word]);
if ($word_length > $length)
{
break;
}
}
$newString = implode(array_slice($words, 0, $last_word));
$final = strlen($newString);
if ($initial != $final && $addTip)
{
$title = self::shorten($string, 400 , false);
return '<span class="hasTip"
title="'.$title.'"
style="cursor:help">'.trim($newString).'...</span>';
}
elseif ($initial != $final && !$addTip)
{
return trim($newString).'...';
}
}
return $string;
}
/**
* Making strings safe (various ways)
*
* @input string The you would like to make safe
*
* @returns string on success
*/
public static function safeString($string, $type = 'L', $spacer
= '_', $replaceNumbers = true, $keepOnlyCharacters = true)
{
if ($replaceNumbers === true)
{
// remove all numbers and replace with english text version (works well
only up to millions)
$string = self::replaceNumbers($string);
}
// 0nly continue if we have a string
if (self::checkString($string))
{
// create file name without the extention that is safe
if ($type === 'filename')
{
// make sure VDM is not in the string
$string = str_replace('VDM', 'vDm', $string);
// Remove anything which isn't a word, whitespace, number
// or any of the following caracters -_()
// If you don't need to handle multi-byte characters
// you can use preg_replace rather than mb_ereg_replace
// Thanks @Łukasz Rysiak!
// $string = mb_ereg_replace("([^\w\s\d\-_\(\)])",
'', $string);
$string = preg_replace("([^\w\s\d\-_\(\)])", '',
$string);
// http://stackoverflow.com/a/2021729/1429677
return preg_replace('/\s+/', ' ', $string);
}
// remove all other characters
$string = trim($string);
$string = preg_replace('/'.$spacer.'+/', '
', $string);
$string = preg_replace('/\s+/', ' ', $string);
// Transliterate string
$string = self::transliterate($string);
// remove all and keep only characters
if ($keepOnlyCharacters)
{
$string = preg_replace("/[^A-Za-z ]/", '',
$string);
}
// keep both numbers and characters
else
{
$string = preg_replace("/[^A-Za-z0-9 ]/", '',
$string);
}
// select final adaptations
if ($type === 'L' || $type === 'strtolower')
{
// replace white space with underscore
$string = preg_replace('/\s+/', $spacer, $string);
// default is to return lower
return strtolower($string);
}
elseif ($type === 'W')
{
// return a string with all first letter of each word uppercase(no
undersocre)
return ucwords(strtolower($string));
}
elseif ($type === 'w' || $type === 'word')
{
// return a string with all lowercase(no undersocre)
return strtolower($string);
}
elseif ($type === 'Ww' || $type === 'Word')
{
// return a string with first letter of the first word uppercase and
all the rest lowercase(no undersocre)
return ucfirst(strtolower($string));
}
elseif ($type === 'WW' || $type === 'WORD')
{
// return a string with all the uppercase(no undersocre)
return strtoupper($string);
}
elseif ($type === 'U' || $type === 'strtoupper')
{
// replace white space with underscore
$string = preg_replace('/\s+/', $spacer, $string);
// return all upper
return strtoupper($string);
}
elseif ($type === 'F' || $type === 'ucfirst')
{
// replace white space with underscore
$string = preg_replace('/\s+/', $spacer, $string);
// return with first caracter to upper
return ucfirst(strtolower($string));
}
elseif ($type === 'cA' || $type === 'cAmel' || $type
=== 'camelcase')
{
// convert all words to first letter uppercase
$string = ucwords(strtolower($string));
// remove white space
$string = preg_replace('/\s+/', '', $string);
// now return first letter lowercase
return lcfirst($string);
}
// return string
return $string;
}
// not a string
return '';
}
public static function transliterate($string)
{
// set tag only once
if (!self::checkString(self::$langTag))
{
// get global value
self::$langTag =
JComponentHelper::getParams('com_blank')->get('language',
'en-GB');
}
// Transliterate on the language requested
$lang = Language::getInstance(self::$langTag);
return $lang->transliterate($string);
}
public static function htmlEscape($var, $charset = 'UTF-8',
$shorten = false, $length = 40)
{
if (self::checkString($var))
{
$filter = new JFilterInput();
$string = $filter->clean(html_entity_decode(htmlentities($var,
ENT_COMPAT, $charset)), 'HTML');
if ($shorten)
{
return self::shorten($string,$length);
}
return $string;
}
else
{
return '';
}
}
public static function replaceNumbers($string)
{
// set numbers array
$numbers = array();
// first get all numbers
preg_match_all('!\d+!', $string, $numbers);
// check if we have any numbers
if (isset($numbers[0]) && self::checkArray($numbers[0]))
{
foreach ($numbers[0] as $number)
{
$searchReplace[$number] = self::numberToString((int)$number);
}
// now replace numbers in string
$string = str_replace(array_keys($searchReplace),
array_values($searchReplace),$string);
// check if we missed any, strange if we did.
return self::replaceNumbers($string);
}
// return the string with no numbers remaining.
return $string;
}
/**
* Convert an integer into an English word string
* Thanks to Tom Nicholson
<http://php.net/manual/en/function.strval.php#41988>
*
* @input an int
* @returns a string
*/
public static function numberToString($x)
{
$nwords = array( "zero", "one", "two",
"three", "four", "five", "six",
"seven",
"eight", "nine", "ten",
"eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen",
"nineteen", "twenty", 30 => "thirty",
40 => "forty",
50 => "fifty", 60 => "sixty", 70 =>
"seventy", 80 => "eighty",
90 => "ninety" );
if(!is_numeric($x))
{
$w = $x;
}
elseif(fmod($x, 1) != 0)
{
$w = $x;
}
else
{
if($x < 0)
{
$w = 'minus ';
$x = -$x;
}
else
{
$w = '';
// ... now $x is a non-negative integer.
}
if($x < 21) // 0 to 20
{
$w .= $nwords[$x];
}
elseif($x < 100) // 21 to 99
{
$w .= $nwords[10 * floor($x/10)];
$r = fmod($x, 10);
if($r > 0)
{
$w .= ' '. $nwords[$r];
}
}
elseif($x < 1000) // 100 to 999
{
$w .= $nwords[floor($x/100)] .' hundred';
$r = fmod($x, 100);
if($r > 0)
{
$w .= ' and '. self::numberToString($r);
}
}
elseif($x < 1000000) // 1000 to 999999
{
$w .= self::numberToString(floor($x/1000)) .' thousand';
$r = fmod($x, 1000);
if($r > 0)
{
$w .= ' ';
if($r < 100)
{
$w .= 'and ';
}
$w .= self::numberToString($r);
}
}
else // millions
{
$w .= self::numberToString(floor($x/1000000)) .' million';
$r = fmod($x, 1000000);
if($r > 0)
{
$w .= ' ';
if($r < 100)
{
$w .= 'and ';
}
$w .= self::numberToString($r);
}
}
}
return $w;
}
/**
* Random Key
*
* @returns a string
*/
public static function randomkey($size)
{
$bag =
"abcefghijknopqrstuwxyzABCDDEFGHIJKLLMMNOPQRSTUVVWXYZabcddefghijkllmmnopqrstuvvwxyzABCEFGHIJKNOPQRSTUWXYZ";
$key = array();
$bagsize = strlen($bag) - 1;
for ($i = 0; $i < $size; $i++)
{
$get = rand(0, $bagsize);
$key[] = $bag[$get];
}
return implode($key);
}
}
category.php000064400000003245151165262530007104 0ustar00<?php
/*----------------------------------------------------------------------------------|
www.vdm.io |----/
fdsh
/-------------------------------------------------------------------------------------------------------/
@version 1.0.39
@build 4th April, 2023
@created 17th December, 2020
@package Reservation
@subpackage category.php
@author farhad shahbazi <http://farhad.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');
/**
* Reservation Component Category Tree
*/
//Insure this view category file is loaded.
$classname = 'ReservationDoctorCategories';
if (!class_exists($classname))
{
$path = JPATH_SITE .
'/components/com_reservation/helpers/categorydoctor.php';
if (is_file($path))
{
include_once $path;
}
}
//Insure this view category file is loaded.
$classname = 'ReservationConsultantCategories';
if (!class_exists($classname))
{
$path = JPATH_SITE .
'/components/com_reservation/helpers/categoryconsultant.php';
if (is_file($path))
{
include_once $path;
}
}
headercheck.php000064400000004344151165262530007516 0ustar00<?php
/*----------------------------------------------------------------------------------|
www.vdm.io |----/
fdsh
/-------------------------------------------------------------------------------------------------------/
@version 1.0.39
@build 4th April, 2023
@created 17th December, 2020
@package Reservation
@subpackage headercheck.php
@author farhad shahbazi <http://farhad.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');
class reservationHeaderCheck
{
function js_loaded($script_name)
{
// UIkit check point
if (strpos($script_name,'uikit') !== false)
{
$app = JFactory::getApplication();
$getTemplateName =
$app->getTemplate('template')->template;
if (strpos($getTemplateName,'yoo') !== false)
{
return true;
}
}
$document = JFactory::getDocument();
$head_data = $document->getHeadData();
foreach (array_keys($head_data['scripts']) as $script)
{
if (stristr($script, $script_name))
{
return true;
}
}
return false;
}
function css_loaded($script_name)
{
// UIkit check point
if (strpos($script_name,'uikit') !== false)
{
$app = JFactory::getApplication();
$getTemplateName =
$app->getTemplate('template')->template;
if (strpos($getTemplateName,'yoo') !== false)
{
return true;
}
}
$document = JFactory::getDocument();
$head_data = $document->getHeadData();
foreach (array_keys($head_data['styleSheets']) as $script)
{
if (stristr($script, $script_name))
{
return true;
}
}
return false;
}
}index.html000064400000000054151165262530006546
0ustar00<html><body
bgcolor="#FFFFFF"></body></html>route.php000064400000004312151165262530006421
0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Multilanguage;
use \Joomla\CMS\Router\Route;
use Joomla\CMS\Uri\Uri;
abstract class SppagebuilderHelperRoute
{
public static function buildRoute($link)
{
// sh404sef
if (defined('SH404SEF_IS_RUNNING'))
{
return Uri::root() . $link;
}
// 4SEF
if (defined('4SEF_IS_RUNNING'))
{
return Uri::root() . $link;
}
return Route::link('site', $link, false, null);
}
// Get page route
public static function getPageRoute($id, $language = 0, $layout = null)
{
// Create the link
$link =
'index.php?option=com_sppagebuilder&view=page&id=' . $id;
if ($language && $language !== '*' &&
Multilanguage::isEnabled())
{
$link .= '&lang=' . $language;
}
if ($layout)
{
$link .= '&layout=' . $layout;
}
if ($Itemid = self::getMenuItemId($id))
{
$link .= '&Itemid=' . $Itemid;
}
return self::buildRoute($link);
}
// Get form route
public static function getFormRoute($id, $language = 0, $Itemid = 0)
{
$link =
'index.php?option=com_sppagebuilder&view=form&id=' .
(int) $id;
if ($language && $language !== '*' &&
Multilanguage::isEnabled())
{
$link .= '&lang=' . $language;
}
if ($Itemid != 0)
{
$link .= '&Itemid=' . $Itemid;
}
else
{
if (self::getMenuItemId($id))
{
$link .= '&Itemid=' . self::getMenuItemId($id);
}
}
$link .= '&layout=edit&tmpl=component';
return self::buildRoute($link);
}
// get menu ID
private static function getMenuItemId($id)
{
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('id')));
$query->from($db->quoteName('#__menu'));
$query->where($db->quoteName('link') . ' LIKE '
. $db->quote('%option=com_sppagebuilder&view=page&id='
. (int) $id . '%'));
$query->where($db->quoteName('published') . ' =
' . $db->quote('1'));
$db->setQuery($query);
$result = $db->loadResult();
if ($result)
{
return $result;
}
return;
}
}
.DS_Store000064400000014004151165346670006244
0ustar00Bud1 dfbwspblobdompdfbwspblob�bplist00�
]ShowStatusBar[ShowSidebar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowPathbar _{{737,
381}, {1461, 797}} %1=I`myz{|}~��dompdfvSrnlong
@� @� @� @E DSDB
`� @� @�
@helpers.php000064400000132371151165346670006744 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.');
class InvoicesHelper{
static function showInvoicesFooter(){
require_once(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'version.php');
return InvoicesVersion::show_footer();
}
static function format($number, $currency = false){
$params = JComponentHelper::getParams( 'com_invoices' );
$db = JFactory::getDBO();
if(is_int($currency)){
$query = "SELECT * FROM #__invoices_currencies WHERE id =
".(int)$currency;
$db->setQuery($query);
$currency = $db->loadObject();
}
if(!$currency){
$query = "SELECT * FROM #__invoices_currencies WHERE id =
".(int)$params->get('currency_id', 1);
$db->setQuery($query);
$currency = $db->loadObject();
}
if($currency == 'percent'){
$currency = new stdClass();
$currency->decpoint = ".";
$currency->thousands = ",";
$currency->decimals = 0;
$currency->symbol_before = "";
$currency->symbol_after = "%";
}
$decpoint = $currency->decpoint;
$thousands = $currency->thousands;
$decimals = $currency->decimals;
$before = $currency->symbol_before;
$after = $currency->symbol_after;
return $before . number_format($number, $decimals, $decpoint,
$thousands) . $after ;
}
static function format_editing($number){
$params = JComponentHelper::getParams( 'com_invoices' );
$decimals = $params->get('decimals_editing', 2);
return number_format($number, $decimals, '.', '') ;
}
static function format_simple($number){
return str_replace(".", ",", $number) ;
}
static function get_subtotal($invoice_id){
$db = JFactory::getDBO();
$query = ' SELECT SUM((it.value * it.amount -
it.discount)*(1+it.tax/100)) FROM #__invoices_items AS it WHERE
it.invoice_id = '.$invoice_id ;
$db->setQuery($query);
$subtotal = $db->loadResult();
$query = ' SELECT discount FROM #__invoices_invoices AS i WHERE i.id
= '.$invoice_id ;
$db->setQuery($query);
$discount = $db->loadResult();
return $subtotal - $discount;
}
static function get_subtotal_items($invoice_id){
$db = JFactory::getDBO();
$query = ' SELECT SUM(it.value * it.amount - it.discount) FROM
#__invoices_items AS it WHERE it.invoice_id = '.$invoice_id ;
$db->setQuery($query);
$subtotal = $db->loadResult();
$query = ' SELECT discount FROM #__invoices_invoices AS i WHERE i.id
= '.$invoice_id ;
$db->setQuery($query);
$discount = $db->loadResult();
return $subtotal - $discount;
}
static function get_total($invoice, $update_taxes = false){
$db = JFactory::getDBO();
$taxes_value = 0;
$thetaxvalue = 0 ;
if(!isset($invoice->subtotal_items)) $invoice->subtotal_items =
InvoicesHelper::get_subtotal_items($invoice->id);
$subtotal1 = $invoice->subtotal ;
$subtotal1_items = $invoice->subtotal_items ;
//if($invoice->taxes){
$query = ' SELECT tax.*, tai.value AS value, tai.id AS tai_id FROM
#__invoices_taxes AS tax '
.' LEFT JOIN #__invoices_tax_invoice AS tai ON (tai.tax_id = tax.id
AND tai.reference_id = ' . $invoice->id . ' AND tai.type = 1)
'
.' WHERE tai.active = 1 '
.' ORDER BY ordering, name ' ;
$db->setQuery($query);
$taxes = $db->loadObjectList();
foreach($taxes as $tax){
switch($tax->type){
case "percent":
if($tax->ordering == 1){ //first group of taxes
if($tax->calculate_on == 1){
$thetaxvalue = ( $tax->value / 100 ) * $invoice->subtotal_items
;
$taxes_value += ( $tax->value / 100 ) *
$invoice->subtotal_items ;
}
else{
$thetaxvalue = ( $tax->value / 100 ) * $invoice->subtotal ;
$taxes_value += ( $tax->value / 100 ) * $invoice->subtotal ;
}
}
else if($tax->ordering == 2){ //second group of taxes
if($tax->calculate_on == 1){
$thetaxvalue = ( $tax->value / 100 ) * $subtotal1_items ;
$taxes_value += ( $tax->value / 100 ) * $subtotal1_items ;
}
else{
$thetaxvalue = ( $tax->value / 100 ) * $subtotal1 ;
$taxes_value += ( $tax->value / 100 ) * $subtotal1 ;
}
}
break;
case "static":
$thetaxvalue = $tax->value ;
$taxes_value += $tax->value ;
break;
}
if($tax->ordering == 1){
$subtotal1 += $thetaxvalue ;
$subtotal1_items += $thetaxvalue ;
}
if($update_taxes){
$query = "UPDATE #__invoices_tax_invoice SET computed_value =
'$thetaxvalue' WHERE id = " . $tax->tai_id ;
$db->setQuery($query);
$db->query();
}
}
//}
$total = $invoice->subtotal + $taxes_value ;
return $total;
}
static function get_display_taxes($row){
$db = JFactory::getDBO();
$subtotal = $row->subtotal;
$subtotal_items = $row->subtotal_items;
$subtotal1 = $row->subtotal ;
$subtotal1_items = $row->subtotal_items ;
$display_taxes = array();
//taxes in 2.1
//individual item taxes
$query = ' SELECT SUM((it.value * it.amount -
it.discount)*(it.tax/100)) AS tax_value, it.tax_id '
.' FROM #__invoices_items AS it '
.' WHERE it.invoice_id = '.$row->id
.' GROUP BY it.tax_id' ;
$db->setQuery($query);
$items_taxes = $db->loadObjectList('tax_id');
//invoice-global taxes
$query = ' SELECT tax.*, tai.value AS value, tai.active FROM
#__invoices_taxes AS tax '
.' LEFT JOIN #__invoices_tax_invoice AS tai ON (tai.tax_id = tax.id
AND tai.reference_id = ' . $row->id . ' AND tai.type = 1 AND
tai.active = 1) '
.' ORDER BY ordering, name ' ;
$db->setQuery($query);
$taxes = $db->loadObjectList('id');
foreach($taxes as $tax){
$taxes_value = 0 ;
//invoice-global taxes
if($tax->active){
switch($tax->type){
case "percent":
if($tax->ordering == 1){ //first group of taxes
if($tax->calculate_on == 1) $taxes_value = ( $tax->value / 100
) * $subtotal_items ;
else $taxes_value = ( $tax->value / 100 ) * $subtotal ;
}
else if($tax->ordering == 2){ //second group of taxes
if($tax->calculate_on == 1) $taxes_value = ( $tax->value / 100
) * $subtotal1_items ;
else $taxes_value = ( $tax->value / 100 ) * $subtotal1 ;
}
break;
case "static":
$taxes_value = $tax->value ;
break;
}
if($tax->ordering == 1){
$subtotal1 += $taxes_value ;
$subtotal1_items += $taxes_value ;
}
}
$taxobject = new stdClass();
$taxobject->tax_id = $tax->id;
//individual item taxes
if(isset($items_taxes[$tax->id])) $taxobject->items_tax =
$items_taxes[$tax->id] ;
else {
$taxobject->items_tax = new stdClass();
$taxobject->items_tax->tax_value = 0 ;
//if only global tax, we can show the percentage
if($tax->active && $tax->type == "percent")
$taxobject->tax_percentage = InvoicesHelper::format($tax->value,
'percent');
}
$taxobject->global_tax = $taxes_value;
$taxobject->tax = $taxobject->items_tax->tax_value +
$taxobject->global_tax;
$taxobject->formatted_tax =
InvoicesHelper::format($taxobject->tax, $row->currency_id);
$display_taxes[$tax->id] = $taxobject ;
}
return $display_taxes;
}
static function get_total_from_id($invoice_id , $update_taxes = false){
$total = 0;
if($invoice_id){
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__invoices_invoices WHERE id = ' .
$invoice_id ;
$db->setQuery($query);
$invoice = $db->loadObject();
if($invoice->id){
$invoice->subtotal = InvoicesHelper::get_subtotal($invoice_id);
$total = InvoicesHelper::get_total($invoice, $update_taxes);
}
}
return $total;
}
static function download_pdf_button($id){
$version = PHP_VERSION >= 5.0 ? true : false ;
$quotes = get_magic_quotes_gpc();
if(file_exists(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php')
&& $version && !$quotes){
$mainframe = JFactory::getApplication();
$uri = JFactory::getURI();
if(!$mainframe->isSite()){
$url =
JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&cid[]='.$id);
}
else $url =
JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&id='.$id);
$return = "<a href='".$url."'
title=\"".JText::_('DOWNLOAD_INVOICE_PDF')."\">".JHTML::image('components/com_invoices/assets/images/page_white_acrobat.png',
JText::_('DOWNLOAD_INVOICE_PDF'))."</a>" ;
}
else $return = "";
return $return ;
}
static function download_pdf_link($id){
$version = PHP_VERSION >= 5.0 ? true : false ;
$quotes = get_magic_quotes_gpc();
if(file_exists(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php')
&& $version && !$quotes){
$mainframe = JFactory::getApplication();
$uri = JFactory::getURI();
if(!$mainframe->isSite()){
$url =
JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&cid[]='.$id,
false);
}
else $url =
JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&id='.$id);
$return = $url;
}
else $return = "";
return $return ;
}
static function pdf_enabled(){
$version = PHP_VERSION >= 5.0 ? true : false ;
$quotes = get_magic_quotes_gpc();
if(file_exists(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php')
&& $version && !$quotes){
return true;
}
else return false;
}
static function view_modal_button($id){
$modal = true ;
if($modal){
$link = "&tmpl=component" ;
$rel = 'rel="{ size: {x: 800, y: 500}, handler:
\'iframe\'}"';
}
$mainframe = JFactory::getApplication();
$uri = JFactory::getURI();
$url =
JRoute::_('index.php?option=com_invoices&view=invoice&id='.$id.$link);
if(!$mainframe->isSite()){
//$url =
$uri->root().'index.php?option=com_invoices&view=invoice&id='.$id.$link;
$url =
JRoute::_('index.php?option=com_invoices&view=invoice&cid[]='.$id.$link);
}
$return = "<a class='modal' ".$rel."
href='".$url."'
title=\"".JText::_('VIEW_INVOICE_DETAILS')."\">".JHTML::image('components/com_invoices/assets/images/magnifier.png',
JText::_('VIEW_INVOICE_DETAILS'))."</a>" ;
return $return ;
}
static function view_online_button($id){
$mainframe = JFactory::getApplication();
$uri = JFactory::getURI();
$url =
JRoute::_('index.php?option=com_invoices&view=invoice&id='.$id
);
if(!$mainframe->isSite()){
//$url =
$uri->root().'index.php?option=com_invoices&view=invoice&id='.$id.'&tmpl=component';
$url =
JRoute::_('index.php?option=com_invoices&view=invoice&cid[]='.$id.'&tmpl=component');
}
$return = "<a target='_blank'
href='".$url."'
title=\"".JText::_('VIEW_INVOICE_ONLINE')."\">".JHTML::image('components/com_invoices/assets/images/invoice.png',
JText::_('VIEW_INVOICE_ONLINE'))."</a>" ;
return $return ;
}
static function send_email_button($id, $type = "invoice"){
$mainframe = JFactory::getApplication();
if(!$mainframe->isSite()){
$url =
JRoute::_('index.php?option=com_invoices&controller='.$type.'&task=send_email&cid[]='.$id);
}
else{
$url =
JRoute::_('index.php?option=com_invoices&task=send&id='.$id);
}
$return = "<a href='".$url."'
title=\"".JText::_('SEND_EMAIL')."\">".JHTML::image('components/com_invoices/assets/images/email.png',
JText::_('SEND_EMAIL'))."</a>" ;
return $return ;
}
static function send_email_link($id, $type = "invoice"){
$mainframe = JFactory::getApplication();
if(!$mainframe->isSite()){
$url =
JRoute::_('index.php?option=com_invoices&controller='.$type.'&task=send_email&cid[]='.$id,
false);
}
else{
$url =
JRoute::_('index.php?option=com_invoices&task=send&id='.$id);
}
return $url ;
}
static function create_invoice($data, $items, $payments){
$mainframe = JFactory::getApplication();
$model = InvoicesHelper::getInvoiceAdminModel();
require_once(
JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'invoice.php'
);
require_once(
JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'contact.php'
);
require_once(
JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'item.php'
);
require_once(
JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'payment.php'
);
require_once(
JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'taxinvoice.php'
);
if ($invoice_id = $model->store($data, $items, $payments)) {
$msg = JText::_( 'INVOICE_SAVED' );
$type = "message" ;
} else {
$msg = JText::_( 'ERROR_SAVING_INVOICE' );
$type = "error" ;
}
return $invoice_id;
}
static function getInvoiceAdminModel()
{
if (!class_exists( 'InvoicesModelInvoice' ))
{
// Build the path to the model based upon a supplied base path
$path =
JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'models'.DS.'invoice.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( 'InvoicesModelInvoice' )) {
JError::raiseWarning( 0, 'View class InvoicesModelInvoice not
found in file.' );
return $false;
}
} else {
JError::raiseWarning( 0, 'View InvoicesModelInvoice not supported.
File not found.' );
return $false;
}
}
$model = new InvoicesModelInvoice();
return $model;
}
static function getStatus(){
$status = array();
$status[] = "paid";
$status[] = "pending";
$status[] = "partial_paid";
$status[] = "pastdue";
$status[] = "refunded";
$status[] = "partial_refunded";
$status[] = "corrected";
return $status;
}
static function getQuoteStatus(){
$status = array();
$status[] = "pending";
$status[] = "accepted";
$status[] = "accepted_client";
$status[] = "cancelled";
$status[] = "rejected";
$status[] = "rejected_client";
$status[] = "expired";
return $status;
}
static function getStatusPaymentFilters(){
$status = array();
$status[] = (object)array("id" => "unpaid",
"name" => 'UNPAID_SIMPLE');
$status[] = (object)array("id" => "paid",
"name" => 'PAID');
$status[] = (object)array("id" => "pending",
"name" => 'PENDING_VALIDATION');
return $status;
}
static function getPaymentStatus(){
$status = array();
$status[0] = JText::_('UNPAID');
$status[1] = JText::_('PAID');
$status[2] = JText::_('UNPAID_ONTIME');
$status[3] = JText::_('PENDING_VALIDATION');
return $status;
}
static function getPaymentData($payment_id){
$db = JFactory::getDBO();
$query = ' SELECT pa.* FROM #__invoices_payments AS pa WHERE pa.id =
'.$payment_id;
$db->setQuery($query);
$payment = $db->loadObject();
return $payment;
}
static function getNextRecurrencyDate($invoice){
if($invoice["rec_year"]) $months =
$invoice["rec_year"] * 12 + $invoice["rec_month"] ;
else $months = $invoice["rec_month"] ;
$thetime = $invoice["rec_nextdate"] . " +
".$months." months + ".$invoice["rec_day"]."
days" ;
//echo $thetime;die;
$nextdate = strtotime($thetime) ;
$nextdate = date("Y-m-d", $nextdate) ;
return $nextdate ;
}
static function getPaymentLink($payment_id){
$uri = JFactory::getURI();
$link = $uri->base() .
'index.php?option=com_invoices&view=payment&id='.$payment_id
;
$link = str_replace("administrator/","",$link) ;
return $link;
}
static function getInvoiceLink($invoice_id){
$uri = JFactory::getURI();
$link = $uri->base() .
'index.php?option=com_invoices&view=invoice&id='.$invoice_id
;
$link = str_replace("administrator/","",$link) ;
return $link;
}
static function getInvoicePublicLink($invoice_id){
$uri = JFactory::getURI();
$db = JFactory::getDBO();
$query = " SELECT auth_code FROM #__invoices_invoices WHERE id =
".$invoice_id ;
$db->setQuery($query);
$auth_code = $db->loadResult();
$link = $uri->base() .
'index.php?option=com_invoices&view=invoice&id='.$invoice_id
.'&auth_code='.$auth_code;
$link = str_replace("administrator/","",$link) ;
return $link;
}
static function getQuoteAcceptLink($quote_id){
$uri = JFactory::getURI();
$db = JFactory::getDBO();
$query = " SELECT auth_code FROM #__invoices_invoices WHERE id =
".$quote_id ;
$db->setQuery($query);
$auth_code = $db->loadResult();
$link = $uri->base() .
'index.php?option=com_invoices&task=accept_quote&id='.$quote_id
.'&auth_code='.$auth_code;
$link = str_replace("administrator/","",$link) ;
return $link;
}
static function getQuoteRejectLink($quote_id){
$uri = JFactory::getURI();
$db = JFactory::getDBO();
$query = " SELECT auth_code FROM #__invoices_invoices WHERE id =
".$quote_id ;
$db->setQuery($query);
$auth_code = $db->loadResult();
$link = $uri->base() .
'index.php?option=com_invoices&task=reject_quote&id='.$quote_id
.'&auth_code='.$auth_code;
$link = str_replace("administrator/","",$link) ;
return $link;
}
static function getInvoiceNum($real_invoice_num, $type = 1){
$params = JComponentHelper::getParams( 'com_invoices' );
if($type == 1) $format = $params->get('invoice_num_format')
;
elseif($type == 2) $format =
$params->get('quote_num_format') ;
$real_invoice_num = str_pad($real_invoice_num,
$params->get('invoice_number_digits', 0), '0',
STR_PAD_LEFT);
$string = str_replace("[num]", $real_invoice_num, $format) ;
$string = str_replace("[yyyy]", date("Y"), $string) ;
$string = str_replace("[mm]", date("m"), $string) ;
$string = str_replace("[dd]", date("d"), $string) ;
return $string ;
}
static function getInvoiceStatus($invoice, $total, $total_payments,
$amount_outstanding){
$params = JComponentHelper::getParams( 'com_invoices' );
$status = $invoice->status ;
if(!$status && $params->get('computestatus')
&& $invoice->type == 1){
//if the status is not set, we calculate it
$status = InvoicesHelper::getComputedInvoiceStatus($invoice, $total,
$total_payments, $amount_outstanding);
//$status = $invoice->computed_status;
}
return $status;
}
static function getComputedInvoiceStatus($invoice, $total, $total_payments
= false, $amount_outstanding = false){
$db = JFactory::getDBO();
$params = JComponentHelper::getParams( 'com_invoices' );
if(!$total_payments){
$query = " SELECT SUM(payment_amount) FROM #__invoices_payments
WHERE payment_status = 1 AND invoice_id = ".$invoice->id ;
$db->setQuery($query);
$total_payments = $db->loadResult();
}
if(!$amount_outstanding){
$query = " SELECT SUM(payment_amount) FROM #__invoices_payments
WHERE payment_status = 0 AND invoice_id = ".$invoice->id ;
$db->setQuery($query);
$amount_outstanding = $db->loadResult();
}
$total_payments = round($total_payments,
$params->get('decimals', 2));
$total = round($total, $params->get('decimals', 2));
if($amount_outstanding == 0 && $total_payments >= $total){
$status = "paid"; //paid in full
}
elseif($invoice->invoice_duedate != "0000-00-00" &&
$invoice->invoice_duedate != "0000-00-00 00:00:00" &&
$invoice->invoice_duedate != "" ){
if(strtotime($invoice->invoice_duedate) <= time()) {
$status = "pastdue"; //past due date
}
else {
if($amount_outstanding && $total_payments){
$status = "partial_paid"; //partially paid
}
else $status = "pending"; //pending
}
}
elseif($invoice->invoice_duedate == "0000-00-00" ||
$invoice->invoice_duedate == "0000-00-00 00:00:00" ||
!$invoice->invoice_duedate){
if($amount_outstanding && $total_payments){
$status = "partial_paid"; //partially paid
}
elseif($total_payments){
$status = "partial_paid"; //partially paid
}
else $status = "pending"; //pending
}
return $status;
}
static function updateComputedStatus($invoice_id, $calculate_total =
false, $create_auth_code = false){
$db = JFactory::getDBO();
$query = " SELECT * FROM #__invoices_invoices WHERE id =
".$invoice_id ;
$db->setQuery($query);
$invoice = $db->loadObject();
$sql_total = "";
$sql_auth_code = "";
if($calculate_total) {
$computed_total = InvoicesHelper::get_total_from_id($invoice->id) ;
$computed_subtotal = InvoicesHelper::get_subtotal_items($invoice->id)
;
$sql_total = ', computed_total = '.$computed_total.',
computed_subtotal = '.$computed_subtotal ;
}
else $computed_total = $invoice->computed_total ;
if(!$invoice->auth_code) {
$auth_code = InvoicesHelper::genRandomCode() ;
$sql_auth_code = ', auth_code =
"'.$auth_code.'" ' ;
}
else $sql_auth_code = "" ;
$computed_status = InvoicesHelper::getComputedInvoiceStatus($invoice,
$computed_total) ;
$query = ' UPDATE #__invoices_invoices SET '.
' computed_status = "'.$computed_status.'"
'.
$sql_total .
$sql_auth_code .
' WHERE id = '.$invoice_id .
' LIMIT 1 ';
$db->setQuery($query);
$db->query();
//added 2.1
InvoicesHelper::updateComputedData($invoice_id);
}
static function updateComputedData($invoice_id){
$db = JFactory::getDBO();
$query = " SELECT * FROM #__invoices_invoices WHERE id =
".$invoice_id ;
$db->setQuery($query);
$row = $db->loadObject();
$computed_total = InvoicesHelper::get_total_from_id($invoice_id, true) ;
$computed_subtotal = InvoicesHelper::get_subtotal_items($invoice_id);
$computed = new StdClass();
$computed->total = $computed_total;
$computed->subtotal = InvoicesHelper::get_subtotal($invoice_id);
$computed->subtotal_items = $computed_subtotal;
$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 = '.$invoice_id.' AND pa.payment_status = 1
' ;
$db->setQuery($query);
$computed->total_paid = $db->loadObject();
$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 = '.$invoice_id.' AND pa.payment_status = 0
' ;
$db->setQuery($query);
$computed->total_unpaid = $db->loadObject();
$row->subtotal = $computed->subtotal;
$row->subtotal_items = $computed_subtotal;
//store taxes in json
$computed->taxes = InvoicesHelper::get_display_taxes($row);
$computed = json_encode($computed);
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
$db->quoteName('computed') . ' = ' .
$db->quote($computed),
$db->quoteName('computed_subtotal') . ' = ' .
$db->quote($computed_subtotal)
);
// Conditions for which records should be updated.
$conditions = array(
$db->quoteName('id') . ' = '.$invoice_id
);
$query->update($db->quoteName('#__invoices_invoices'))->set($fields)->where($conditions);
$db->setQuery($query);
$db->execute();
}
static function render_status($status){
switch($status){
case "paid": case "payed": case
"accepted": case "accepted_client":
$status = "<span class='label
label-success'>".JText::_($status)."</span>" ;
break;
case "pending":case "partial_paid":
$status = "<span class='label
label-warning'>".JText::_($status)."</span>" ;
break;
case "pastdue": case "rejected": case
"rejected_client":
$status = "<span class='label
label-important'>".JText::_($status)."</span>"
;
break;
case "refunded": case "partial_refunded": case
"cancelled": case "expired":
$status = "<span class='label
label-inverse'>".JText::_($status)."</span>" ;
break;
case "corrected":
$status = "<span class='label
label-info'>".JText::_($status)."</span>" ;
break;
default:
$status = "<span class='label
label-default'>".JText::_("NOT_SETTED")."</span>"
;
break;
}
return $status;
}
static function render_status_class($status){
switch($status){
case "paid": case "payed": case
"accepted": case "accepted_client":
$status = "success" ;
break;
case "pending":case "partial_paid":
$status = "warning" ;
break;
case "pastdue": case "rejected": case
"rejected_client":
$status = "danger" ;
break;
case "refunded": case "partial_refunded": case
"cancelled": case "expired":
$status = "inverse" ;
break;
case "corrected":
$status = "info" ;
break;
default:
$status = "default" ;
break;
}
return $status;
}
static function getThePaymentStatus($payment){
if($payment->payment_status){
$thestatus = 1;
}
elseif($payment->payment_duedate != "0000-00-00 00:00:00"
&& !$payment->payment_status){
if(strtotime($payment->payment_duedate) <= time()) {
$thestatus = 0;
}
else {
$thestatus = 2;
}
}
elseif($payment->payment_duedate == "0000-00-00 00:00:00"){
$thestatus = 2;
}
if($payment->payment_status == 2){
$thestatus = 3;
}
return $thestatus ;
}
static function render_status_payment($status){
$payment_status = InvoicesHelper::getPaymentStatus();
switch($status){
case 0:
$status = "<span class='label
label-important'>".$payment_status[$status]."</span>"
;
break;
case 1:
$status = "<span class='label
label-success'>".$payment_status[$status]."</span>"
;
break;
case 2:
$status = "<span class='label
label-warning'>".$payment_status[$status]."</span>"
;
break;
case 3:
$status = "<span class='label
label-default'>".$payment_status[$status]."</span>"
;
break;
}
return $status;
}
static function render_num_payments_received($num){
switch($num){
case 0:
$status = "<span class='badge badge-default
badge-secondary'>".$num."</span>" ;
break;
default:
$status = "<span class='badge
badge-success'>".$num."</span>" ;
break;
}
return $status;
}
static function render_num_pending_payments($num){
switch($num){
case 0:
$status = "<span
class='badge'>".$num."</span>" ;
break;
default:
$status = "<span class='badge
badge-warning'>".$num."</span>" ;
break;
}
return $status;
}
static function PDFavailable(){
return InvoicesHelper::pdf_enabled();
}
static function genRandomCode($length = 64)
{
$salt =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$base = strlen($salt);
$makepass = '';
/*
* Start with a cryptographic strength random string, then convert it to
* a string with the numeric base of the salt.
* Shift the base conversion on each character so the character
* distribution is even, and randomize the start shift so it's not
* predictable.
*/
$random = JCrypt::genRandomBytes($length + 1);
$shift = ord($random[0]);
for ($i = 1; $i <= $length; ++$i)
{
$makepass .= $salt[($shift + ord($random[$i])) % $base];
$shift += ord($random[$i]);
}
return $makepass;
}
static function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
static function replace_string_between($string, $start, $end, $replace){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return $string;
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr_replace($string,$replace,$ini,$len);
}
static function updateSentDate($id){
$db = JFactory::getDBO();
$query = " UPDATE #__invoices_invoices SET `last_sent` = NOW() WHERE
id = ".$id;
$db->setQuery($query);
$db->query();
}
static function allowEdit($recordId = 0, $ownerId = 0)
{
if(!$recordId){
$array = JRequest::getVar('cid', 0, '',
'array');
$recordId = (int)$array[0];
}
$user = JFactory::getUser();
//new item
if(!$recordId){
if ($user->authorise('core.create',
'com_invoices' ))
{
return true;
}
else return false;
}
// Check general edit permission first.
if ($user->authorise('core.edit', 'com_invoices'
))
{
return true;
}
// Fallback on edit.own.
// First test if the permission is available.
if ($user->authorise('core.edit.own',
'com_invoices' ))
{
// Now test the owner is the user.
if(!$ownerId){
$db = JFactory::getDBO();
$query = ' SELECT created_by FROM #__invoices_invoices WHERE id =
'.$recordId;
$db->setQuery($query);
$ownerId = $db->loadResult();
}
if (empty($ownerId) && $recordId)
{
return false;
}
// If the owner matches 'me' then do the test.
if ($ownerId == $user->id)
{
return true;
}
}
return false;
}
static function canDelete($recordId = 0, $ownerId = 0)
{
$user = JFactory::getUser();
return $user->authorise('core.delete',
'com_invoices');
}
static function canEditState($recordId = 0, $ownerId = 0)
{
$user = JFactory::getUser();
return $user->authorise('core.edit.state',
'com_invoices');
}
static function versionBox()
{
$db = JFactory::getDBO();
$query = ' SELECT manifest_cache FROM #__extensions WHERE element =
"com_invoices" AND type = "component" ';
$db->setQuery( $query );
$extenison_info = $db->loadObject();
$extenison_info = json_decode($extenison_info->manifest_cache);
$installed_version = $extenison_info->version;
$versionBox = '';
$versionBox .= "<div class='row-fluid version-box
hidden-xs'><div class=''><div
class='container-fluid'><div class='row-fluid
sys-info-title'><span>".JText::_('SYSTEM_INFO')."</span></div><div
class='row-fluid'><span>".JText::sprintf('INSTALLED_VERSION',
$installed_version)."</span></div><div
class='row-fluid'><span>".JText::_('LATEST_VERSION')."</span><span
id='latest-version'>".$installed_version."</span></div><div
class='row-fluid'><div
id='update-info'>".JText::_('SEARCHING_UPDATES')."</div></div></div></div></div>";
return $versionBox;
}
public static function addSubmenu($vName)
{
JHtmlSidebar::addEntry(
JText::_('INVOICES'),
'index.php?option=com_invoices',
$vName == 'invoices'
);
JHtmlSidebar::addEntry(
JText::_('QUOTES'),
'index.php?option=com_invoices&controller=quotes',
$vName == 'quotes'
);
JHtmlSidebar::addEntry(
JText::_('PAYMENTS'),
'index.php?option=com_invoices&controller=payments',
$vName == 'payments'
);
JHtmlSidebar::addEntry(
JText::_('CONTACTS'),
'index.php?option=com_invoices&controller=contacts',
$vName == 'contacts'
);
JHtmlSidebar::addEntry(
JText::_('TAXES'),
'index.php?option=com_invoices&controller=taxes',
$vName == 'taxes'
);
JHtmlSidebar::addEntry(
JText::_('TEMPLATES'),
'index.php?option=com_invoices&controller=templates',
$vName == 'templates'
);
JHtmlSidebar::addEntry(
JText::_('PRODUCTS'),
'index.php?option=com_invoices&controller=templateitems',
$vName == 'products'
);
JHtmlSidebar::addEntry(
JText::_('PAYMENT_OPTIONS'),
'index.php?option=com_plugins&filter_folder=invoices'
);
JHtmlSidebar::addEntry(
JText::_('CONFIGURATION_OPTIONS'),
'index.php?option=com_config&view=component&component=com_invoices&path=&return='.urlencode(base64_encode('index.php?option=com_invoices'))
);
JHtmlSidebar::addEntry(
JText::_('CURRENCIES'),
'index.php?option=com_invoices&controller=currencies',
$vName == 'currencies'
);
}
static function getOrderOptions(){
$return = array();
$option = new stdClass();
$option->value = "i.invoice_date,desc";
$option->name = JText::_( 'ORDER_DATE_DESC' );
$return[] = $option;
$option = new stdClass();
$option->value = "i.invoice_date,asc";
$option->name = JText::_( 'ORDER_DATE_ASC' );
$return[] = $option;
$option = new stdClass();
$option->value = "i.to_name,desc";
$option->name = JText::_( 'ORDER_NAME_DESC' );
$return[] = $option;
$option = new stdClass();
$option->value = "i.to_name,asc";
$option->name = JText::_( 'ORDER_NAME_ASC' );
$return[] = $option;
$option = new stdClass();
$option->value = "i.computed_total,asc";
$option->name = JText::_( 'ORDER_VALUE_DESC' );
$return[] = $option;
$option = new stdClass();
$option->value = "i.computed_total,desc";
$option->name = JText::_( 'ORDER_VALUE_ASC' );
$return[] = $option;
return $return;
}
static function build_order_header($name, $value, $filter_order,
$filter_order_dir){
if($filter_order == $value) $hidden = "";
else $hidden = "style='display:none'" ;
if(strtoupper($filter_order_dir) == "ASC") {
$dir = "DESC" ;
$class = "";
}
elseif(strtoupper($filter_order_dir) == "DESC") {
$dir = "ASC" ;
$class = "-alt";
}
$return = "<a href='#'
onclick=\"order_by('".$value."',jQuery(this));return
false;\" data-order-dir='".$dir."' >".
JText::_($name)." <span class='glyphicon
glyphicon-sort-by-attributes".$class." order_dir_button'
".$hidden."></span></a>";
return $return;
}
static function getCurrencies()
{
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__invoices_currencies '.
' WHERE currency_published = 1 '.
' ORDER BY id ASC ';
$db->setQuery( $query );
$currencies = $db->loadObjectList('id');
return $currencies;
}
static function getDefaultCurrency(){
$params = JComponentHelper::getParams( 'com_invoices' );
$db = JFactory::getDBO();
$query = "SELECT * FROM #__invoices_currencies WHERE id =
".(int)$params->get('currency_id', 1);
$db->setQuery($query);
$currency = $db->loadObject();
return $currency;
}
static function percentCurrency($currency = false){
$params = JComponentHelper::getParams( 'com_invoices' );
if(!$currency) $currency = InvoicesHelper::getDefaultCurrency();
$return = new stdClass();
$return->symbol_before = "";
$return->symbol_after = "%";
$return->decimals = (int)$params->get('decimals_tax', 0);
$return->thousands = $currency->thousands;
$return->decpoint = $currency->decpoint;
return $return;
}
public static function templateToVue($template)
{
//the language tags
$pattern = '/\[\[(.*?)\]\]/' ;
$matches = array();
preg_match_all($pattern, $template, $matches);
foreach($matches[1] as $value){
$template = str_replace("[[".$value."]]",
"{{ '".$value."' | translate }}", $template);
}
//ITEMS
$items = InvoicesHelper::get_string_between($template,
"<!--ITEMS-->", "<!--/ITEMS-->");
$search = array(
"<tr>",
"{sku}",
"{name}",
"{desc}",
"{value}",
"{amount}",
"{discount}",
"{tax}",
"{item_tax_value}",
"{item_with_tax}",
"{tax_name}",
"{item_subtotal_no_discount}",
"{item_subtotal}",
"{item_total}",
);
$replace = array(
"<tr v-for='(item, index) in invoice.items'>",
"{{ item.sku }}",
"{{ item.name }}",
"{{ item.desc }}",
"{{ item.value | currency(invoice.currency_id) }}",
"{{ item.amount }}",
"{{ item.discount | currency(invoice.currency_id) }}",
"{{ item.tax | taxpercentage }}",
"{{ invoice.taxItem(index) | currency(invoice.currency_id)
}}",
"{{ invoice.itemWithTax(index) | currency(invoice.currency_id)
}}",
"{{ item.tax_id | taxname | translate }}",
"{{ invoice.subtotalItemNoDiscount(index) |
currency(invoice.currency_id) }}",
"{{ invoice.subtotalItem(index) | currency(invoice.currency_id)
}}",
"{{ invoice.totalItem(index) | currency(invoice.currency_id)
}}",
);
$items = str_replace($search, $replace, $items) ;
$template = InvoicesHelper::replace_string_between($template,
"<!--ITEMS-->", "<!--/ITEMS-->",
"{items}");
//TAXES
$taxes = InvoicesHelper::get_string_between($template,
"<!--TAXES-->", "<!--/TAXES-->");
$search = array(
"<tr>",
"{name}",
"{value}",
"{tax_value}",
"{calculated_on_amount}",
);
$replace = array(
"<tr v-for='(tax, index) in invoice.taxes'
v-show='tax.active'>",
"{{ tax.name | translate }}",
"{{ invoice.globaltax(tax.id) | currency(invoice.currency_id)
}}",
"{{ tax.tax_value | taxpercentageorflat(tax, invoice.currency_id)
}}",
"{{ tax.calculated_on_amount | currency(invoice.currency_id)
}}",
);
$taxes = str_replace($search, $replace, $taxes) ;
$template = InvoicesHelper::replace_string_between($template,
"<!--TAXES-->", "<!--/TAXES-->",
"{taxes}");
//GROUPED TAXES
$grouped_taxes = InvoicesHelper::get_string_between($template,
"<!--GROUPED_TAXES-->",
"<!--/GROUPED_TAXES-->");
$search = array(
"<tr>",
"{name}",
"{value}",
"{tax_value}",
"{calculated_on_amount}",
);
$replace = array(
"<tr v-for='(tax, index) in
invoice.individualTaxes()'>",
"{{ tax.name | translate }}",
"{{ tax.value | currency(invoice.currency_id) }}",
"{{ tax.percent_value | taxpercentage }}",
"{{ tax.calculated_on_amount | currency(invoice.currency_id)
}}",
);
$grouped_taxes = str_replace($search, $replace, $grouped_taxes) ;
$template = InvoicesHelper::replace_string_between($template,
"<!--GROUPED_TAXES-->",
"<!--/GROUPED_TAXES-->", "{grouped_taxes}");
//GROUPED TAXES TOTAL
$grouped_taxes_total = InvoicesHelper::get_string_between($template,
"<!--GROUPED_TAXES_TOTAL-->",
"<!--/GROUPED_TAXES_TOTAL-->");
$search = array(
"<tr>",
"{name}",
"{value}",
"{tax_value}",
"{calculated_on_amount}",
);
$replace = array(
"<tr v-for='(tax, index) in
invoice.individual_taxes_totals'>",
"{{ tax.name | translate }}",
"{{ tax.value | currency(invoice.currency_id) }}",
"{{ tax.tax_value | taxpercentage }}",
"{{ tax.calculated_on_amount | currency(invoice.currency_id)
}}",
);
$grouped_taxes_total = str_replace($search, $replace,
$grouped_taxes_total) ;
$template = InvoicesHelper::replace_string_between($template,
"<!--GROUPED_TAXES_TOTAL-->",
"<!--/GROUPED_TAXES_TOTAL-->",
"{grouped_taxes_total}");
//PAYMENTS
$payments = InvoicesHelper::get_string_between($template,
"<!--PAYMENTS-->", "<!--/PAYMENTS-->");
$search = array(
"<tr>",
"{description}",
"{duedate}",
"{payment_datetime}",
"{amount}",
"href=\"{payment_link}\"",
"{payment_status}",
);
$replace = array(
"<tr v-for='(payment, index) in
getPaidPayments()'>",
"{{ payment.payment_description }}",
"{{ payment.payment_duedate | date('D MMMM YYYY',
undefined, invoice.language) }}",
"{{ payment.payment_datetime | date('D MMMM YYYY',
undefined, invoice.language) }}",
"{{ payment.payment_amount | currency(invoice.currency_id)
}}",
":href=\"payment.payment_link\"",
"<span :class=\"'label label-' +
invoice.getPaymentStatusClass(payment)\">{{
invoice.getPaymentStatusName(payment) | translate }}</span>",
);
$payments = str_replace($search, $replace, $payments) ;
$template = InvoicesHelper::replace_string_between($template,
"<!--PAYMENTS-->", "<!--/PAYMENTS-->",
"{payments}");
//PAYMENTS2
$payments2 = InvoicesHelper::get_string_between($template,
"<!--PAYMENTS2-->", "<!--/PAYMENTS2-->");
$search = array(
"<tr>",
"{description}",
"{duedate}",
"{payment_datetime}",
"{amount}",
"href=\"{payment_link}\"",
"{payment_status}",
);
$replace = array(
"<tr v-for='(payment, index) in
getUnpaidPayments()'>",
"{{ payment.payment_description }}",
"{{ payment.payment_duedate | date('D MMMM YYYY',
undefined, invoice.language) }}",
"{{ payment.payment_datetime | date('D MMMM YYYY',
undefined, invoice.language) }}",
"{{ payment.payment_amount | currency(invoice.currency_id)
}}",
":href=\"payment.payment_link\"
target='_blank'",
"<span :class=\"'label label-' +
invoice.getPaymentStatusClass(payment)\">{{
invoice.getPaymentStatusName(payment) | translate }}</span>",
);
$payments2 = str_replace($search, $replace, $payments2) ;
$template = InvoicesHelper::replace_string_between($template,
"<!--PAYMENTS2-->", "<!--/PAYMENTS2-->",
"{payments2}");
//the tags
$search = array(
"{to_name}",
"{to_company}",
"{to_email}",
"{to_address}",
"{from_name}",
"{from_address}",
"{from_num}",
"{from_url}",
"{from_email}",
"{from_phone}",
"{invoice_date}",
"{notes}",
"{invoice_num}",
"{items}",
"{subtotal}",
"{taxes}",
"{grouped_taxes}",
"{grouped_taxes_total}",
"{total}",
"{payments}",
"{payments2}",
"{total_payments}",
"{amount_outstanding}",
"{to_zipcode}",
"{to_city}",
"{to_state}",
"{to_country}",
"{to_vatid}",
"{discount}",
"{invoice_duedate}",
"{status}",
"{num_payments_received}",
"{num_pending_payments}",
"{to_phone}",
"{invoice_link}",
"{invoice_unlogged_link}",
"{subtotal_items}",
"{subtotal_items_less_total_discount}",
"{external_ref}",
"{paynow_button}",
"{total_items_tax}",
"{subtotal_items_no_discount}",
"{total_items_discount}",
"{accept_button}",
"{reject_button}"
);
$replace = array(
"{{ invoice.to_name }}",
"{{ invoice.to_company }}",
"{{ invoice.to_email }}",
"<div
v-html='nl2br(invoice.to_address)'></div>",
"{{ invoice.from_name }}",
"<div
v-html='nl2br(invoice.from_address)'></div>",
"{{ invoice.from_num }}",
"{{ invoice.from_url }}",
"{{ invoice.from_email }}",
"{{ invoice.from_phone }}",
"{{ invoice.invoice_date | date('D MMMM YYYY', undefined,
invoice.language) }}",
"<div v-html='invoice.notes'></div>",
"{{ invoice.invoice_num }}",
//ITEMS
$items,
"{{ invoice.subtotal_items() | currency(invoice.currency_id)
}}",
//TAXES
$taxes,
//GROUPED TAXES
$grouped_taxes,
//GROUPED TAXES TOTAL
$grouped_taxes_total,
"{{ invoice.thetotal() | currency(invoice.currency_id) }}",
//PAYMENTS
$payments,
//PAYMENTS2
$payments2,
"{{ invoice.total_payments }}",
"{{ invoice.total_unpaid | currency(invoice.currency_id) }}",
"{{ invoice.to_zipcode }}",
"{{ invoice.to_city }}",
"{{ invoice.to_state }}",
"{{ invoice.to_country }}",
"{{ invoice.to_vatid }}",
"{{ invoice.discount | currency(invoice.currency_id) }}",
"{{ invoice.invoice_duedate | date('D MMMM YYYY',
undefined, invoice.language) }}",
"<span :class=\"'label label-' +
status_class\">{{ status_name }}</span>",
"{{ invoice.num_payments_received }}",
"{{ invoice.num_pending_payments }}",
"{{ invoice.to_phone }}",
"{{ invoice.link }}",
"{{ invoice.public_link }}",
"{{ invoice.subtotal_items() | currency(invoice.currency_id)
}}",
"{{ invoice.subtotal_items() | currency(invoice.currency_id)
}}",
"{{ invoice.external_ref }}",
"<div v-html='paynow_button'></div>",
"{{ invoice.individual_taxes_totals | currency(invoice.currency_id)
}}",
"{subtotal_items_no_discount}",
"{total_items_discount}",
"<div v-html='accept_button'></div>",
"<div v-html='reject_button'></div>",
);
$template = str_replace($search, $replace, $template) ;
return $template;
}
/**
* Get an array of all the taxes defined in the system
* @return array An array of objects, each containing the tax element from
the DB
*/
public static function getAllTaxes(){
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__invoices_taxes ORDER BY ordering, name
';
$db->setQuery( $query );
$alltaxes = $db->loadObjectList();
return $alltaxes;
}
public static function getTemplatesData(){
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__invoices_templates '.
' ORDER BY name ';
$db->setQuery( $query );
$templates_data = $db->loadObjectList();
return $templates_data;
}
/**
* Get an array of the taxes that are set to be displayed as columns
* @return array An array of objects, each containing the tax element from
the DB
*/
public static function getTaxes(){
$db = JFactory::getDBO();
$query = ' SELECT * FROM #__invoices_taxes WHERE show_column = 1
ORDER BY ordering, name ';
$db->setQuery( $query );
$taxes = $db->loadObjectList();
return $taxes;
}
public static function loadStatusLanguageStrings()
{
JText::script('PAID');
JText::script('ACCEPTED');
JText::script('ACCEPTED_CLIENT');
JText::script('PENDING');
JText::script('PARTIAL_PAID');
JText::script('PASTDUE');
JText::script('REJECTED');
JText::script('REJECTED_CLIENT');
JText::script('REFUNDED');
JText::script('PARTIAL_REFUNDED');
JText::script('CANCELLED');
JText::script('EXPIRED');
JText::script('CORRECTED');
JText::script('UNPAID_ONTIME');
JText::script('PAID_LATE');
}
public static function sendJSONResponse($object, $status = 200){
$app = JFactory::getApplication();
switch($status){
case 403:
header('HTTP/1.0 403 Forbidden');
break;
default:
break;
}
header('Content-Type: application/json');
echo json_encode($object);
$app->close();
}
public static function storepdf($location, $view)
{
jimport( 'joomla.html.html');
require_once(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php');
if(file_exists(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'html'.DS.'html.php'))
require_once(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'html'.DS.'html.php');
elseif(file_exists(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'html.php'))
require_once(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'html.php');
if(file_exists(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'date'.DS.'date.php'))
require_once(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'date'.DS.'date.php');
elseif(file_exists(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'date.php'))
require_once(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'date.php');
$mainframe = JFactory::getApplication();
$plantilla = 'email' ;
$html = $view->loadTemplate($plantilla);
$search = array("€", "¢", "£",
"¤", "¥");
$replace = array("€", "¢",
"£", "¤", "¥");
$html = str_replace($search, $replace, $html);
$html = mb_convert_encoding($html, 'HTML-ENTITIES',
'UTF-8');
$html = utf8_decode($html);
$html = '<!DOCTYPE HTML>
<html>
<body>
<style>
'.$view->template->styles.'
</style>'
. $html .
'</body></html>';
$options = new Dompdf\Options();
$options->set( 'isRemoteEnabled', TRUE );
$dompdf = new Dompdf\Dompdf($options);
$dompdf->set_paper('a4');
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
return file_put_contents($location, $pdf);
}
}
version.php000064400000001270151165346670006760 0ustar00<?php
/*------------------------------------------------------------------------
# com_invoices - Invoices for Joomla
# ------------------------------------------------------------------------
# author Germinal Camps
# copyright Copyright (C) 2012 JoomlaFinances.com. All Rights Reserved.
# @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.JoomlaFinances.com
# Technical Support: Forum - http://www.JoomlaFinances.com/forum
-------------------------------------------------------------------------*/
//no direct access
defined('_JEXEC') or die('Restricted access.');
class InvoicesVersion{
static function show_footer(){
return "";
}
}categoryconsultant.php000064400000003022151165544530011213
0ustar00<?php
/*----------------------------------------------------------------------------------|
www.vdm.io |----/
fdsh
/-------------------------------------------------------------------------------------------------------/
@version 1.0.39
@build 4th April, 2023
@created 17th December, 2020
@package Reservation
@subpackage categoryconsultant.php
@author farhad shahbazi <http://farhad.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');
/**
* Reservation Consultant Component Category Tree
*/
class ReservationConsultantCategories extends JCategories
{
/**
* Class constructor
*
* @param array $options Array of options
*
*/
public function __construct($options = array())
{
$options['table'] = '#__reservation_consultant';
$options['extension'] = 'com_reservation.consultant';
parent::__construct($options);
}
}
categorydoctor.php000064400000002776151165544530010332 0ustar00<?php
/*----------------------------------------------------------------------------------|
www.vdm.io |----/
fdsh
/-------------------------------------------------------------------------------------------------------/
@version 1.0.39
@build 4th April, 2023
@created 17th December, 2020
@package Reservation
@subpackage categorydoctor.php
@author farhad shahbazi <http://farhad.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');
/**
* Reservation Doctor Component Category Tree
*/
class ReservationDoctorCategories extends JCategories
{
/**
* Class constructor
*
* @param array $options Array of options
*
*/
public function __construct($options = array())
{
$options['table'] = '#__reservation_doctor';
$options['extension'] = 'com_reservation.doctor';
parent::__construct($options);
}
}
reservation.php000064400000122301151165544530007626 0ustar00<?php
/*----------------------------------------------------------------------------------|
www.vdm.io |----/
fdsh
/-------------------------------------------------------------------------------------------------------/
@version 1.0.39
@build 4th April, 2023
@created 17th December, 2020
@package Reservation
@subpackage reservation.php
@author farhad shahbazi <http://farhad.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\CMS\Filesystem\File;
use Joomla\CMS\Language\Language;
use Joomla\Registry\Registry;
use Joomla\String\StringHelper;
use Joomla\Utilities\ArrayHelper;
/**
* Reservation component helper
*/
abstract class ReservationHelper
{
/**
* Composer Switch
*
* @var array
*/
protected static $composer = array();
/**
* The Main Active Language
*
* @var string
*/
public static $langTag;
/***[JCBGUI.joomla_component.php_helper_site.28.$$$$]***/
public static function getSessionCount($pk)
{
// select number of sessions performed by consultants
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select(' COUNT(*) as count')
->from($db->quoteName('#__reservation_session',
's'))
->join('INNER',
$db->quoteName('#__reservation_plan', 'p') . '
ON ' . $db->quoteName('s.planid') . ' = ' .
$db->quoteName('p.id'))
->join('INNER',
$db->quoteName('#__reservation_consultant', 'co') .
' ON ' . $db->quoteName('p.consultantid') . ' =
' . $db->quoteName('co.id'))
->where($db->quoteName('s.pay').'=
1')
->where($db->quoteName('co.id').'=
'.$pk.' ');
$db->setQuery($query);
$sessionCount = $db->loadObject();
return $sessionCount;
}
public static function checkAccount($userid= 'this')
{
if ($userid == 'this')
{
$user= JFactory::getUser();
$userid= $user->id;
}
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('id');
$query->from($db->quoteName('#__reservation_sick',
's'));
$query->where($db->quoteName('userid').'='.$db->quote($userid));
$db->setQuery($query);
$result['sick'] = $db->loadResult();
$query = $db->getQuery(true);
$query->select('id');
$query->from($db->quoteName('#__reservation_consultant',
'c'));
$query->where($db->quoteName('userid').'='.$db->quote($userid));
$db->setQuery($query);
$result['consultant'] = $db->loadResult();
$query = $db->getQuery(true);
$query->select('id');
$query->from($db->quoteName('#__reservation_doctor',
'd'));
$query->where($db->quoteName('userid').'='.$db->quote($userid));
$db->setQuery($query);
$result['doctor'] = $db->loadResult();
return $result;
}
public static function exist($table, $column, $value)
{
$db= JFactory::getDbo();
$query= $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName($table,'t'))
->where($db->quoteName($column).'='.$db->quote($value));
$db->setQuery($query);
$result= $db->loadResult();
if (empty($result))
return false;
return $result;
}
public static function doctorAuthorize($uid)
{
$app = JFactory::getApplication();
$uid = $app->input->get('uid');
$params = $app->getparams('com_reservation');
$userGroups = !empty($params->get('doctorgroup')) ?
$params->get('doctorgroup') : [0];
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('co.id'))
->from($db->quoteName('#__reservation_consultant',
'co'))
->join('inner',
$db->quoteName('#__user_usergroup_map', 'uu') .
'on' . $db->quoteName('uu.user_id') . '='
. $db->quoteName('co.userid'))
->where($db->quoteName('co.userid') .
'=' . $db->quote($uid))
->where($db->quoteName('uu.group_id') .
'IN(' . implode(',', $userGroups) . ')');
$db->setQuery($query);
$result = $db->loadObject();
if (empty($result))
return false;
return true;
}
public static function seid_user_road($seid)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from($db->quoteName('#__users',
'u'));
$query->join('inner',$db->quoteName('#__reservation_consultant',
'co'). ' on '.
$db->quoteName('co.userid').' = '.
$db->quoteName('u.id'));
$query->join('inner',$db->quoteName('#__reservation_plan',
'p'). ' on '.
$db->quoteName('p.consultantid').' = '.
$db->quoteName('co.id'));
$query->join('inner',$db->quoteName('#__reservation_session',
'se'). ' on '.
$db->quoteName('se.planid').' = '.
$db->quoteName('p.id'));
$query->where($db->quoteName('se.id').'='.$db->quote($seid));
$db->setQuery($query);
$result = $db->loadObject();
return $result;
}/***[/JCBGUI$$$$]***/
/***[JCBGUI.joomla_component.php_helper_both.28.$$$$]***/
public static function getConsultant($coid= null, $userid= null)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*, co.id as id');
$query->from($db->quoteName('#__reservation_consultant',
'co'));
$query->join('inner',$db->quoteName('#__users',
'u'). ' on '.
$db->quoteName('co.userid').' = '.
$db->quoteName('u.id'));
$query->join('inner',$db->quoteName('#__categories',
'c'). ' on '.
$db->quoteName('c.id').' = '.
$db->quoteName('co.catid'));
if ($coid)
$query->where($db->quoteName('co.id').'='.$db->quote($coid));
elseif ($userid)
$query->where($db->quoteName('u.id').'='.$db->quote($userid));
$db->setQuery($query);
$result = $db->loadObject();
return $result;
}
public static function setExpireTime()
{
$app= JFactory::getApplication();
date_default_timezone_set('asia/tehran');
$expire= date("M d, Y H:i:s", strtotime(date("M d,
Y H:i:s"))+(3*60));
$app->setUserState('expire',$expire );
JFactory::getDocument()->addScriptOptions('expire',
$expire);
}
public static function setVerifyCode()
{
$app= JFactory::getApplication();
$verify= rand(1000, 9999);
$app->setUserState('verify',$verify );
return $verify;
}/***[/JCBGUI$$$$]***/
/**
* Load the Composer Vendors
*/
public static function composerAutoload($target)
{
// insure we load the composer vendor only once
if (!isset(self::$composer[$target]))
{
// get the function name
$functionName = self::safeString('compose' . $target);
// check if method exist
if (method_exists(__CLASS__, $functionName))
{
return self::{$functionName}();
}
return false;
}
return self::$composer[$target];
}
/**
* Convert it into a string
*/
public static function jsonToString($value, $sperator = ", ",
$table = null, $id = 'id', $name = 'name')
{
// do some table foot work
$external = false;
if (strpos($table, '#__') !== false)
{
$external = true;
$table = str_replace('#__', '', $table);
}
// check if string is JSON
$result = json_decode($value, true);
if (json_last_error() === JSON_ERROR_NONE)
{
// is JSON
if (self::checkArray($result))
{
if (self::checkString($table))
{
$names = array();
foreach ($result as $val)
{
if ($external)
{
if ($_name = self::getVar(null, $val, $id, $name, '=',
$table))
{
$names[] = $_name;
}
}
else
{
if ($_name = self::getVar($table, $val, $id, $name))
{
$names[] = $_name;
}
}
}
if (self::checkArray($names))
{
return (string) implode($sperator,$names);
}
}
return (string) implode($sperator,$result);
}
return (string) json_decode($value);
}
return $value;
}
/**
* Load the Component xml manifest.
*/
public static function manifest()
{
$manifestUrl =
JPATH_ADMINISTRATOR."/components/com_reservation/reservation.xml";
return simplexml_load_file($manifestUrl);
}
/**
* Joomla version object
*/
protected static $JVersion;
/**
* set/get Joomla version
*/
public static function jVersion()
{
// check if set
if (!self::checkObject(self::$JVersion))
{
self::$JVersion = new JVersion();
}
return self::$JVersion;
}
/**
* Load the Contributors details.
*/
public static function getContributors()
{
// get params
$params = JComponentHelper::getParams('com_reservation');
// start contributors array
$contributors = array();
// get all Contributors (max 20)
$searchArray = range('0','20');
foreach($searchArray as $nr)
{
if ((NULL !== $params->get("showContributor".$nr))
&& ($params->get("showContributor".$nr) == 2 ||
$params->get("showContributor".$nr) == 3))
{
// set link based of selected option
if($params->get("useContributor".$nr) == 1)
{
$link_front = '<a
href="mailto:'.$params->get("emailContributor".$nr).'"
target="_blank">';
$link_back = '</a>';
}
elseif($params->get("useContributor".$nr) == 2)
{
$link_front = '<a
href="'.$params->get("linkContributor".$nr).'"
target="_blank">';
$link_back = '</a>';
}
else
{
$link_front = '';
$link_back = '';
}
$contributors[$nr]['title'] =
self::htmlEscape($params->get("titleContributor".$nr));
$contributors[$nr]['name'] =
$link_front.self::htmlEscape($params->get("nameContributor".$nr)).$link_back;
}
}
return $contributors;
}
/**
* Can be used to build help urls.
**/
public static function getHelpUrl($view)
{
return false;
}
/**
* Get any component's model
*/
public static function getModel($name, $path = JPATH_COMPONENT_SITE,
$Component = 'Reservation', $config = array())
{
// fix the name
$name = self::safeString($name);
// full path to models
$fullPathModels = $path . '/models';
// load the model file
JModelLegacy::addIncludePath($fullPathModels, $Component .
'Model');
// make sure the table path is loaded
if (!isset($config['table_path']) ||
!self::checkString($config['table_path']))
{
// This is the JCB default path to tables in Joomla 3.x
$config['table_path'] = JPATH_ADMINISTRATOR .
'/components/com_' . strtolower($Component) .
'/tables';
}
// get instance
$model = JModelLegacy::getInstance($name, $Component . 'Model',
$config);
// if model not found (strange)
if ($model == false)
{
jimport('joomla.filesystem.file');
// get file path
$filePath = $path . '/' . $name . '.php';
$fullPathModel = $fullPathModels . '/' . $name .
'.php';
// check if it exists
if (File::exists($filePath))
{
// get the file
require_once $filePath;
}
elseif (File::exists($fullPathModel))
{
// get the file
require_once $fullPathModel;
}
// build class names
$modelClass = $Component . 'Model' . $name;
if (class_exists($modelClass))
{
// initialize the model
return new $modelClass($config);
}
}
return $model;
}
/**
* Add to asset Table
*/
public static function setAsset($id, $table, $inherit = true)
{
$parent = JTable::getInstance('Asset');
$parent->loadByName('com_reservation');
$parentId = $parent->id;
$name = 'com_reservation.'.$table.'.'.$id;
$title = '';
$asset = JTable::getInstance('Asset');
$asset->loadByName($name);
// Check for an error.
$error = $asset->getError();
if ($error)
{
return false;
}
else
{
// Specify how a new or moved node asset is inserted into the tree.
if ($asset->parent_id != $parentId)
{
$asset->setLocation($parentId, 'last-child');
}
// Prepare the asset to be stored.
$asset->parent_id = $parentId;
$asset->name = $name;
$asset->title = $title;
// get the default asset rules
$rules = self::getDefaultAssetRules('com_reservation', $table,
$inherit);
if ($rules instanceof JAccessRules)
{
$asset->rules = (string) $rules;
}
if (!$asset->check() || !$asset->store())
{
JFactory::getApplication()->enqueueMessage($asset->getError(),
'warning');
return false;
}
else
{
// Create an asset_id or heal one that is corrupted.
$object = new stdClass();
// Must be a valid primary key value.
$object->id = $id;
$object->asset_id = (int) $asset->id;
// Update their asset_id to link to the asset table.
return
JFactory::getDbo()->updateObject('#__reservation_'.$table,
$object, 'id');
}
}
return false;
}
/**
* Gets the default asset Rules for a component/view.
*/
protected static function getDefaultAssetRules($component, $view, $inherit
= true)
{
// if new or inherited
$assetId = 0;
// Only get the actual item rules if not inheriting
if (!$inherit)
{
// Need to find the asset id by the name of the component.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__assets'))
->where($db->quoteName('name') . ' = ' .
$db->quote($component));
$db->setQuery($query);
$db->execute();
// check that there is a value
if ($db->getNumRows())
{
// asset already set so use saved rules
$assetId = (int) $db->loadResult();
}
}
// get asset rules
$result = JAccess::getAssetRules($assetId);
if ($result instanceof JAccessRules)
{
$_result = (string) $result;
$_result = json_decode($_result);
foreach ($_result as $name => &$rule)
{
$v = explode('.', $name);
if ($view !== $v[0])
{
// remove since it is not part of this view
unset($_result->$name);
}
elseif ($inherit)
{
// clear the value since we inherit
$rule = array();
}
}
// check if there are any view values remaining
if (count((array) $_result))
{
$_result = json_encode($_result);
$_result = array($_result);
// Instantiate and return the JAccessRules object for the asset rules.
$rules = new JAccessRules($_result);
// return filtered rules
return $rules;
}
}
return $result;
}
/**
* xmlAppend
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param mixed $node A SimpleXMLElement node to append
to the XML element reference, or a stdClass object containing a comment
attribute to be injected before the XML node and a fieldXML attribute
containing a SimpleXMLElement
*
* @return null
*
*/
public static function xmlAppend(&$xml, $node)
{
if (!$node)
{
// element was not returned
return;
}
switch (get_class($node))
{
case 'stdClass':
if (property_exists($node, 'comment'))
{
self::xmlComment($xml, $node->comment);
}
if (property_exists($node, 'fieldXML'))
{
self::xmlAppend($xml, $node->fieldXML);
}
break;
case 'SimpleXMLElement':
$domXML = dom_import_simplexml($xml);
$domNode = dom_import_simplexml($node);
$domXML->appendChild($domXML->ownerDocument->importNode($domNode,
true));
$xml = simplexml_import_dom($domXML);
break;
}
}
/**
* xmlComment
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param string $comment The comment to inject
*
* @return null
*
*/
public static function xmlComment(&$xml, $comment)
{
$domXML = dom_import_simplexml($xml);
$domComment = new DOMComment($comment);
$nodeTarget = $domXML->ownerDocument->importNode($domComment,
true);
$domXML->appendChild($nodeTarget);
$xml = simplexml_import_dom($domXML);
}
/**
* xmlAddAttributes
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param array $attributes The attributes to apply to
the XML element
*
* @return null
*
*/
public static function xmlAddAttributes(&$xml, $attributes = array())
{
foreach ($attributes as $key => $value)
{
$xml->addAttribute($key, $value);
}
}
/**
* xmlAddOptions
*
* @param SimpleXMLElement $xml The XML element reference in
which to inject a comment
* @param array $options The options to apply to the
XML element
*
* @return void
*
*/
public static function xmlAddOptions(&$xml, $options = array())
{
foreach ($options as $key => $value)
{
$addOption = $xml->addChild('option');
$addOption->addAttribute('value', $key);
$addOption[] = $value;
}
}
/**
* get the field object
*
* @param array $attributes The array of attributes
* @param string $default The default of the field
* @param array $options The options to apply to the XML
element
*
* @return object
*
*/
public static function getFieldObject(&$attributes, $default =
'', $options = null)
{
// make sure we have attributes and a type value
if (self::checkArray($attributes) &&
isset($attributes['type']))
{
// make sure the form helper class is loaded
if (!method_exists('JFormHelper', 'loadFieldType'))
{
jimport('joomla.form.form');
}
// get field type
$field = JFormHelper::loadFieldType($attributes['type'],
true);
// get field xml
$XML = self::getFieldXML($attributes, $options);
// setup the field
$field->setup($XML, $default);
// return the field object
return $field;
}
return false;
}
/**
* get the field xml
*
* @param array $attributes The array of attributes
* @param array $options The options to apply to the XML
element
*
* @return object
*
*/
public static function getFieldXML(&$attributes, $options = null)
{
// make sure we have attributes and a type value
if (self::checkArray($attributes))
{
// start field xml
$XML = new SimpleXMLElement('<field/>');
// load the attributes
self::xmlAddAttributes($XML, $attributes);
// check if we have options
if (self::checkArray($options))
{
// load the options
self::xmlAddOptions($XML, $options);
}
// return the field xml
return $XML;
}
return false;
}
/**
* Render Bool Button
*
* @param array $args All the args for the button
* 0) name
* 1) additional (options class) // not used
at this time
* 2) default
* 3) yes (name)
* 4) no (name)
*
* @return string The input html of the button
*
*/
public static function renderBoolButton()
{
$args = func_get_args();
// check if there is additional button class
$additional = isset($args[1]) ? (string) $args[1] : ''; // not
used at this time
// button attributes
$buttonAttributes = array(
'type' => 'radio',
'name' => isset($args[0]) ? self::htmlEscape($args[0]) :
'bool_button',
'label' => isset($args[0]) ?
self::safeString(self::htmlEscape($args[0]), 'Ww') : 'Bool
Button', // not seen anyway
'class' => 'btn-group',
'filter' => 'INT',
'default' => isset($args[2]) ? (int) $args[2] : 0);
// set the button options
$buttonOptions = array(
'1' => isset($args[3]) ? self::htmlEscape($args[3]) :
'JYES',
'0' => isset($args[4]) ? self::htmlEscape($args[4]) :
'JNO');
// return the input
return self::getFieldObject($buttonAttributes,
$buttonAttributes['default'], $buttonOptions)->input;
}
/**
* Get a variable
*
* @param string $table The table from which to get the
variable
* @param string $where The value where
* @param string $whereString The target/field string where/name
* @param string $what The return field
* @param string $operator The operator between $whereString/field
and $where/value
* @param string $main The component in which the table is
found
*
* @return mix string/int/float
*
*/
public static function getVar($table, $where = null, $whereString =
'user', $what = 'id', $operator = '=', $main
= 'reservation')
{
if(!$where)
{
$where = JFactory::getUser()->id;
}
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query->select($db->quoteName(array($what)));
if (empty($table))
{
$query->from($db->quoteName('#__'.$main));
}
else
{
$query->from($db->quoteName('#__'.$main.'_'.$table));
}
if (is_numeric($where))
{
$query->where($db->quoteName($whereString) . '
'.$operator.' '.(int) $where);
}
elseif (is_string($where))
{
$query->where($db->quoteName($whereString) . '
'.$operator.' '. $db->quote((string)$where));
}
else
{
return false;
}
$db->setQuery($query);
$db->execute();
if ($db->getNumRows())
{
return $db->loadResult();
}
return false;
}
/**
* Get array of variables
*
* @param string $table The table from which to get the
variables
* @param string $where The value where
* @param string $whereString The target/field string where/name
* @param string $what The return field
* @param string $operator The operator between $whereString/field
and $where/value
* @param string $main The component in which the table is
found
* @param bool $unique The switch to return a unique array
*
* @return array
*
*/
public static function getVars($table, $where = null, $whereString =
'user', $what = 'id', $operator = 'IN', $main
= 'reservation', $unique = true)
{
if(!$where)
{
$where = JFactory::getUser()->id;
}
if (!self::checkArray($where) && $where > 0)
{
$where = array($where);
}
if (self::checkArray($where))
{
// prep main <-- why? well if $main='' is empty then $table
can be categories or users
if (self::checkString($main))
{
$main = '_'.ltrim($main, '_');
}
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query->select($db->quoteName(array($what)));
if (empty($table))
{
$query->from($db->quoteName('#__'.$main));
}
else
{
$query->from($db->quoteName('#_'.$main.'_'.$table));
}
// add strings to array search
if ('IN_STRINGS' === $operator || 'NOT IN_STRINGS'
=== $operator)
{
$query->where($db->quoteName($whereString) . ' ' .
str_replace('_STRINGS', '', $operator) . '
("' . implode('","',$where) .
'")');
}
else
{
$query->where($db->quoteName($whereString) . ' ' .
$operator . ' (' . implode(',',$where) .
')');
}
$db->setQuery($query);
$db->execute();
if ($db->getNumRows())
{
if ($unique)
{
return array_unique($db->loadColumn());
}
return $db->loadColumn();
}
}
return false;
}
public static function isPublished($id,$type)
{
if ($type == 'raw')
{
$type = 'item';
}
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array('a.published'));
$query->from('#__reservation_'.$type.' AS a');
$query->where('a.id = '. (int) $id);
$query->where('a.published = 1');
$db->setQuery($query);
$db->execute();
$found = $db->getNumRows();
if($found)
{
return true;
}
return false;
}
public static function getGroupName($id)
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(array('a.title'));
$query->from('#__usergroups AS a');
$query->where('a.id = '. (int) $id);
$db->setQuery($query);
$db->execute();
$found = $db->getNumRows();
if($found)
{
return $db->loadResult();
}
return $id;
}
/**
* Get the action permissions
*
* @param string $view The related view name
* @param int $record The item to act upon
* @param string $views The related list view name
* @param mixed $target Only get this permission (like edit,
create, delete)
* @param string $component The target component
* @param object $user The user whose permissions we are loading
*
* @return object The JObject of permission/authorised actions
*
*/
public static function getActions($view, &$record = null, $views =
null, $target = null, $component = 'reservation', $user =
'null')
{
// load the user if not given
if (!self::checkObject($user))
{
// get the user object
$user = JFactory::getUser();
}
// load the JObject
$result = new JObject;
// make view name safe (just incase)
$view = self::safeString($view);
if (self::checkString($views))
{
$views = self::safeString($views);
}
// get all actions from component
$actions = JAccess::getActionsFromFile(
JPATH_ADMINISTRATOR . '/components/com_' . $component .
'/access.xml',
"/access/section[@name='component']/"
);
// if non found then return empty JObject
if (empty($actions))
{
return $result;
}
// get created by if not found
if (self::checkObject($record) && !isset($record->created_by)
&& isset($record->id))
{
$record->created_by = self::getVar($view, $record->id,
'id', 'created_by', '=', $component);
}
// set actions only set in component settings
$componentActions = array('core.admin',
'core.manage', 'core.options',
'core.export');
// check if we have a target
$checkTarget = false;
if ($target)
{
// convert to an array
if (self::checkString($target))
{
$target = array($target);
}
// check if we are good to go
if (self::checkArray($target))
{
$checkTarget = true;
}
}
// loop the actions and set the permissions
foreach ($actions as $action)
{
// check target action filter
if ($checkTarget && self::filterActions($view, $action->name,
$target))
{
continue;
}
// set to use component default
$fallback = true;
// reset permission per/action
$permission = false;
$catpermission = false;
// set area
$area = 'comp';
// check if the record has an ID and the action is item related (not a
component action)
if (self::checkObject($record) && isset($record->id)
&& $record->id > 0 && !in_array($action->name,
$componentActions) &&
(strpos($action->name, 'core.') !== false ||
strpos($action->name, $view . '.') !== false))
{
// we are in item
$area = 'item';
// The record has been set. Check the record permissions.
$permission = $user->authorise($action->name, 'com_' .
$component . '.' . $view . '.' . (int) $record->id);
// if no permission found, check edit own
if (!$permission)
{
// With edit, if the created_by matches current user then dig deeper.
if (($action->name === 'core.edit' || $action->name
=== $view . '.edit') && $record->created_by > 0
&& ($record->created_by == $user->id))
{
// the correct target
$coreCheck = (array) explode('.', $action->name);
// check that we have both local and global access
if ($user->authorise($coreCheck[0] . '.edit.own',
'com_' . $component . '.' . $view . '.' .
(int) $record->id) &&
$user->authorise($coreCheck[0] . '.edit.own',
'com_' . $component))
{
// allow edit
$result->set($action->name, true);
// set not to use global default
// because we already validated it
$fallback = false;
}
else
{
// do not allow edit
$result->set($action->name, false);
$fallback = false;
}
}
}
elseif (self::checkString($views) && isset($record->catid)
&& $record->catid > 0)
{
// we are in item
$area = 'category';
// set the core check
$coreCheck = explode('.', $action->name);
$core = $coreCheck[0];
// make sure we use the core. action check for the categories
if (strpos($action->name, $view) !== false &&
strpos($action->name, 'core.') === false )
{
$coreCheck[0] = 'core';
$categoryCheck = implode('.', $coreCheck);
}
else
{
$categoryCheck = $action->name;
}
// The record has a category. Check the category permissions.
$catpermission = $user->authorise($categoryCheck, 'com_'
. $component . '.' . $views . '.category.' . (int)
$record->catid);
if (!$catpermission && !is_null($catpermission))
{
// With edit, if the created_by matches current user then dig deeper.
if (($action->name === 'core.edit' || $action->name
=== $view . '.edit') && $record->created_by > 0
&& ($record->created_by == $user->id))
{
// check that we have both local and global access
if ($user->authorise('core.edit.own', 'com_'
. $component . '.' . $views . '.category.' . (int)
$record->catid) &&
$user->authorise($core . '.edit.own', 'com_'
. $component))
{
// allow edit
$result->set($action->name, true);
// set not to use global default
// because we already validated it
$fallback = false;
}
else
{
// do not allow edit
$result->set($action->name, false);
$fallback = false;
}
}
}
}
}
// if allowed then fallback on component global settings
if ($fallback)
{
// if item/category blocks access then don't fall back on global
if ((($area === 'item') && !$permission) || (($area
=== 'category') && !$catpermission))
{
// do not allow
$result->set($action->name, false);
}
// Finally remember the global settings have the final say. (even if
item allow)
// The local item permissions can block, but it can't open and
override of global permissions.
// Since items are created by users and global permissions is set by
system admin.
else
{
$result->set($action->name,
$user->authorise($action->name, 'com_' . $component));
}
}
}
return $result;
}
/**
* Filter the action permissions
*
* @param string $action The action to check
* @param array $targets The array of target actions
*
* @return boolean true if action should be filtered out
*
*/
protected static function filterActions(&$view, &$action,
&$targets)
{
foreach ($targets as $target)
{
if (strpos($action, $view . '.' . $target) !== false ||
strpos($action, 'core.' . $target) !== false)
{
return false;
break;
}
}
return true;
}
/**
* Check if have an json string
*
* @input string The json string to check
*
* @returns bool true on success
*/
public static function checkJson($string)
{
if (self::checkString($string))
{
json_decode($string);
return (json_last_error() === JSON_ERROR_NONE);
}
return false;
}
/**
* Check if have an object with a length
*
* @input object The object to check
*
* @returns bool true on success
*/
public static function checkObject($object)
{
if (isset($object) && is_object($object))
{
return count((array)$object) > 0;
}
return false;
}
/**
* Check if have an array with a length
*
* @input array The array to check
*
* @returns bool/int number of items in array on success
*/
public static function checkArray($array, $removeEmptyString = false)
{
if (isset($array) && is_array($array) && ($nr =
count((array)$array)) > 0)
{
// also make sure the empty strings are removed
if ($removeEmptyString)
{
foreach ($array as $key => $string)
{
if (empty($string))
{
unset($array[$key]);
}
}
return self::checkArray($array, false);
}
return $nr;
}
return false;
}
/**
* Check if have a string with a length
*
* @input string The string to check
*
* @returns bool true on success
*/
public static function checkString($string)
{
if (isset($string) && is_string($string) &&
strlen($string) > 0)
{
return true;
}
return false;
}
/**
* Check if we are connected
* Thanks https://stackoverflow.com/a/4860432/1429677
*
* @returns bool true on success
*/
public static function isConnected()
{
// If example.com is down, then probably the whole internet is down,
since IANA maintains the domain. Right?
$connected = @fsockopen("www.example.com", 80);
// website, port (try 80 or 443)
if ($connected)
{
//action when connected
$is_conn = true;
fclose($connected);
}
else
{
//action in connection failure
$is_conn = false;
}
return $is_conn;
}
/**
* Merge an array of array's
*
* @input array The arrays you would like to merge
*
* @returns array on success
*/
public static function mergeArrays($arrays)
{
if(self::checkArray($arrays))
{
$arrayBuket = array();
foreach ($arrays as $array)
{
if (self::checkArray($array))
{
$arrayBuket = array_merge($arrayBuket, $array);
}
}
return $arrayBuket;
}
return false;
}
// typo sorry!
public static function sorten($string, $length = 40, $addTip = true)
{
return self::shorten($string, $length, $addTip);
}
/**
* Shorten a string
*
* @input string The you would like to shorten
*
* @returns string on success
*/
public static function shorten($string, $length = 40, $addTip = true)
{
if (self::checkString($string))
{
$initial = strlen($string);
$words = preg_split('/([\s\n\r]+)/', $string, null,
PREG_SPLIT_DELIM_CAPTURE);
$words_count = count((array)$words);
$word_length = 0;
$last_word = 0;
for (; $last_word < $words_count; ++$last_word)
{
$word_length += strlen($words[$last_word]);
if ($word_length > $length)
{
break;
}
}
$newString = implode(array_slice($words, 0, $last_word));
$final = strlen($newString);
if ($initial != $final && $addTip)
{
$title = self::shorten($string, 400 , false);
return '<span class="hasTip"
title="'.$title.'"
style="cursor:help">'.trim($newString).'...</span>';
}
elseif ($initial != $final && !$addTip)
{
return trim($newString).'...';
}
}
return $string;
}
/**
* Making strings safe (various ways)
*
* @input string The you would like to make safe
*
* @returns string on success
*/
public static function safeString($string, $type = 'L', $spacer
= '_', $replaceNumbers = true, $keepOnlyCharacters = true)
{
if ($replaceNumbers === true)
{
// remove all numbers and replace with english text version (works well
only up to millions)
$string = self::replaceNumbers($string);
}
// 0nly continue if we have a string
if (self::checkString($string))
{
// create file name without the extention that is safe
if ($type === 'filename')
{
// make sure VDM is not in the string
$string = str_replace('VDM', 'vDm', $string);
// Remove anything which isn't a word, whitespace, number
// or any of the following caracters -_()
// If you don't need to handle multi-byte characters
// you can use preg_replace rather than mb_ereg_replace
// Thanks @Łukasz Rysiak!
// $string = mb_ereg_replace("([^\w\s\d\-_\(\)])",
'', $string);
$string = preg_replace("([^\w\s\d\-_\(\)])", '',
$string);
// http://stackoverflow.com/a/2021729/1429677
return preg_replace('/\s+/', ' ', $string);
}
// remove all other characters
$string = trim($string);
$string = preg_replace('/'.$spacer.'+/', '
', $string);
$string = preg_replace('/\s+/', ' ', $string);
// Transliterate string
$string = self::transliterate($string);
// remove all and keep only characters
if ($keepOnlyCharacters)
{
$string = preg_replace("/[^A-Za-z ]/", '',
$string);
}
// keep both numbers and characters
else
{
$string = preg_replace("/[^A-Za-z0-9 ]/", '',
$string);
}
// select final adaptations
if ($type === 'L' || $type === 'strtolower')
{
// replace white space with underscore
$string = preg_replace('/\s+/', $spacer, $string);
// default is to return lower
return strtolower($string);
}
elseif ($type === 'W')
{
// return a string with all first letter of each word uppercase(no
undersocre)
return ucwords(strtolower($string));
}
elseif ($type === 'w' || $type === 'word')
{
// return a string with all lowercase(no undersocre)
return strtolower($string);
}
elseif ($type === 'Ww' || $type === 'Word')
{
// return a string with first letter of the first word uppercase and
all the rest lowercase(no undersocre)
return ucfirst(strtolower($string));
}
elseif ($type === 'WW' || $type === 'WORD')
{
// return a string with all the uppercase(no undersocre)
return strtoupper($string);
}
elseif ($type === 'U' || $type === 'strtoupper')
{
// replace white space with underscore
$string = preg_replace('/\s+/', $spacer, $string);
// return all upper
return strtoupper($string);
}
elseif ($type === 'F' || $type === 'ucfirst')
{
// replace white space with underscore
$string = preg_replace('/\s+/', $spacer, $string);
// return with first caracter to upper
return ucfirst(strtolower($string));
}
elseif ($type === 'cA' || $type === 'cAmel' || $type
=== 'camelcase')
{
// convert all words to first letter uppercase
$string = ucwords(strtolower($string));
// remove white space
$string = preg_replace('/\s+/', '', $string);
// now return first letter lowercase
return lcfirst($string);
}
// return string
return $string;
}
// not a string
return '';
}
public static function transliterate($string)
{
// set tag only once
if (!self::checkString(self::$langTag))
{
// get global value
self::$langTag =
JComponentHelper::getParams('com_reservation')->get('language',
'en-GB');
}
// Transliterate on the language requested
$lang = Language::getInstance(self::$langTag);
return $lang->transliterate($string);
}
public static function htmlEscape($var, $charset = 'UTF-8',
$shorten = false, $length = 40)
{
if (self::checkString($var))
{
$filter = new JFilterInput();
$string = $filter->clean(html_entity_decode(htmlentities($var,
ENT_COMPAT, $charset)), 'HTML');
if ($shorten)
{
return self::shorten($string,$length);
}
return $string;
}
else
{
return '';
}
}
public static function replaceNumbers($string)
{
// set numbers array
$numbers = array();
// first get all numbers
preg_match_all('!\d+!', $string, $numbers);
// check if we have any numbers
if (isset($numbers[0]) && self::checkArray($numbers[0]))
{
foreach ($numbers[0] as $number)
{
$searchReplace[$number] = self::numberToString((int)$number);
}
// now replace numbers in string
$string = str_replace(array_keys($searchReplace),
array_values($searchReplace),$string);
// check if we missed any, strange if we did.
return self::replaceNumbers($string);
}
// return the string with no numbers remaining.
return $string;
}
/**
* Convert an integer into an English word string
* Thanks to Tom Nicholson
<http://php.net/manual/en/function.strval.php#41988>
*
* @input an int
* @returns a string
*/
public static function numberToString($x)
{
$nwords = array( "zero", "one", "two",
"three", "four", "five", "six",
"seven",
"eight", "nine", "ten",
"eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen",
"seventeen", "eighteen",
"nineteen", "twenty", 30 => "thirty",
40 => "forty",
50 => "fifty", 60 => "sixty", 70 =>
"seventy", 80 => "eighty",
90 => "ninety" );
if(!is_numeric($x))
{
$w = $x;
}
elseif(fmod($x, 1) != 0)
{
$w = $x;
}
else
{
if($x < 0)
{
$w = 'minus ';
$x = -$x;
}
else
{
$w = '';
// ... now $x is a non-negative integer.
}
if($x < 21) // 0 to 20
{
$w .= $nwords[$x];
}
elseif($x < 100) // 21 to 99
{
$w .= $nwords[10 * floor($x/10)];
$r = fmod($x, 10);
if($r > 0)
{
$w .= ' '. $nwords[$r];
}
}
elseif($x < 1000) // 100 to 999
{
$w .= $nwords[floor($x/100)] .' hundred';
$r = fmod($x, 100);
if($r > 0)
{
$w .= ' and '. self::numberToString($r);
}
}
elseif($x < 1000000) // 1000 to 999999
{
$w .= self::numberToString(floor($x/1000)) .' thousand';
$r = fmod($x, 1000);
if($r > 0)
{
$w .= ' ';
if($r < 100)
{
$w .= 'and ';
}
$w .= self::numberToString($r);
}
}
else // millions
{
$w .= self::numberToString(floor($x/1000000)) .' million';
$r = fmod($x, 1000000);
if($r > 0)
{
$w .= ' ';
if($r < 100)
{
$w .= 'and ';
}
$w .= self::numberToString($r);
}
}
}
return $w;
}
/**
* Random Key
*
* @returns a string
*/
public static function randomkey($size)
{
$bag =
"abcefghijknopqrstuwxyzABCDDEFGHIJKLLMMNOPQRSTUVVWXYZabcddefghijkllmmnopqrstuvvwxyzABCEFGHIJKNOPQRSTUWXYZ";
$key = array();
$bagsize = strlen($bag) - 1;
for ($i = 0; $i < $size; $i++)
{
$get = rand(0, $bagsize);
$key[] = $bag[$get];
}
return implode($key);
}
}
reserve.php000064400000015026151165544530006745 0ustar00<?php
interface validation
{
function dovalidation();
}
class default_personalinfo implements validation
{
public function dovalidation()
{
$this->app= JFactory::getApplication();
$personalInfo=
$this->app->input->get('jform',array(),
'array');
$this->app->setUserState('data.personalinfo',
$personalInfo);
return true;
}
}
class default_policy implements validation
{
public function dovalidation()
{
$this->app= JFactory::getApplication();
$data= $this->app->input->get('jform',array(),
'array');
return true;
}
}
class default_payment implements validation
{
public function dovalidation()
{
$this->app= JFactory::getApplication();
$payment_method=
$this->app->input->post->get('payment_method');
$strategy= new strategy();
if ($payment_method)
$strategy->do_request();
else
$verify_result= $strategy->do_verify();
if ($verify_result)
return true;
return false;
}
}
class reserve
{
public function __construct()
{
defined('_JEXEC') or die('Restricted access');
$this->app= JFactory::getApplication();
$payment_method_from_qs=
$this->app->input->get->get('payment_method');
if (!$payment_method_from_qs)
JSession::checkToken('post') or die('invalid
token');
$layout= $this->getLayout();
$obj = new $layout;
$result= $obj->dovalidation();
if ($result)
$this->nextStep();
$this->app->redirect((string)JUri::getInstance());
//
$this->app->redirect(JRoute::_('index.php?option=com_reservation&view=reserve'));
}
private function getLayout()
{
require_once
JPATH_SITE.'/components/com_reservation/controllers/reserve.php';
$controller = new ReservationControllerReserve;
return $controller->getLayout();
}
private function nextStep()
{
$function_to_be_executed=
$this->app->getUserState('function_to_be_executed',0);
$this->app->setUserState('function_to_be_executed',++$function_to_be_executed);
}
}
interface payment
{
function request();
function verify();
}
class zarinpal implements payment
{
public function __construct()
{
require_once JPATH_ADMINISTRATOR .
'/components/com_reservation/models/reserve.php';
$this->app= JFactory::getApplication();
$this->user= JFactory::getUser();
$this->aid= $this->app->input->get('aid');
$this->uid= $this->app->input->get('uid');
$this->params=
JComponentHelper::getParams('com_reservation');
$this->full_price= 12000;
$this->doctor_quota= 60;
$this->system_quota= 40;
}
function request()
{
$sickid= ReservationHelper::exist('#__reservation_sick',
'userid', $this->user->id);
$data = array(
'sickid' => $sickid,
'full_price' => $this->full_price,
'doctor_quota' => $this->full_price *
($this->doctor_quota/100),
'system_quota' => $this->full_price *
($this->system_quota/100),
'appointmentid' => $this->aid,
'status' => 'created'
);
$reserve= new ReservationModelReserve;
if (!$reserve->save($data))
return false;
$reserve_id= $reserve->getState('reserve.id');
$requestUrl =
'https://sandbox.zarinpal.com/pg/services/WebGate/wsdl';
$client = new SoapClient($requestUrl, ['encoding' =>
'UTF-8']);
$result = $client->PaymentRequest(
[
'MerchantID' =>
"aaaaaaaabaaaabaaaabaaaacaaaaaaaaaaaa",
'Amount' => $this->full_price,
'Description' => "خرید تست",
'CallbackURL' =>
"http://www.lmsyaran.ir/index.php?option=com_reservation&view=reserve_appointment&payment_method=zarinpal&aid=".$this->aid."&uid=".$this->uid."&reserveid=".$reserve_id,
]
);
if ($result->Status == 100) {
header('Location:
https://sandbox.zarinpal.com/pg/StartPay/' . $result->Authority);
exit();
}
}
function verify()
{
$Authority=
$this->app->input->get->get('Authority');
$statue= $this->app->input->get('Status');
$reserve_id=
$this->app->input->get('reserveid');
$data= array(
'id' => $reserve_id,
'status' => 'confirmed'
);
if ($Authority)
{
$requestUrl =
'https://sandbox.zarinpal.com/pg/services/WebGate/wsdl';
$client = new SoapClient($requestUrl, ['encoding'
=> 'UTF-8']);
$result = $client->PaymentVerification(
[
'MerchantID' =>
'aaaaaaaabaaaabaaaabaaaacaaaaaaaaaaaa',
'Authority' => $Authority,
'Amount' => $this->full_price,
]
);
$uri= JUri::getInstance();
$uri->delVar('Authority');
$uri->delVar('payment_method');
$uri->delVar('Status');
if ($statue== 'OK')
{
if ($result->Status== 100)
{
$reserve = new ReservationModelReserve;
$reserve->save($data);
return true;
}
}
}
$this->app->enqueueMessage('پرداخت شما با
شکست روبرو شد . لطفا دوباره عمل پرداخت را
انجام دهید', 'warning');
return false;
}
}
class strategy
{
public function do_request()
{
$this->app= JFactory::getApplication();
$this->payment_method=
$this->app->input->post->get('payment_method',
'zarinpal');
if (class_exists($this->payment_method))
{
$object = new $this->payment_method;
if ($object instanceof payment)
$object->request();
}
}
public function do_verify()
{
$this->app= JFactory::getApplication();
$this->payment_method=
$this->app->input->get->get('payment_method',
'zarinpal');
if (class_exists($this->payment_method))
{
$object = new $this->payment_method;
if ($object instanceof payment)
return $object->verify();
}
}
}html/filter.php000064400000033711151165607370007526 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\Registry\Registry;
JLoader::register('FinderHelperLanguage', JPATH_ADMINISTRATOR .
'/components/com_finder/helpers/language.php');
/**
* Filter HTML Behaviors for Finder.
*
* @since 2.5
*/
abstract class JHtmlFilter
{
/**
* Method to generate filters using the slider widget and decorated
* with the FinderFilter JavaScript behaviors.
*
* @param array $options An array of configuration options. [optional]
*
* @return mixed A rendered HTML widget on success, null otherwise.
*
* @since 2.5
*/
public static function slider($options = array())
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$user = JFactory::getUser();
$groups = implode(',', $user->getAuthorisedViewLevels());
$html = '';
$filter = null;
// Get the configuration options.
$filterId = array_key_exists('filter_id', $options) ?
$options['filter_id'] : null;
$activeNodes = array_key_exists('selected_nodes', $options) ?
$options['selected_nodes'] : array();
$classSuffix = array_key_exists('class_suffix', $options) ?
$options['class_suffix'] : '';
// Load the predefined filter if specified.
if (!empty($filterId))
{
$query->select('f.data, f.params')
->from($db->quoteName('#__finder_filters') . ' AS
f')
->where('f.filter_id = ' . (int) $filterId);
// Load the filter data.
$db->setQuery($query);
try
{
$filter = $db->loadObject();
}
catch (RuntimeException $e)
{
return null;
}
// Initialize the filter parameters.
if ($filter)
{
$filter->params = new Registry($filter->params);
}
}
// Build the query to get the branch data and the number of child nodes.
$query->clear()
->select('t.*, count(c.id) AS children')
->from($db->quoteName('#__finder_taxonomy') . ' AS
t')
->join('INNER',
$db->quoteName('#__finder_taxonomy') . ' AS c ON
c.parent_id = t.id')
->where('t.parent_id = 1')
->where('t.state = 1')
->where('t.access IN (' . $groups . ')')
->group('t.id, t.parent_id, t.state, t.access, t.ordering,
t.title, c.parent_id')
->order('t.ordering, t.title');
// Limit the branch children to a predefined filter.
if ($filter)
{
$query->where('c.id IN(' . $filter->data .
')');
}
// Load the branches.
$db->setQuery($query);
try
{
$branches = $db->loadObjectList('id');
}
catch (RuntimeException $e)
{
return null;
}
// Check that we have at least one branch.
if (count($branches) === 0)
{
return null;
}
$branch_keys = array_keys($branches);
$html .= JHtml::_('bootstrap.startAccordion',
'accordion', array('parent' => true,
'active' => 'accordion-' . $branch_keys[0])
);
// Load plugin language files.
FinderHelperLanguage::loadPluginLanguage();
// Iterate through the branches and build the branch groups.
foreach ($branches as $bk => $bv)
{
// If the multi-lang plugin is enabled then drop the language branch.
if ($bv->title === 'Language' &&
JLanguageMultilang::isEnabled())
{
continue;
}
// Build the query to get the child nodes for this branch.
$query->clear()
->select('t.*')
->from($db->quoteName('#__finder_taxonomy') . ' AS
t')
->where('t.parent_id = ' . (int) $bk)
->where('t.state = 1')
->where('t.access IN (' . $groups . ')')
->order('t.ordering, t.title');
// Self-join to get the parent title.
$query->select('e.title AS parent_title')
->join('LEFT',
$db->quoteName('#__finder_taxonomy', 'e') . '
ON ' . $db->quoteName('e.id') . ' = ' .
$db->quoteName('t.parent_id'));
// Load the branches.
$db->setQuery($query);
try
{
$nodes = $db->loadObjectList('id');
}
catch (RuntimeException $e)
{
return null;
}
// Translate node titles if possible.
$lang = JFactory::getLanguage();
foreach ($nodes as $nk => $nv)
{
if (trim($nv->parent_title, '**') ===
'Language')
{
$title = FinderHelperLanguage::branchLanguageTitle($nv->title);
}
else
{
$key = FinderHelperLanguage::branchPlural($nv->title);
$title = $lang->hasKey($key) ? JText::_($key) : $nv->title;
}
$nodes[$nk]->title = $title;
}
// Adding slides
$html .= JHtml::_('bootstrap.addSlide',
'accordion',
JText::sprintf('COM_FINDER_FILTER_BRANCH_LABEL',
JText::_(FinderHelperLanguage::branchSingular($bv->title)) . '
- ' . count($nodes)
),
'accordion-' . $bk
);
// Populate the toggle button.
$html .= '<button class="btn jform-rightbtn"
type="button"
onclick="jQuery(\'[id="tax-'
. $bk .
'"]\').each(function(){this.click();});"><span
class="icon-checkbox-partial"></span> '
. JText::_('JGLOBAL_SELECTION_INVERT') .
'</button><hr/>';
// Populate the group with nodes.
foreach ($nodes as $nk => $nv)
{
// Determine if the node should be checked.
$checked = in_array($nk, $activeNodes) ? '
checked="checked"' : '';
// Build a node.
$html .= '<div class="control-group">';
$html .= '<div class="controls">';
$html .= '<label class="checkbox">';
$html .= '<input type="checkbox" class="selector
filter-node' . $classSuffix . '" value="' . $nk .
'" name="t[]" id="tax-'
. $bk . '"' . $checked . ' />';
$html .= $nv->title;
$html .= '</label>';
$html .= '</div>';
$html .= '</div>';
}
$html .= JHtml::_('bootstrap.endSlide');
}
$html .= JHtml::_('bootstrap.endAccordion');
return $html;
}
/**
* Method to generate filters using select box dropdown controls.
*
* @param FinderIndexerQuery $idxQuery A FinderIndexerQuery object.
* @param array $options An array of options.
*
* @return mixed A rendered HTML widget on success, null otherwise.
*
* @since 2.5
*/
public static function select($idxQuery, $options)
{
$user = JFactory::getUser();
$groups = implode(',', $user->getAuthorisedViewLevels());
$filter = null;
// Get the configuration options.
$classSuffix = $options->get('class_suffix', null);
$showDates = $options->get('show_date_filters', false);
// Try to load the results from cache.
$cache = JFactory::getCache('com_finder', '');
$cacheId = 'filter_select_' .
serialize(array($idxQuery->filter, $options, $groups,
JFactory::getLanguage()->getTag()));
// Check the cached results.
if ($cache->contains($cacheId))
{
$branches = $cache->get($cacheId);
}
else
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Load the predefined filter if specified.
if (!empty($idxQuery->filter))
{
$query->select('f.data, ' .
$db->quoteName('f.params'))
->from($db->quoteName('#__finder_filters') . ' AS
f')
->where('f.filter_id = ' . (int) $idxQuery->filter);
// Load the filter data.
$db->setQuery($query);
try
{
$filter = $db->loadObject();
}
catch (RuntimeException $e)
{
return null;
}
// Initialize the filter parameters.
if ($filter)
{
$filter->params = new Registry($filter->params);
}
}
// Build the query to get the branch data and the number of child nodes.
$query->clear()
->select('t.*, count(c.id) AS children')
->from($db->quoteName('#__finder_taxonomy') . ' AS
t')
->join('INNER',
$db->quoteName('#__finder_taxonomy') . ' AS c ON
c.parent_id = t.id')
->where('t.parent_id = 1')
->where('t.state = 1')
->where('t.access IN (' . $groups . ')')
->where('c.state = 1')
->where('c.access IN (' . $groups . ')')
->group($db->quoteName('t.id'))
->order('t.ordering, t.title');
// Limit the branch children to a predefined filter.
if (!empty($filter->data))
{
$query->where('c.id IN(' . $filter->data .
')');
}
// Load the branches.
$db->setQuery($query);
try
{
$branches = $db->loadObjectList('id');
}
catch (RuntimeException $e)
{
return null;
}
// Check that we have at least one branch.
if (count($branches) === 0)
{
return null;
}
// Iterate through the branches and build the branch groups.
foreach ($branches as $bk => $bv)
{
// If the multi-lang plugin is enabled then drop the language branch.
if ($bv->title === 'Language' &&
JLanguageMultilang::isEnabled())
{
continue;
}
// Build the query to get the child nodes for this branch.
$query->clear()
->select('t.*')
->from($db->quoteName('#__finder_taxonomy') . '
AS t')
->where('t.parent_id = ' . (int) $bk)
->where('t.state = 1')
->where('t.access IN (' . $groups . ')')
->order('t.ordering, t.title');
// Self-join to get the parent title.
$query->select('e.title AS parent_title')
->join('LEFT',
$db->quoteName('#__finder_taxonomy', 'e') . '
ON ' . $db->quoteName('e.id') . ' = ' .
$db->quoteName('t.parent_id'));
// Limit the nodes to a predefined filter.
if (!empty($filter->data))
{
$query->where('t.id IN(' . $filter->data .
')');
}
// Load the branches.
$db->setQuery($query);
try
{
$branches[$bk]->nodes = $db->loadObjectList('id');
}
catch (RuntimeException $e)
{
return null;
}
// Translate branch nodes if possible.
$language = JFactory::getLanguage();
foreach ($branches[$bk]->nodes as $node_id => $node)
{
if (trim($node->parent_title, '**') ===
'Language')
{
$title = FinderHelperLanguage::branchLanguageTitle($node->title);
}
else
{
$key = FinderHelperLanguage::branchPlural($node->title);
$title = $language->hasKey($key) ? JText::_($key) :
$node->title;
}
$branches[$bk]->nodes[$node_id]->title = $title;
}
// Add the Search All option to the branch.
array_unshift($branches[$bk]->nodes, array('id' =>
null, 'title' =>
JText::_('COM_FINDER_FILTER_SELECT_ALL_LABEL')));
}
// Store the data in cache.
$cache->store($branches, $cacheId);
}
$html = '';
// Add the dates if enabled.
if ($showDates)
{
$html .= JHtml::_('filter.dates', $idxQuery, $options);
}
$html .= '<div class="filter-branch' . $classSuffix .
' control-group clearfix">';
// Iterate through all branches and build code.
foreach ($branches as $bk => $bv)
{
// If the multi-lang plugin is enabled then drop the language branch.
if ($bv->title === 'Language' &&
JLanguageMultilang::isEnabled())
{
continue;
}
$active = null;
// Check if the branch is in the filter.
if (array_key_exists($bv->title, $idxQuery->filters))
{
// Get the request filters.
$temp =
JFactory::getApplication()->input->request->get('t',
array(), 'array');
// Search for active nodes in the branch and get the active node.
$active = array_intersect($temp, $idxQuery->filters[$bv->title]);
$active = count($active) === 1 ? array_shift($active) : null;
}
// Build a node.
$html .= '<div class="controls
finder-selects">';
$html .= '<label for="tax-' .
JFilterOutput::stringURLSafe($bv->title) . '"
class="control-label">';
$html .= JText::sprintf('COM_FINDER_FILTER_BRANCH_LABEL',
JText::_(FinderHelperLanguage::branchSingular($bv->title)));
$html .= '</label>';
$html .= '<br />';
$html .= JHtml::_(
'select.genericlist',
$branches[$bk]->nodes, 't[]', 'class="inputbox
advancedSelect"', 'id', 'title', $active,
'tax-' . JFilterOutput::stringURLSafe($bv->title)
);
$html .= '</div>';
}
$html .= '</div>';
return $html;
}
/**
* Method to generate fields for filtering dates
*
* @param FinderIndexerQuery $idxQuery A FinderIndexerQuery object.
* @param array $options An array of options.
*
* @return mixed A rendered HTML widget on success, null otherwise.
*
* @since 2.5
*/
public static function dates($idxQuery, $options)
{
$html = '';
// Get the configuration options.
$classSuffix = $options->get('class_suffix', null);
$loadMedia = $options->get('load_media', true);
$showDates = $options->get('show_date_filters', false);
if (!empty($showDates))
{
// Build the date operators options.
$operators = array();
$operators[] = JHtml::_('select.option', 'before',
JText::_('COM_FINDER_FILTER_DATE_BEFORE'));
$operators[] = JHtml::_('select.option', 'exact',
JText::_('COM_FINDER_FILTER_DATE_EXACTLY'));
$operators[] = JHtml::_('select.option', 'after',
JText::_('COM_FINDER_FILTER_DATE_AFTER'));
// Load the CSS/JS resources.
if ($loadMedia)
{
JHtml::_('stylesheet', 'com_finder/dates.css',
array('version' => 'auto', 'relative'
=> true));
}
// Open the widget.
$html .= '<ul
id="finder-filter-select-dates">';
// Start date filter.
$attribs['class'] = 'input-medium';
$html .= '<li class="filter-date' . $classSuffix .
'">';
$html .= '<label for="filter_date1"
class="hasTooltip" title ="' .
JText::_('COM_FINDER_FILTER_DATE1_DESC') .
'">';
$html .= JText::_('COM_FINDER_FILTER_DATE1');
$html .= '</label>';
$html .= '<br />';
$html .= JHtml::_(
'select.genericlist',
$operators, 'w1', 'class="inputbox
filter-date-operator advancedSelect"', 'value',
'text', $idxQuery->when1, 'finder-filter-w1'
);
$html .= JHtml::_('calendar', $idxQuery->date1,
'd1', 'filter_date1', '%Y-%m-%d', $attribs);
$html .= '</li>';
// End date filter.
$html .= '<li class="filter-date' . $classSuffix .
'">';
$html .= '<label for="filter_date2"
class="hasTooltip" title ="' .
JText::_('COM_FINDER_FILTER_DATE2_DESC') .
'">';
$html .= JText::_('COM_FINDER_FILTER_DATE2');
$html .= '</label>';
$html .= '<br />';
$html .= JHtml::_(
'select.genericlist',
$operators, 'w2', 'class="inputbox
filter-date-operator advancedSelect"', 'value',
'text', $idxQuery->when2, 'finder-filter-w2'
);
$html .= JHtml::_('calendar', $idxQuery->date2,
'd2', 'filter_date2', '%Y-%m-%d', $attribs);
$html .= '</li>';
// Close the widget.
$html .= '</ul>';
}
return $html;
}
}
html/query.php000064400000010772151165607370007410 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;
/**
* Query HTML behavior class for Finder.
*
* @since 2.5
*/
abstract class JHtmlQuery
{
/**
* Method to get the explained (human-readable) search query.
*
* @param FinderIndexerQuery $query A FinderIndexerQuery object to
explain.
*
* @return mixed String if there is data to explain, null otherwise.
*
* @since 2.5
*/
public static function explained(FinderIndexerQuery $query)
{
$parts = array();
// Process the required tokens.
foreach ($query->included as $token)
{
if ($token->required && (!isset($token->derived) ||
$token->derived == false))
{
$parts[] = '<span class="query-required">' .
JText::sprintf('COM_FINDER_QUERY_TOKEN_REQUIRED',
$token->term) . '</span>';
}
}
// Process the optional tokens.
foreach ($query->included as $token)
{
if (!$token->required && (!isset($token->derived) ||
$token->derived == false))
{
$parts[] = '<span class="query-optional">' .
JText::sprintf('COM_FINDER_QUERY_TOKEN_OPTIONAL',
$token->term) . '</span>';
}
}
// Process the excluded tokens.
foreach ($query->excluded as $token)
{
if (!isset($token->derived) || $token->derived === false)
{
$parts[] = '<span class="query-excluded">' .
JText::sprintf('COM_FINDER_QUERY_TOKEN_EXCLUDED',
$token->term) . '</span>';
}
}
// Process the start date.
if ($query->date1)
{
$date =
JFactory::getDate($query->date1)->format(JText::_('DATE_FORMAT_LC'));
$datecondition = JText::_('COM_FINDER_QUERY_DATE_CONDITION_' .
strtoupper($query->when1));
$parts[] = '<span class="query-start-date">' .
JText::sprintf('COM_FINDER_QUERY_START_DATE', $datecondition,
$date) . '</span>';
}
// Process the end date.
if ($query->date2)
{
$date =
JFactory::getDate($query->date2)->format(JText::_('DATE_FORMAT_LC'));
$datecondition = JText::_('COM_FINDER_QUERY_DATE_CONDITION_' .
strtoupper($query->when2));
$parts[] = '<span class="query-end-date">' .
JText::sprintf('COM_FINDER_QUERY_END_DATE', $datecondition,
$date) . '</span>';
}
// Process the taxonomy filters.
if (!empty($query->filters))
{
// Get the filters in the request.
$t =
JFactory::getApplication()->input->request->get('t',
array(), 'array');
// Process the taxonomy branches.
foreach ($query->filters as $branch => $nodes)
{
// Process the taxonomy nodes.
$lang = JFactory::getLanguage();
foreach ($nodes as $title => $id)
{
// Translate the title for Types
$key = FinderHelperLanguage::branchPlural($title);
if ($lang->hasKey($key))
{
$title = JText::_($key);
}
// Don't include the node if it is not in the request.
if (!in_array($id, $t))
{
continue;
}
// Add the node to the explanation.
$parts[] = '<span class="query-taxonomy">'
. JText::sprintf('COM_FINDER_QUERY_TAXONOMY_NODE', $title,
JText::_(FinderHelperLanguage::branchSingular($branch)))
. '</span>';
}
}
}
// Build the interpreted query.
return count($parts) ?
JText::sprintf('COM_FINDER_QUERY_TOKEN_INTERPRETED',
implode(JText::_('COM_FINDER_QUERY_TOKEN_GLUE'), $parts)) : null;
}
/**
* Method to get the suggested search query.
*
* @param FinderIndexerQuery $query A FinderIndexerQuery object.
*
* @return mixed String if there is a suggestion, false otherwise.
*
* @since 2.5
*/
public static function suggested(FinderIndexerQuery $query)
{
$suggested = false;
// Check if the query input is empty.
if (empty($query->input))
{
return $suggested;
}
// Check if there were any ignored or included keywords.
if (count($query->ignored) || count($query->included))
{
$suggested = $query->input;
// Replace the ignored keyword suggestions.
foreach (array_reverse($query->ignored) as $token)
{
if (isset($token->suggestion))
{
$suggested = str_ireplace($token->term, $token->suggestion,
$suggested);
}
}
// Replace the included keyword suggestions.
foreach (array_reverse($query->included) as $token)
{
if (isset($token->suggestion))
{
$suggested = str_ireplace($token->term, $token->suggestion,
$suggested);
}
}
// Check if we made any changes.
if ($suggested == $query->input)
{
$suggested = false;
}
}
return $suggested;
}
}
assignment.php000064400000002561151166122710007433 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLAssignment
extends \RegularLabs\Library\Condition
{
function pass($pass = true, $include_type = null)
{
return $this->_($pass, $include_type);
}
public function passByPageTypes($option, $selection = [], $assignment =
'all', $add_view = false, $get_task = false, $get_layout = true)
{
return $this->passByPageType($option, $selection, $assignment,
$add_view, $get_task, $get_layout);
}
public function passContentIds()
{
return $this->passContentId();
}
public function passContentKeywords($fields = ['title',
'introtext', 'fulltext'], $text = '')
{
return $this->passContentKeyword($fields, $text);
}
public function passMetaKeywords($field = 'metakey', $keywords =
'')
{
return $this->passMetaKeyword($field, $keywords);
}
public function passAuthors($field = 'created_by', $author =
'')
{
return $this->passAuthors($field, $author);
}
}
assignments/agents.php000064400000007077151166122720011107 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
require_once dirname(__DIR__) . '/text.php';
require_once dirname(__DIR__) . '/mobile_detect.php';
class RLAssignmentsAgents extends RLAssignment
{
var $agent = null;
var $device = null;
/**
* passBrowsers
*/
public function passBrowsers()
{
if (empty($this->selection))
{
return $this->pass(false);
}
foreach ($this->selection as $browser)
{
if ( ! $this->passBrowser($browser))
{
continue;
}
return $this->pass(true);
}
return $this->pass(false);
}
/**
* passOS
*/
public function passOS()
{
return self::passBrowsers();
}
/**
* passDevices
*/
public function passDevices()
{
$pass = (in_array('mobile', $this->selection) &&
$this->isMobile())
|| (in_array('tablet', $this->selection) &&
$this->isTablet())
|| (in_array('desktop', $this->selection) &&
$this->isDesktop());
return $this->pass($pass);
}
/**
* isPhone
*/
public function isPhone()
{
return $this->isMobile();
}
/**
* isMobile
*/
public function isMobile()
{
return $this->getDevice() == 'mobile';
}
/**
* isTablet
*/
public function isTablet()
{
return $this->getDevice() == 'tablet';
}
/**
* isDesktop
*/
public function isDesktop()
{
return $this->getDevice() == 'desktop';
}
/**
* setDevice
*/
private function getDevice()
{
if ( ! is_null($this->device))
{
return $this->device;
}
$detect = new RLMobile_Detect;
$this->is_mobile = $detect->isMobile();
switch (true)
{
case($detect->isTablet()):
$this->device = 'tablet';
break;
case ($detect->isMobile()):
$this->device = 'mobile';
break;
default:
$this->device = 'desktop';
}
return $this->device;
}
/**
* getAgent
*/
private function getAgent()
{
if ( ! is_null($this->agent))
{
return $this->agent;
}
$detect = new RLMobile_Detect;
$agent = $detect->getUserAgent();
switch (true)
{
case (stripos($agent, 'Trident') !== false):
// Add MSIE to IE11
$agent = preg_replace('#(Trident/[0-9\.]+;
rv:([0-9\.]+))#is', '\1 MSIE \2', $agent);
break;
case (stripos($agent, 'Chrome') !== false):
// Remove Safari from Chrome
$agent = preg_replace('#(Chrome/.*)Safari/[0-9\.]*#is',
'\1', $agent);
// Add MSIE to IE Edge and remove Chrome from IE Edge
$agent = preg_replace('#Chrome/.*(Edge/[0-9])#is', 'MSIE
\1', $agent);
break;
case (stripos($agent, 'Opera') !== false):
$agent = preg_replace('#(Opera/.*)Version/#is',
'\1Opera/', $agent);
break;
}
$this->agent = $agent;
return $this->agent;
}
/**
* passBrowser
*/
private function passBrowser($browser = '')
{
if ( ! $browser)
{
return false;
}
if ($browser == 'mobile')
{
return $this->isMobile();
}
if ( ! (strpos($browser, '#') === 0))
{
$browser = '#' . RLText::pregQuote($browser) . '#';
}
// also check for _ instead of .
$browser = preg_replace('#\\\.([^\]])#', '[\._]\1',
$browser);
$browser = str_replace('\.]', '\._]', $browser);
return preg_match($browser . 'i', $this->getAgent());
}
}
assignments/akeebasubs.php000064400000002606151166122720011724
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLAssignmentsAkeebaSubs extends RLAssignment
{
public function init()
{
if ( ! $this->request->id && $this->request->view ==
'level')
{
$slug =
JFactory::getApplication()->input->getString('slug',
'');
if ($slug)
{
$query = $this->db->getQuery(true)
->select('l.akeebasubs_level_id')
->from('#__akeebasubs_levels AS l')
->where('l.slug = ' . $this->db->quote($slug));
$this->db->setQuery($query);
$this->request->id = $this->db->loadResult();
}
}
}
public function passPageTypes()
{
return $this->passByPageTypes('com_akeebasubs',
$this->selection, $this->assignment);
}
public function passLevels()
{
if ( ! $this->request->id || $this->request->option !=
'com_akeebasubs' || $this->request->view !=
'level')
{
return $this->pass(false);
}
return $this->passSimple($this->request->id);
}
}
assignments/components.php000064400000001321151166122720011775
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsComponents extends RLAssignment
{
public function passComponents()
{
return $this->passSimple(strtolower($this->request->option));
}
}
assignments/content.php000064400000013030151166122720011262
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
use Joomla\CMS\MVC\Model\BaseDatabaseModel as JModel;
use Joomla\CMS\Table\Table as JTable;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsContent extends RLAssignment
{
public function passPageTypes()
{
$components = ['com_content', 'com_contentsubmit'];
if ( ! in_array($this->request->option, $components))
{
return $this->pass(false);
}
if ($this->request->view == 'category' &&
$this->request->layout == 'blog')
{
$view = 'categoryblog';
}
else
{
$view = $this->request->view;
}
return $this->passSimple($view);
}
public function passCategories()
{
// components that use the com_content secs/cats
$components = ['com_content', 'com_flexicontent',
'com_contentsubmit'];
if ( ! in_array($this->request->option, $components))
{
return $this->pass(false);
}
if (empty($this->selection))
{
return $this->pass(false);
}
$is_content = in_array($this->request->option,
['com_content', 'com_flexicontent']);
$is_category = in_array($this->request->view,
['category']);
$is_item = in_array($this->request->view, ['',
'article', 'item', 'form']);
if (
$this->request->option != 'com_contentsubmit'
&& ! ($this->params->inc_categories && $is_content
&& $is_category)
&& ! ($this->params->inc_articles && $is_content
&& $is_item)
&& ! ($this->params->inc_others && ! ($is_content
&& ($is_category || $is_item)))
)
{
return $this->pass(false);
}
if ($this->request->option == 'com_contentsubmit')
{
// Content Submit
$contentsubmit_params = new ContentsubmitModelArticle;
if (in_array($contentsubmit_params->_id, $this->selection))
{
return $this->pass(true);
}
return $this->pass(false);
}
$pass = false;
if (
$this->params->inc_others
&& ! ($is_content && ($is_category || $is_item))
&& $this->article
)
{
if ( ! isset($this->article->id) &&
isset($this->article->slug))
{
$this->article->id = (int) $this->article->slug;
}
if ( ! isset($this->article->catid) &&
isset($this->article->catslug))
{
$this->article->catid = (int) $this->article->catslug;
}
$this->request->id = $this->article->id;
$this->request->view = 'article';
}
$catids = $this->getCategoryIds($is_category);
foreach ($catids as $catid)
{
if ( ! $catid)
{
continue;
}
$pass = in_array($catid, $this->selection);
if ($pass && $this->params->inc_children == 2)
{
$pass = false;
continue;
}
if ( ! $pass && $this->params->inc_children)
{
$parent_ids = $this->getCatParentIds($catid);
$parent_ids = array_diff($parent_ids, [1]);
foreach ($parent_ids as $id)
{
if (in_array($id, $this->selection))
{
$pass = true;
break;
}
}
unset($parent_ids);
}
}
return $this->pass($pass);
}
private function getCategoryIds($is_category = false)
{
if ($is_category)
{
return (array) $this->request->id;
}
if ( ! $this->article && $this->request->id)
{
$this->article = JTable::getInstance('content');
$this->article->load($this->request->id);
}
if ($this->article && $this->article->catid)
{
return (array) $this->article->catid;
}
$catid =
JFactory::getApplication()->input->getInt('catid',
JFactory::getApplication()->getUserState('com_content.articles.filter.category_id'));
$menuparams = $this->getMenuItemParams($this->request->Itemid);
if ($this->request->view == 'featured')
{
$menuparams = $this->getMenuItemParams($this->request->Itemid);
return isset($menuparams->featured_categories) ? (array)
$menuparams->featured_categories : (array) $catid;
}
return isset($menuparams->catid) ? (array) $menuparams->catid :
(array) $catid;
}
public function passArticles()
{
if ( ! $this->request->id
|| ! (($this->request->option == 'com_content'
&& $this->request->view == 'article')
|| ($this->request->option == 'com_flexicontent'
&& $this->request->view == 'item')
)
)
{
return $this->pass(false);
}
$pass = false;
// Pass Article Id
if ( ! $this->passItemByType($pass, 'ContentIds'))
{
return $this->pass(false);
}
// Pass Content Keywords
if ( ! $this->passItemByType($pass, 'ContentKeywords'))
{
return $this->pass(false);
}
// Pass Meta Keywords
if ( ! $this->passItemByType($pass, 'MetaKeywords'))
{
return $this->pass(false);
}
// Pass Authors
if ( ! $this->passItemByType($pass, 'Authors'))
{
return $this->pass(false);
}
return $this->pass($pass);
}
public function getItem($fields = [])
{
if ($this->article)
{
return $this->article;
}
if ( ! class_exists('ContentModelArticle'))
{
require_once JPATH_SITE .
'/components/com_content/models/article.php';
}
$model = JModel::getInstance('article',
'contentModel');
if ( ! method_exists($model, 'getItem'))
{
return null;
}
$this->article = $model->getItem($this->request->id);
return $this->article;
}
private function getCatParentIds($id = 0)
{
return $this->getParentIds($id, 'categories');
}
}
assignments/cookieconfirm.php000064400000001477151166122720012453
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsCookieConfirm extends RLAssignment
{
public function passCookieConfirm()
{
require_once JPATH_PLUGINS . '/system/cookieconfirm/core.php';
$pass = PlgSystemCookieconfirmCore::getInstance()->isCookiesAllowed();
return $this->pass($pass);
}
}
assignments/datetime.php000064400000014107151166122720011412
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsDateTime extends RLAssignment
{
var $timezone = null;
var $dates = [];
public function passDate()
{
if ( ! $this->params->publish_up && !
$this->params->publish_down)
{
// no date range set
return ($this->assignment == 'include');
}
require_once dirname(__DIR__) . '/text.php';
RLText::fixDate($this->params->publish_up);
RLText::fixDate($this->params->publish_down);
$now = $this->getNow();
$up = $this->getDate($this->params->publish_up);
$down = $this->getDate($this->params->publish_down);
if (isset($this->params->recurring) &&
$this->params->recurring)
{
if ( ! (int) $this->params->publish_up || ! (int)
$this->params->publish_down)
{
// no date range set
return ($this->assignment == 'include');
}
$up = strtotime(date('Y') . $up->format('-m-d
H:i:s', true));
$down = strtotime(date('Y') . $down->format('-m-d
H:i:s', true));
// pass:
// 1) now is between up and down
// 2) up is later in year than down and:
// 2a) now is after up
// 2b) now is before down
if (
($up < $now && $down > $now)
|| ($up > $down
&& (
$up < $now
|| $down > $now
)
)
)
{
return ($this->assignment == 'include');
}
// outside date range
return $this->pass(false);
}
if (
(
(int) $this->params->publish_up
&& strtotime($up->format('Y-m-d H:i:s', true))
> $now
)
|| (
(int) $this->params->publish_down
&& strtotime($down->format('Y-m-d H:i:s', true))
< $now
)
)
{
// outside date range
return $this->pass(false);
}
// pass
return ($this->assignment == 'include');
}
public function passSeasons()
{
$season = self::getSeason($this->date,
$this->params->hemisphere);
return $this->passSimple($season);
}
public function passMonths()
{
$month = $this->date->format('m', true); // 01 (for
January) through 12 (for December)
return $this->passSimple((int) $month);
}
public function passDays()
{
$day = $this->date->format('N', true); // 1 (for Monday)
though 7 (for Sunday )
return $this->passSimple($day);
}
public function passTime()
{
$now = $this->getNow();
$up = strtotime($this->date->format('Y-m-d ', true) .
$this->params->publish_up);
$down = strtotime($this->date->format('Y-m-d ', true) .
$this->params->publish_down);
if ($up > $down)
{
// publish up is after publish down (spans midnight)
// current time should be:
// - after publish up
// - OR before publish down
if ($now >= $up || $now < $down)
{
return $this->pass(true);
}
return $this->pass(false);
}
// publish down is after publish up (simple time span)
// current time should be:
// - after publish up
// - AND before publish down
if ($now >= $up && $now < $down)
{
return $this->pass(true);
}
return $this->pass(false);
}
private function getSeason(&$d, $hemisphere = 'northern')
{
// Set $date to today
$date = strtotime($d->format('Y-m-d H:i:s', true));
// Get year of date specified
$date_year = $d->format('Y', true); // Four digit
representation for the year
// Specify the season names
$season_names = ['winter', 'spring',
'summer', 'fall'];
// Declare season date ranges
switch (strtolower($hemisphere))
{
case 'southern':
if (
$date < strtotime($date_year . '-03-21')
|| $date >= strtotime($date_year . '-12-21')
)
{
return $season_names[2]; // Must be in Summer
}
if ($date >= strtotime($date_year . '-09-23'))
{
return $season_names[1]; // Must be in Spring
}
if ($date >= strtotime($date_year . '-06-21'))
{
return $season_names[0]; // Must be in Winter
}
if ($date >= strtotime($date_year . '-03-21'))
{
return $season_names[3]; // Must be in Fall
}
break;
case 'australia':
if (
$date < strtotime($date_year . '-03-01')
|| $date >= strtotime($date_year . '-12-01')
)
{
return $season_names[2]; // Must be in Summer
}
if ($date >= strtotime($date_year . '-09-01'))
{
return $season_names[1]; // Must be in Spring
}
if ($date >= strtotime($date_year . '-06-01'))
{
return $season_names[0]; // Must be in Winter
}
if ($date >= strtotime($date_year . '-03-01'))
{
return $season_names[3]; // Must be in Fall
}
break;
default: // northern
if (
$date < strtotime($date_year . '-03-21')
|| $date >= strtotime($date_year . '-12-21')
)
{
return $season_names[0]; // Must be in Winter
}
if ($date >= strtotime($date_year . '-09-23'))
{
return $season_names[3]; // Must be in Fall
}
if ($date >= strtotime($date_year . '-06-21'))
{
return $season_names[2]; // Must be in Summer
}
if ($date >= strtotime($date_year . '-03-21'))
{
return $season_names[1]; // Must be in Spring
}
break;
}
return 0;
}
private function getNow()
{
return strtotime($this->date->format('Y-m-d H:i:s',
true));
}
private function getDate($date = '')
{
$id = 'date_' . $date;
if (isset($this->dates[$id]))
{
return $this->dates[$id];
}
$this->dates[$id] = JFactory::getDate($date);
if (empty($this->params->ignore_time_zone))
{
$this->dates[$id]->setTimeZone($this->getTimeZone());
}
return $this->dates[$id];
}
private function getTimeZone()
{
if ( ! is_null($this->timezone))
{
return $this->timezone;
}
$this->timezone = new
DateTimeZone(JFactory::getApplication()->getCfg('offset'));
return $this->timezone;
}
}
assignments/easyblog.php000064400000010007151166122720011416
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsEasyBlog extends RLAssignment
{
public function passPageTypes()
{
return $this->passByPageTypes('com_easyblog',
$this->selection, $this->assignment);
}
public function passCategories()
{
if ($this->request->option != 'com_easyblog')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_categories &&
$this->request->view == 'categories')
|| ($this->params->inc_items && $this->request->view
== 'entry')
);
if ( ! $pass)
{
return $this->pass(false);
}
$cats = $this->makeArray($this->getCategories());
$pass = $this->passSimple($cats, 'include');
if ($pass && $this->params->inc_children == 2)
{
return $this->pass(false);
}
else if ( ! $pass && $this->params->inc_children)
{
foreach ($cats as $cat)
{
$cats = array_merge($cats, $this->getCatParentIds($cat));
}
}
return $this->passSimple($cats);
}
private function getCategories()
{
switch ($this->request->view)
{
case 'entry' :
return $this->getCategoryIDFromItem();
break;
case 'categories' :
return $this->request->id;
break;
default:
return '';
}
}
private function getCategoryIDFromItem()
{
$query = $this->db->getQuery(true)
->select('i.category_id')
->from('#__easyblog_post AS i')
->where('i.id = ' . (int) $this->request->id);
$this->db->setQuery($query);
return $this->db->loadResult();
}
public function passTags()
{
if ($this->request->option != 'com_easyblog')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_tags && $this->request->layout
== 'tag')
|| ($this->params->inc_items && $this->request->view
== 'entry')
);
if ( ! $pass)
{
return $this->pass(false);
}
if ($this->params->inc_tags && $this->request->layout
== 'tag')
{
$query = $this->db->getQuery(true)
->select('t.alias')
->from('#__easyblog_tag AS t')
->where('t.id = ' . (int) $this->request->id)
->where('t.published = 1');
$this->db->setQuery($query);
$tags = $this->db->loadColumn();
return $this->passSimple($tags, true);
}
$query = $this->db->getQuery(true)
->select('t.alias')
->from('#__easyblog_post_tag AS x')
->join('LEFT', '#__easyblog_tag AS t ON t.id =
x.tag_id')
->where('x.post_id = ' . (int) $this->request->id)
->where('t.published = 1');
$this->db->setQuery($query);
$tags = $this->db->loadColumn();
return $this->passSimple($tags, true);
}
public function passItems()
{
if ( ! $this->request->id || $this->request->option !=
'com_easyblog' || $this->request->view !=
'entry')
{
return $this->pass(false);
}
$pass = false;
// Pass Article Id
if ( ! $this->passItemByType($pass, 'ContentIds'))
{
return $this->pass(false);
}
// Pass Content Keywords
if ( ! $this->passItemByType($pass, 'ContentKeywords'))
{
return $this->pass(false);
}
// Pass Authors
if ( ! $this->passItemByType($pass, 'Authors'))
{
return $this->pass(false);
}
return $this->pass($pass);
}
public function passContentKeywords($fields = ['title',
'intro', 'content'], $text = '')
{
parent::passContentKeywords($fields);
}
public function getItem($fields = [])
{
$query = $this->db->getQuery(true)
->select($fields)
->from('#__easyblog_post')
->where('id = ' . (int) $this->request->id);
$this->db->setQuery($query);
return $this->db->loadObject();
}
private function getCatParentIds($id = 0)
{
return $this->getParentIds($id, 'easyblog_category',
'parent_id');
}
}
assignments/flexicontent.php000064400000004622151166122720012321
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsFlexiContent extends RLAssignment
{
public function passPageTypes()
{
return $this->passByPageTypes('com_flexicontent',
$this->selection, $this->assignment);
}
public function passTags()
{
if ($this->request->option != 'com_flexicontent')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_tags && $this->request->view ==
'tags')
|| ($this->params->inc_items &&
in_array($this->request->view, ['item',
'items']))
);
if ( ! $pass)
{
return $this->pass(false);
}
if ($this->params->inc_tags && $this->request->view
== 'tags')
{
$query = $this->db->getQuery(true)
->select('t.name')
->from('#__flexicontent_tags AS t')
->where('t.id = ' . (int)
trim(JFactory::getApplication()->input->getInt('id', 0)))
->where('t.published = 1');
$this->db->setQuery($query);
$tag = $this->db->loadResult();
$tags = [$tag];
}
else
{
$query = $this->db->getQuery(true)
->select('t.name')
->from('#__flexicontent_tags_item_relations AS x')
->join('LEFT', '#__flexicontent_tags AS t ON t.id =
x.tid')
->where('x.itemid = ' . (int) $this->request->id)
->where('t.published = 1');
$this->db->setQuery($query);
$tags = $this->db->loadColumn();
}
return $this->passSimple($tags, true);
}
public function passTypes()
{
if ($this->request->option != 'com_flexicontent')
{
return $this->pass(false);
}
$pass = in_array($this->request->view, ['item',
'items']);
if ( ! $pass)
{
return $this->pass(false);
}
$query = $this->db->getQuery(true)
->select('x.type_id')
->from('#__flexicontent_items_ext AS x')
->where('x.item_id = ' . (int) $this->request->id);
$this->db->setQuery($query);
$type = $this->db->loadResult();
$types = $this->makeArray($type);
return $this->passSimple($types);
}
}
assignments/form2content.php000064400000002062151166122720012233
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsForm2Content extends RLAssignment
{
public function passProjects()
{
if ($this->request->option != 'com_content' &&
$this->request->view == 'article')
{
return $this->pass(false);
}
$query = $this->db->getQuery(true)
->select('c.projectid')
->from('#__f2c_form AS c')
->where('c.reference_id = ' . (int)
$this->request->id);
$this->db->setQuery($query);
$type = $this->db->loadResult();
$types = $this->makeArray($type);
return $this->passSimple($types);
}
}
assignments/geo.php000064400000005162151166122720010371 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
use Joomla\CMS\Log\Log as JLog;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsGeo extends RLAssignment
{
var $geo = null;
/**
* passContinents
*/
public function passContinents()
{
if ( ! $this->getGeo() || empty($this->geo->continentCode))
{
return $this->pass(false);
}
return $this->passSimple([$this->geo->continent,
$this->geo->continentCode]);
}
/**
* passCountries
*/
public function passCountries()
{
$this->getGeo();
if ( ! $this->getGeo() || empty($this->geo->countryCode))
{
return $this->pass(false);
}
return $this->passSimple([$this->geo->country,
$this->geo->countryCode]);
}
/**
* passRegions
*/
public function passRegions()
{
if ( ! $this->getGeo() || empty($this->geo->countryCode) ||
empty($this->geo->regionCodes))
{
return $this->pass(false);
}
$regions = $this->geo->regionCodes;
array_walk($regions, function (&$value) {
$value = $this->geo->countryCode . '-' . $value;
});
return $this->passSimple($regions);
}
/**
* passPostalcodes
*/
public function passPostalcodes()
{
if ( ! $this->getGeo() || empty($this->geo->postalCode))
{
return $this->pass(false);
}
// replace dashes with dots: 730-0011 => 730.0011
$postalcode = str_replace('-', '.',
$this->geo->postalCode);
return $this->passInRange($postalcode);
}
public function getGeo($ip = '')
{
if ($this->geo !== null)
{
return $this->geo;
}
$geo = $this->getGeoObject($ip);
if (empty($geo))
{
return false;
}
$this->geo = $geo->get();
if (JFactory::getApplication()->get('debug'))
{
JLog::addLogger(['text_file' =>
'regularlabs_geoip.log.php'], JLog::ALL,
['regularlabs_geoip']);
JLog::add(json_encode($this->geo), JLog::DEBUG,
'regularlabs_geoip');
}
return $this->geo;
}
private function getGeoObject($ip)
{
if ( ! file_exists(JPATH_LIBRARIES . '/geoip/geoip.php'))
{
return false;
}
require_once JPATH_LIBRARIES . '/geoip/geoip.php';
if ( ! class_exists('RegularLabs_GeoIp'))
{
return new GeoIp($ip);
}
return new RegularLabs_GeoIp($ip);
}
}
assignments/hikashop.php000064400000005775151166122720011437
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsHikaShop extends RLAssignment
{
public function passPageTypes()
{
if ($this->request->option != 'com_hikashop')
{
return $this->pass(false);
}
$type = $this->request->view;
if (
($type == 'product' &&
in_array($this->request->layout, ['contact',
'show']))
|| ($type == 'user' &&
in_array($this->request->layout, ['cpanel']))
)
{
$type .= '_' . $this->request->layout;
}
return $this->passSimple($type);
}
public function passCategories()
{
if ($this->request->option != 'com_hikashop')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_categories
&& ($this->request->view == 'category' ||
$this->request->layout == 'listing')
)
|| ($this->params->inc_items && $this->request->view
== 'product')
);
if ( ! $pass)
{
return $this->pass(false);
}
$cats = $this->getCategories();
$pass = $this->passSimple($cats, 'include');
if ($pass && $this->params->inc_children == 2)
{
return $this->pass(false);
}
else if ( ! $pass && $this->params->inc_children)
{
foreach ($cats as $cat)
{
$cats = array_merge($cats, $this->getCatParentIds($cat));
}
}
return $this->passSimple($cats);
}
public function passProducts()
{
if ( ! $this->request->id || $this->request->option !=
'com_hikashop' || $this->request->view !=
'product')
{
return $this->pass(false);
}
return $this->passSimple($this->request->id);
}
private function getCategories()
{
switch (true)
{
case (($this->request->view == 'category' ||
$this->request->layout == 'listing') &&
$this->request->id):
return [$this->request->id];
case ($this->request->view == 'category' ||
$this->request->layout == 'listing'):
include_once JPATH_ADMINISTRATOR .
'/components/com_hikashop/helpers/helper.php';
$menuClass = hikashop_get('class.menus');
$menuData = $menuClass->get($this->request->Itemid);
return
$this->makeArray($menuData->hikashop_params['selectparentlisting']);
case ($this->request->id):
$query = $this->db->getQuery(true)
->select('c.category_id')
->from('#__hikashop_product_category AS c')
->where('c.product_id = ' . (int)
$this->request->id);
$this->db->setQuery($query);
$cats = $this->db->loadColumn();
return $this->makeArray($cats);
default:
return [];
}
}
private function getCatParentIds($id = 0)
{
return $this->getParentIds($id, 'hikashop_category',
'category_parent_id', 'category_id');
}
}
assignments/homepage.php000064400000011606151166122720011404
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
use Joomla\CMS\Language\LanguageHelper as JLanguageHelper;
use Joomla\CMS\Uri\Uri as JUri;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/text.php';
require_once dirname(__DIR__) . '/string.php';
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsHomePage extends RLAssignment
{
public function passHomePage()
{
$home =
JFactory::getApplication()->getMenu('site')->getDefault(JFactory::getLanguage()->getTag());
// return if option or other set values do not match the homepage menu
item values
if ($this->request->option)
{
// check if option is different to home menu
if ( ! $home || ! isset($home->query['option']) ||
$home->query['option'] != $this->request->option)
{
return $this->pass(false);
}
if ( ! $this->request->option)
{
// set the view/task/layout in the menu item to empty if not set
$home->query['view'] =
isset($home->query['view']) ?
$home->query['view'] : '';
$home->query['task'] =
isset($home->query['task']) ?
$home->query['task'] : '';
$home->query['layout'] =
isset($home->query['layout']) ?
$home->query['layout'] : '';
}
// check set values against home menu query items
foreach ($home->query as $k => $v)
{
if ((isset($this->request->{$k}) &&
$this->request->{$k} != $v)
|| (
( ! isset($this->request->{$k}) || in_array($v,
['virtuemart', 'mijoshop']))
&& JFactory::getApplication()->input->get($k) != $v
)
)
{
return $this->pass(false);
}
}
// check post values against home menu params
foreach ($home->params->toObject() as $k => $v)
{
if (($v && isset($_POST[$k]) && $_POST[$k] != $v)
|| ( ! $v && isset($_POST[$k]) && $_POST[$k])
)
{
return $this->pass(false);
}
}
}
$pass = $this->checkPass($home);
if ( ! $pass)
{
$pass = $this->checkPass($home, 1);
}
return $this->pass($pass);
}
private function checkPass(&$home, $addlang = 0)
{
$uri = JUri::getInstance();
if ($addlang)
{
$sef = $uri->getVar('lang');
if (empty($sef))
{
$langs = array_keys(JLanguageHelper::getLanguages('sef'));
$path = RLString::substr(
$uri->toString(['scheme', 'user',
'pass', 'host', 'port', 'path']),
RLString::strlen($uri->base())
);
$path = preg_replace('#^index\.php/?#', '',
$path);
$parts = explode('/', $path);
$part = reset($parts);
if (in_array($part, $langs))
{
$sef = $part;
}
}
if (empty($sef))
{
return false;
}
}
$query = $uri->toString(['query']);
if (strpos($query, 'option=') === false &&
strpos($query, 'Itemid=') === false)
{
$url = $uri->toString(['host', 'path']);
}
else
{
$url = $uri->toString(['host', 'path',
'query']);
}
// remove the www.
$url = preg_replace('#^www\.#', '', $url);
// replace ampersand chars
$url = str_replace('&', '&', $url);
// remove any language vars
$url =
preg_replace('#((\?)lang=[a-z-_]*(&|$)|&lang=[a-z-_]*)#',
'\2', $url);
// remove trailing nonsense
$url = trim(preg_replace('#/?\??&?$#', '',
$url));
// remove the index.php/
$url = preg_replace('#/index\.php(/|$)#', '/', $url);
// remove trailing /
$url = trim(preg_replace('#/$#', '', $url));
$root = JUri::root();
// remove the http(s)
$root = preg_replace('#^.*?://#', '', $root);
// remove the www.
$root = preg_replace('#^www\.#', '', $root);
//remove the port
$root = preg_replace('#:[0-9]+#', '', $root);
// so also passes on urls with trailing /, ?, &, /?, etc...
$root = preg_replace('#(Itemid=[0-9]*).*^#', '\1',
$root);
// remove trailing /
$root = trim(preg_replace('#/$#', '', $root));
if ($addlang)
{
$root .= '/' . $sef;
}
/* Pass urls:
* [root]
*/
$regex = '#^' . $root . '$#i';
if (preg_match($regex, $url))
{
return true;
}
/* Pass urls:
* [root]?Itemid=[menu-id]
* [root]/?Itemid=[menu-id]
* [root]/index.php?Itemid=[menu-id]
* [root]/[menu-alias]
* [root]/[menu-alias]?Itemid=[menu-id]
* [root]/index.php?[menu-alias]
* [root]/index.php?[menu-alias]?Itemid=[menu-id]
* [root]/[menu-link]
* [root]/[menu-link]&Itemid=[menu-id]
*/
$regex = '#^' . $root
. '(/('
. 'index\.php'
. '|'
. '(index\.php\?)?' . RLText::pregQuote($home->alias)
. '|'
. RLText::pregQuote($home->link)
. ')?)?'
. '(/?[\?&]Itemid=' . (int) $home->id . ')?'
. '$#i';
return preg_match($regex, $url);
}
}
assignments/ips.php000064400000005742151166122720010416 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsIPs extends RLAssignment
{
public function passIPs()
{
if (is_array($this->selection))
{
$this->selection = implode(',', $this->selection);
}
$this->selection = explode(',', str_replace([' ',
"\r", "\n"], ['', '',
','], $this->selection));
$pass = $this->checkIPList();
return $this->pass($pass);
}
private function checkIPList()
{
foreach ($this->selection as $range)
{
// Check next range if this one doesn't match
if ( ! $this->checkIP($range))
{
continue;
}
// Match found, so return true!
return true;
}
// No matches found, so return false
return false;
}
private function checkIP($range)
{
if (empty($range))
{
return false;
}
if (strpos($range, '-') !== false)
{
// Selection is an IP range
return $this->checkIPRange($range);
}
// Selection is a single IP (part)
return $this->checkIPPart($range);
}
private function checkIPRange($range)
{
$ip = $_SERVER['REMOTE_ADDR'];
// Return if no IP address can be found (shouldn't happen, but who
knows)
if (empty($ip))
{
return false;
}
// check if IP is between or equal to the from and to IP range
list($min, $max) = explode('-', trim($range), 2);
// Return false if IP is smaller than the range start
if ($ip < trim($min))
{
return false;
}
$max = $this->fillMaxRange($max, $min);
// Return false if IP is larger than the range end
if ($ip > trim($max))
{
return false;
}
return true;
}
/* Fill the max range by prefixing it with the missing parts from the min
range
* So 101.102.103.104-201.202 becomes:
* max: 101.102.201.202
*/
private function fillMaxRange($max, $min)
{
$max_parts = explode('.', $max);
if (count() == 4)
{
return $max;
}
$min_parts = explode('.', $min);
$prefix = array_slice($min_parts, 0, count($min_parts) -
count($max_parts));
return implode('.', $prefix) . '.' .
implode('.', $max_parts);
}
private function checkIPPart($range)
{
$ip = $_SERVER['REMOTE_ADDR'];
// Return if no IP address can be found (shouldn't happen, but who
knows)
if (empty($ip))
{
return false;
}
$ip_parts = explode('.', $ip);
$range_parts = explode('.', trim($range));
// Trim the IP to the part length of the range
$ip = implode('.', array_slice($ip_parts, 0,
count($range_parts)));
// Return false if ip does not match the range
if ($range != $ip)
{
return false;
}
return true;
}
}
assignments/k2.php000064400000010676151166122720010141 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
// If controller.php exists, assume this is K2 v3
defined('RL_K2_VERSION') or define('RL_K2_VERSION',
file_exists(JPATH_ADMINISTRATOR .
'/components/com_k2/controller.php') ? 3 : 2);
class RLAssignmentsK2 extends RLAssignment
{
public function passPageTypes()
{
return $this->passByPageTypes('com_k2', $this->selection,
$this->assignment, false, true);
}
public function passCategories()
{
if ($this->request->option != 'com_k2')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_categories
&& (($this->request->view == 'itemlist'
&& $this->request->task == 'category')
|| $this->request->view == 'latest'
)
)
|| ($this->params->inc_items && $this->request->view
== 'item')
);
if ( ! $pass)
{
return $this->pass(false);
}
$cats = $this->makeArray($this->getCategories());
$pass = $this->passSimple($cats, 'include');
if ($pass && $this->params->inc_children == 2)
{
return $this->pass(false);
}
else if ( ! $pass && $this->params->inc_children)
{
foreach ($cats as $cat)
{
$cats = array_merge($cats, $this->getCatParentIds($cat));
}
}
return $this->passSimple($cats);
}
private function getCategories()
{
switch ($this->request->view)
{
case 'item' :
return $this->getCategoryIDFromItem();
break;
case 'itemlist' :
return $this->getCategoryID();
break;
default:
return '';
}
}
private function getCategoryID()
{
return $this->request->id ?:
JFactory::getApplication()->getUserStateFromRequest('com_k2itemsfilter_category',
'catid', 0, 'int');
}
private function getCategoryIDFromItem()
{
if ($this->article && isset($this->article->catid))
{
return $this->article->catid;
}
$query = $this->db->getQuery(true)
->select('i.catid')
->from('#__k2_items AS i')
->where('i.id = ' . (int) $this->request->id);
$this->db->setQuery($query);
return $this->db->loadResult();
}
public function passTags()
{
if ($this->request->option != 'com_k2')
{
return $this->pass(false);
}
$tag =
trim(JFactory::getApplication()->input->getString('tag',
''));
$pass = (
($this->params->inc_tags && $tag != '')
|| ($this->params->inc_items && $this->request->view
== 'item')
);
if ( ! $pass)
{
return $this->pass(false);
}
if ($this->params->inc_tags && $tag != '')
{
$tags =
[trim(JFactory::getApplication()->input->getString('tag',
''))];
return $this->passSimple($tags, true);
}
$query = $this->db->getQuery(true)
->select('t.name')
->from('#__k2_tags_xref AS x')
->join('LEFT', '#__k2_tags AS t ON t.id =
x.tagID')
->where('x.itemID = ' . (int) $this->request->id)
->where('t.published = 1');
$this->db->setQuery($query);
$tags = $this->db->loadColumn();
return $this->passSimple($tags, true);
}
public function passItems()
{
if ( ! $this->request->id || $this->request->option !=
'com_k2' || $this->request->view != 'item')
{
return $this->pass(false);
}
$pass = false;
// Pass Article Id
if ( ! $this->passItemByType($pass, 'ContentIds'))
{
return $this->pass(false);
}
// Pass Content Keywords
if ( ! $this->passItemByType($pass, 'ContentKeywords'))
{
return $this->pass(false);
}
// Pass Meta Keywords
if ( ! $this->passItemByType($pass, 'MetaKeywords'))
{
return $this->pass(false);
}
// Pass Authors
if ( ! $this->passItemByType($pass, 'Authors'))
{
return $this->pass(false);
}
return $this->pass($pass);
}
public function getItem($fields = [])
{
$query = $this->db->getQuery(true)
->select($fields)
->from('#__k2_items')
->where('id = ' . (int) $this->request->id);
$this->db->setQuery($query);
return $this->db->loadObject();
}
private function getCatParentIds($id = 0)
{
$parent_field = RL_K2_VERSION == 3 ? 'parent_id' :
'parent';
return $this->getParentIds($id, 'k2_categories',
$parent_field);
}
}
assignments/languages.php000064400000001371151166122720011563
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsLanguages extends RLAssignment
{
public function passLanguages()
{
return $this->passSimple(JFactory::getLanguage()->getTag(), true);
}
}
assignments/menu.php000064400000004547151166122720010571 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsMenu extends RLAssignment
{
public function passMenu()
{
// return if no Itemid or selection is set
if ( ! $this->request->Itemid || empty($this->selection))
{
return $this->pass($this->params->inc_noitemid);
}
$menutype = 'type.' . self::getMenuType();
// return true if menu type is in selection
if (in_array($menutype, $this->selection))
{
return $this->pass(true);
}
// return true if menu is in selection
if (in_array($this->request->Itemid, $this->selection))
{
return $this->pass(($this->params->inc_children != 2));
}
if ( ! $this->params->inc_children)
{
return $this->pass(false);
}
$parent_ids = $this->getMenuParentIds($this->request->Itemid);
$parent_ids = array_diff($parent_ids, [1]);
foreach ($parent_ids as $id)
{
if ( ! in_array($id, $this->selection))
{
continue;
}
return $this->pass(true);
}
return $this->pass(false);
}
private function getMenuParentIds($id = 0)
{
return $this->getParentIds($id, 'menu');
}
private function getMenuType()
{
if (isset($this->request->menutype))
{
return $this->request->menutype;
}
if (empty($this->request->Itemid))
{
$this->request->menutype = '';
return $this->request->menutype;
}
if (JFactory::getApplication()->isClient('site'))
{
$menu = JFactory::getApplication()->getMenu()->getItem((int)
$this->request->Itemid);
$this->request->menutype = isset($menu->menutype) ?
$menu->menutype : '';
return $this->request->menutype;
}
$query = $this->db->getQuery(true)
->select('m.menutype')
->from('#__menu AS m')
->where('m.id = ' . (int) $this->request->Itemid);
$this->db->setQuery($query);
$this->request->menutype = $this->db->loadResult();
return $this->request->menutype;
}
}
assignments/mijoshop.php000064400000005770151166122720011454
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsMijoShop extends RLAssignment
{
public function init()
{
$input = JFactory::getApplication()->input;
$category_id = $input->getCmd('path', 0);
if (strpos($category_id, '_'))
{
$category_id = end(explode('_', $category_id));
}
$this->request->item_id =
$input->getInt('product_id', 0);
$this->request->category_id = $category_id;
$this->request->id = ($this->request->item_id) ?
$this->request->item_id : $this->request->category_id;
$view = $input->getCmd('view', '');
if (empty($view))
{
$mijoshop = JPATH_ROOT .
'/components/com_mijoshop/mijoshop/mijoshop.php';
if ( ! file_exists($mijoshop))
{
return;
}
require_once($mijoshop);
$route = $input->getString('route', '');
$view = MijoShop::get('router')->getView($route);
}
$this->request->view = $view;
}
public function passPageTypes()
{
return $this->passByPageTypes('com_mijoshop',
$this->selection, $this->assignment, true);
}
public function passCategories()
{
if ($this->request->option != 'com_mijoshop')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_categories
&& ($this->request->view == 'category')
)
|| ($this->params->inc_items && $this->request->view
== 'product')
);
if ( ! $pass)
{
return $this->pass(false);
}
$cats = [];
if ($this->request->category_id)
{
$cats = $this->request->category_id;
}
else if ($this->request->item_id)
{
$query = $this->db->getQuery(true)
->select('c.category_id')
->from('#__mijoshop_product_to_category AS c')
->where('c.product_id = ' . (int)
$this->request->id);
$this->db->setQuery($query);
$cats = $this->db->loadColumn();
}
$cats = $this->makeArray($cats);
$pass = $this->passSimple($cats, 'include');
if ($pass && $this->params->inc_children == 2)
{
return $this->pass(false);
}
else if ( ! $pass && $this->params->inc_children)
{
foreach ($cats as $cat)
{
$cats = array_merge($cats, $this->getCatParentIds($cat));
}
}
return $this->passSimple($cats);
}
public function passProducts()
{
if ( ! $this->request->id || $this->request->option !=
'com_mijoshop' || $this->request->view !=
'product')
{
return $this->pass(false);
}
return $this->passSimple($this->request->id);
}
private function getCatParentIds($id = 0)
{
return $this->getParentIds($id, 'mijoshop_category',
'parent_id', 'category_id');
}
}
assignments/php.php000064400000005445151166122720010412 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
use Joomla\CMS\MVC\Model\BaseDatabaseModel as JModel;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsPHP extends RLAssignment
{
public function passPHP()
{
$article = $this->article;
if ( ! is_array($this->selection))
{
$this->selection = [$this->selection];
}
$pass = false;
foreach ($this->selection as $php)
{
// replace \n with newline and other fix stuff
$php = str_replace('\|', '|', $php);
$php = preg_replace('#(?<!\\\)\\\n#', "\n",
$php);
$php = trim(str_replace('[:REGEX_ENTER:]', '\n',
$php));
if ($php == '')
{
$pass = true;
break;
}
if ( ! $article && strpos($php, '$article') !== false)
{
$article = null;
if ($this->request->option == 'com_content' &&
$this->request->view == 'article')
{
$article = $this->getArticleById($this->request->id);
}
}
if ( ! isset($Itemid))
{
$Itemid =
JFactory::getApplication()->input->getInt('Itemid', 0);
}
if ( ! isset($mainframe))
{
$mainframe = JFactory::getApplication();
}
if ( ! isset($app))
{
$app = JFactory::getApplication();
}
if ( ! isset($document))
{
$document = JFactory::getDocument();
}
if ( ! isset($doc))
{
$doc = JFactory::getDocument();
}
if ( ! isset($database))
{
$database = JFactory::getDbo();
}
if ( ! isset($db))
{
$db = JFactory::getDbo();
}
if ( ! isset($user))
{
$user = JFactory::getUser();
}
$php .= ';return true;';
$temp_PHP_func = create_function('&$article, &$Itemid,
&$mainframe, &$app, &$document, &$doc, &$database,
&$db, &$user', $php);
// evaluate the script
ob_start();
$pass = (bool) $temp_PHP_func($article, $Itemid, $mainframe, $app,
$document, $doc, $database, $db, $user);
unset($temp_PHP_func);
ob_end_clean();
if ($pass)
{
break;
}
}
return $this->pass($pass);
}
private function getArticleById($id = 0)
{
if ( ! $id)
{
return null;
}
if ( ! class_exists('ContentModelArticle'))
{
require_once JPATH_SITE .
'/components/com_content/models/article.php';
}
$model = JModel::getInstance('article',
'contentModel');
if ( ! method_exists($model, 'getItem'))
{
return null;
}
return $model->getItem($this->request->id);
}
}
assignments/redshop.php000064400000005046151166122720011264
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsRedShop extends RLAssignment
{
public function init()
{
$this->request->item_id =
JFactory::getApplication()->input->getInt('pid', 0);
$this->request->category_id =
JFactory::getApplication()->input->getInt('cid', 0);
$this->request->id = ($this->request->item_id) ?
$this->request->item_id : $this->request->category_id;
}
public function passPageTypes()
{
return $this->passByPageTypes('com_redshop',
$this->selection, $this->assignment, true);
}
public function passCategories()
{
if ($this->request->option != 'com_redshop')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_categories
&& ($this->request->view == 'category')
)
|| ($this->params->inc_items && $this->request->view
== 'product')
);
if ( ! $pass)
{
return $this->pass(false);
}
$cats = [];
if ($this->request->category_id)
{
$cats = $this->request->category_id;
}
else if ($this->request->item_id)
{
$query = $this->db->getQuery(true)
->select('x.category_id')
->from('#__redshop_product_category_xref AS x')
->where('x.product_id = ' . (int)
$this->request->item_id);
$this->db->setQuery($query);
$cats = $this->db->loadColumn();
}
$cats = $this->makeArray($cats);
$pass = $this->passSimple($cats, 'include');
if ($pass && $this->params->inc_children == 2)
{
return $this->pass(false);
}
else if ( ! $pass && $this->params->inc_children)
{
foreach ($cats as $cat)
{
$cats = array_merge($cats, $this->getCatParentIds($cat));
}
}
return $this->passSimple($cats);
}
public function passProducts()
{
if ( ! $this->request->id || $this->request->option !=
'com_redshop' || $this->request->view !=
'product')
{
return $this->pass(false);
}
return $this->passSimple($this->request->id);
}
private function getCatParentIds($id = 0)
{
return $this->getParentIds($id, 'redshop_category_xref',
'category_parent_id', 'category_child_id');
}
}
assignments/tags.php000064400000005173151166122720010557 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsTags extends RLAssignment
{
public function passTags()
{
if (in_array($this->request->option, ['com_content',
'com_flexicontent']))
{
return $this->passTagsContent();
}
if ($this->request->option != 'com_tags'
|| $this->request->view != 'tag'
|| ! $this->request->id
)
{
return $this->pass(false);
}
return $this->passTag($this->request->id);
}
private function passTagsContent()
{
$is_item = in_array($this->request->view, ['',
'article', 'item']);
$is_category = in_array($this->request->view,
['category']);
switch (true)
{
case ($is_item):
$prefix = 'com_content.article';
break;
case ($is_category):
$prefix = 'com_content.category';
break;
default:
return $this->pass(false);
}
// Load the tags.
$query = $this->db->getQuery(true)
->select($this->db->quoteName('t.id'))
->select($this->db->quoteName('t.title'))
->from('#__tags AS t')
->join(
'INNER', '#__contentitem_tag_map AS m'
. ' ON m.tag_id = t.id'
. ' AND m.type_alias = ' . $this->db->quote($prefix)
. ' AND m.content_item_id IN ( ' . $this->request->id .
')'
);
$this->db->setQuery($query);
$tags = $this->db->loadObjectList();
if (empty($tags))
{
return $this->pass(false);
}
foreach ($tags as $tag)
{
if ( ! $this->passTag($tag->id) && !
$this->passTag($tag->title))
{
continue;
}
return $this->pass(true);
}
return $this->pass(false);
}
private function passTag($tag)
{
$pass = in_array($tag, $this->selection);
if ($pass)
{
// If passed, return false if assigned to only children
// Else return true
return ($this->params->inc_children != 2);
}
if ( ! $this->params->inc_children)
{
return false;
}
// Return true if a parent id is present in the selection
return array_intersect(
$this->getTagsParentIds($tag),
$this->selection
);
}
private function getTagsParentIds($id = 0)
{
$parentids = $this->getParentIds($id, 'tags');
// Remove the root tag
$parentids = array_diff($parentids, [1]);
return $parentids;
}
}
assignments/templates.php000064400000003773151166122740011625
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsTemplates extends RLAssignment
{
public function passTemplates()
{
$template = $this->getTemplate();
// Put template name and name + style id into array
// The '::' separator was used in pre Joomla 3.3
$template = [$template->template, $template->template .
'--' . $template->id, $template->template . '::'
. $template->id];
return $this->passSimple($template, true);
}
public function getTemplate()
{
$template = JFactory::getApplication()->getTemplate(true);
if (isset($template->id))
{
return $template;
}
$params = json_encode($template->params);
// Find template style id based on params, as the template style id is
not always stored in the getTemplate
$query = $this->db->getQuery(true)
->select('id')
->from('#__template_styles as s')
->where('s.client_id = 0')
->where('s.template = ' .
$this->db->quote($template->template))
->where('s.params = ' . $this->db->quote($params))
->setLimit(1);
$this->db->setQuery($query);
$template->id = $this->db->loadResult('id');
if ($template->id)
{
return $template;
}
// No template style id is found, so just grab the first result based on
the template name
$query->clear('where')
->where('s.client_id = 0')
->where('s.template = ' .
$this->db->quote($template->template))
->setLimit(1);
$this->db->setQuery($query);
$template->id = $this->db->loadResult('id');
return $template;
}
}
assignments/urls.php000064400000003401151166122740010600 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Uri\Uri as JUri;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
require_once dirname(__DIR__) . '/text.php';
class RLAssignmentsURLs extends RLAssignment
{
public function passURLs()
{
$regex = isset($this->params->regex) ? $this->params->regex :
0;
if ( ! is_array($this->selection))
{
$this->selection = explode("\n", $this->selection);
}
if (count($this->selection) == 1)
{
$this->selection = explode("\n", $this->selection[0]);
}
$url = JUri::getInstance();
$url = $url->toString();
$urls = [
RLText::html_entity_decoder(urldecode($url)),
urldecode($url),
RLText::html_entity_decoder($url),
$url,
];
$urls = array_unique($urls);
$pass = false;
foreach ($urls as $url)
{
foreach ($this->selection as $s)
{
$s = trim($s);
if ($s == '')
{
continue;
}
if ($regex)
{
$url_part = str_replace(['#', '&'],
['\#', '(&|&)'], $s);
$s = '#' . $url_part . '#si';
if (@preg_match($s . 'u', $url) || @preg_match($s, $url))
{
$pass = true;
break;
}
continue;
}
if (strpos($url, $s) !== false)
{
$pass = true;
break;
}
}
if ($pass)
{
break;
}
}
return $this->pass($pass);
}
}
assignments/users.php000064400000007123151166122740010761 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsUsers extends RLAssignment
{
public function passAccessLevels()
{
$user = JFactory::getUser();
$levels = $user->getAuthorisedViewLevels();
$this->selection =
$this->convertAccessLevelNamesToIds($this->selection);
return $this->passSimple($levels);
}
public function passUserGroupLevels()
{
$user = JFactory::getUser();
if ( ! empty($user->groups))
{
$groups = array_values($user->groups);
}
else
{
$groups = $user->getAuthorisedGroups();
}
if ($this->params->inc_children)
{
$this->setUserGroupChildrenIds();
}
$this->selection =
$this->convertUsergroupNamesToIds($this->selection);
return $this->passSimple($groups);
}
public function passUsers()
{
return $this->passSimple(JFactory::getUser()->get('id'));
}
private function convertAccessLevelNamesToIds($selection)
{
$names = [];
foreach ($selection as $i => $level)
{
if (is_numeric($level))
{
continue;
}
unset($selection[$i]);
$names[] = strtolower(str_replace(' ', '', $level));
}
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from('#__viewlevels')
->where('LOWER(REPLACE(' .
$db->quoteName('title') . ', " ",
"")) IN (\'' . implode('\',\'',
$names) . '\')');
$db->setQuery($query);
$level_ids = $db->loadColumn();
return array_unique(array_merge($selection, $level_ids));
}
private function convertUsergroupNamesToIds($selection)
{
$names = [];
foreach ($selection as $i => $group)
{
if (is_numeric($group))
{
continue;
}
unset($selection[$i]);
$names[] = strtolower(str_replace(' ', '', $group));
}
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from('#__usergroups')
->where('LOWER(REPLACE(' .
$db->quoteName('title') . ', " ",
"")) IN (\'' . implode('\',\'',
$names) . '\')');
$db->setQuery($query);
$group_ids = $db->loadColumn();
return array_unique(array_merge($selection, $group_ids));
}
private function setUserGroupChildrenIds()
{
$children = $this->getUserGroupChildrenIds($this->selection);
if ($this->params->inc_children == 2)
{
$this->selection = $children;
return;
}
$this->selection = array_merge($this->selection, $children);
}
private function getUserGroupChildrenIds($groups)
{
$children = [];
$db = JFactory::getDbo();
foreach ($groups as $group)
{
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('parent_id') . ' = ' .
(int) $group);
$db->setQuery($query);
$group_children = $db->loadColumn();
if (empty($group_children))
{
continue;
}
$children = array_merge($children, $group_children);
$group_grand_children =
$this->getUserGroupChildrenIds($group_children);
if (empty($group_grand_children))
{
continue;
}
$children = array_merge($children, $group_grand_children);
}
$children = array_unique($children);
return $children;
}
}
assignments/virtuemart.php000064400000010021151166122740012011
0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsVirtueMart extends RLAssignment
{
public function init()
{
$virtuemart_product_id =
JFactory::getApplication()->input->get('virtuemart_product_id',
[], 'array');
$virtuemart_category_id =
JFactory::getApplication()->input->get('virtuemart_category_id',
[], 'array');
$this->request->item_id = isset($virtuemart_product_id[0]) ?
$virtuemart_product_id[0] : null;
$this->request->category_id = isset($virtuemart_category_id[0]) ?
$virtuemart_category_id[0] : null;
$this->request->id = ($this->request->item_id) ?
$this->request->item_id : $this->request->category_id;
}
public function passPageTypes()
{
// Because VM sucks, we have to get the view again
$this->request->view =
JFactory::getApplication()->input->getString('view');
return $this->passByPageTypes('com_virtuemart',
$this->selection, $this->assignment, true);
}
public function passCategories()
{
if ($this->request->option != 'com_virtuemart')
{
return $this->pass(false);
}
// Because VM sucks, we have to get the view again
$this->request->view =
JFactory::getApplication()->input->getString('view');
$pass = (($this->params->inc_categories &&
in_array($this->request->view, ['categories',
'category']))
|| ($this->params->inc_items && $this->request->view
== 'productdetails')
);
if ( ! $pass)
{
return $this->pass(false);
}
$cats = [];
if ($this->request->view == 'productdetails' &&
$this->request->item_id)
{
$query = $this->db->getQuery(true)
->select('x.virtuemart_category_id')
->from('#__virtuemart_product_categories AS x')
->where('x.virtuemart_product_id = ' . (int)
$this->request->item_id);
$this->db->setQuery($query);
$cats = $this->db->loadColumn();
}
else if ($this->request->category_id)
{
$cats = $this->request->category_id;
if ( ! is_numeric($cats))
{
$query = $this->db->getQuery(true)
->select('config')
->from('#__virtuemart_configs')
->where('virtuemart_config_id = 1');
$this->db->setQuery($query);
$config = $this->db->loadResult();
$lang = substr($config, strpos($config, 'vmlang='));
$lang = substr($lang, 0, strpos($lang, '|'));
if (preg_match('#"([^"]*_[^"]*)"#',
$lang, $lang))
{
$lang = $lang[1];
}
else
{
$lang = 'en_gb';
}
$query = $this->db->getQuery(true)
->select('l.virtuemart_category_id')
->from('#__virtuemart_categories_' . $lang . ' AS
l')
->where('l.slug = ' . $this->db->quote($cats));
$this->db->setQuery($query);
$cats = $this->db->loadResult();
}
}
$cats = $this->makeArray($cats);
$pass = $this->passSimple($cats, 'include');
if ($pass && $this->params->inc_children == 2)
{
return $this->pass(false);
}
if ( ! $pass && $this->params->inc_children)
{
foreach ($cats as $cat)
{
$cats = array_merge($cats, $this->getCatParentIds($cat));
}
}
return $this->passSimple($cats);
}
public function passProducts()
{
// Because VM sucks, we have to get the view again
$this->request->view =
JFactory::getApplication()->input->getString('view');
if ( ! $this->request->id || $this->request->option !=
'com_virtuemart' || $this->request->view !=
'productdetails')
{
return $this->pass(false);
}
return $this->passSimple($this->request->id);
}
private function getCatParentIds($id = 0)
{
return $this->getParentIds($id,
'virtuemart_category_categories', 'category_parent_id',
'category_child_id');
}
}
assignments/zoo.php000064400000013015151166122740010424 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use Joomla\CMS\Factory as JFactory;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
require_once dirname(__DIR__) . '/assignment.php';
class RLAssignmentsZoo extends RLAssignment
{
public function init()
{
if ( ! $this->request->view)
{
$this->request->view = $this->request->task;
}
switch ($this->request->view)
{
case 'item':
$this->request->idname = 'item_id';
break;
case 'category':
$this->request->idname = 'category_id';
break;
}
$this->request->id =
JFactory::getApplication()->input->getInt($this->request->idname,
0);
}
public function initAssignment($assignment, $article = 0)
{
parent::initAssignment($assignment, $article);
if ($this->request->option != 'com_zoo' && !
isset($this->request->idname))
{
return;
}
switch ($this->request->idname)
{
case 'item_id':
$this->request->view = 'item';
break;
case 'category_id':
$this->request->view = 'category';
break;
}
}
public function passPageTypes()
{
return $this->passByPageTypes('com_zoo',
$this->selection, $this->assignment);
}
public function passCategories()
{
if ($this->request->option != 'com_zoo')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_apps && $this->request->view ==
'frontpage')
|| ($this->params->inc_categories &&
$this->request->view == 'category')
|| ($this->params->inc_items && $this->request->view
== 'item')
);
if ( ! $pass)
{
return $this->pass(false);
}
$cats = $this->getCategories();
if ($cats === false)
{
return $this->pass(false);
}
$cats = $this->makeArray($cats);
$pass = $this->passSimple($cats, 'include');
if ($pass && $this->params->inc_children == 2)
{
return $this->pass(false);
}
if ( ! $pass && $this->params->inc_children)
{
foreach ($cats as $cat)
{
$cats = array_merge($cats, $this->getCatParentIds($cat));
}
}
return $this->passSimple($cats);
}
private function getCategories()
{
if ($this->article && isset($this->article->catid))
{
return [$this->article->catid];
}
$menuparams = $this->getMenuItemParams($this->request->Itemid);
switch ($this->request->view)
{
case 'frontpage':
if ($this->request->id)
{
return [$this->request->id];
}
if ( ! isset($menuparams->application))
{
return [];
}
return ['app' . $menuparams->application];
case 'category':
$cats = [];
if ($this->request->id)
{
$cats[] = $this->request->id;
}
else if (isset($menuparams->category))
{
$cats[] = $menuparams->category;
}
if (empty($cats[0]))
{
return [];
}
$query = $this->db->getQuery(true)
->select('c.application_id')
->from('#__zoo_category AS c')
->where('c.id = ' . (int) $cats[0]);
$this->db->setQuery($query);
$cats[] = 'app' . $this->db->loadResult();
return $cats;
case 'item':
$id = $this->request->id;
if ( ! $id && isset($menuparams->item_id))
{
$id = $menuparams->item_id;
}
if ( ! $id)
{
return [];
}
$query = $this->db->getQuery(true)
->select('c.category_id')
->from('#__zoo_category_item AS c')
->where('c.item_id = ' . (int) $id)
->where('c.category_id != 0');
$this->db->setQuery($query);
$cats = $this->db->loadColumn();
$query = $this->db->getQuery(true)
->select('i.application_id')
->from('#__zoo_item AS i')
->where('i.id = ' . (int) $id);
$this->db->setQuery($query);
$cats[] = 'app' . $this->db->loadResult();
return $cats;
default:
return false;
}
}
public function passItems()
{
if ( ! $this->request->id || $this->request->option !=
'com_zoo')
{
return $this->pass(false);
}
if ($this->request->view != 'item')
{
return $this->pass(false);
}
$pass = false;
// Pass Article Id
if ( ! $this->passItemByType($pass, 'ContentIds'))
{
return $this->pass(false);
}
// Pass Authors
if ( ! $this->passItemByType($pass, 'Authors'))
{
return $this->pass(false);
}
return $this->pass($pass);
}
public function getItem($fields = [])
{
$query = $this->db->getQuery(true)
->select($fields)
->from('#__zoo_item')
->where('id = ' . (int) $this->request->id);
$this->db->setQuery($query);
return $this->db->loadObject();
}
private function getCatParentIds($id = 0)
{
$parent_ids = [];
if ( ! $id)
{
return $parent_ids;
}
while ($id)
{
if (substr($id, 0, 3) == 'app')
{
$parent_ids[] = $id;
break;
}
$query = $this->db->getQuery(true)
->select('c.parent')
->from('#__zoo_category AS c')
->where('c.id = ' . (int) $id);
$this->db->setQuery($query);
$pid = $this->db->loadResult();
if ( ! $pid)
{
$query = $this->db->getQuery(true)
->select('c.application_id')
->from('#__zoo_category AS c')
->where('c.id = ' . (int) $id);
$this->db->setQuery($query);
$app = $this->db->loadResult();
if ($app)
{
$parent_ids[] = 'app' . $app;
}
break;
}
$parent_ids[] = $pid;
$id = $pid;
}
return $parent_ids;
}
}
assignments.php000064400000002132151166122740007613 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Conditions as RL_Conditions;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLAssignmentsHelper
{
function passAll($assignments, $matching_method = 'all', $item =
0)
{
return RL_Conditions::pass($assignments, $matching_method, $item);
}
public function getAssignmentsFromParams(&$params)
{
return RL_Conditions::getConditionsFromParams($params);
}
public function getAssignmentsFromTagAttributes(&$params, $types = [])
{
return RL_Conditions::getConditionsFromTagAttributes($params, $types);
}
public function hasAssignments(&$assignments)
{
return RL_Conditions::hasConditions($assignments);
}
}
cache.php000064400000001734151166122740006332 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Cache as RL_Cache;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLCache
{
static $cache = [];
public static function has($id)
{
return RL_Cache::has($id);
}
public static function get($id)
{
return RL_Cache::get($id);
}
public static function set($id, $data)
{
return RL_Cache::set($id, $data);
}
public static function read($id)
{
return RL_Cache::read($id);
}
public static function write($id, $data, $ttl = 0)
{
return RL_Cache::write($id, $data, $ttl);
}
}
field.php000064400000001070151166122740006343 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLFormField
extends \RegularLabs\Library\Field
{
}
functions.php000064400000010562151166122740007276 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Document as RL_Document;
use RegularLabs\Library\Extension as RL_Extension;
use RegularLabs\Library\File as RL_File;
use RegularLabs\Library\Http as RL_Http;
use RegularLabs\Library\Language as RL_Language;
use RegularLabs\Library\Xml as RL_Xml;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
/**
* Framework Functions
*/
class RLFunctions
{
public static function getContents($url, $timeout = 20)
{
return ! class_exists('RegularLabs\Library\Http') ?
'' : RL_Http::get($url, $timeout);
}
public static function getByUrl($url, $timeout = 20)
{
return ! class_exists('RegularLabs\Library\Http') ?
'' : RL_Http::getFromServer($url, $timeout);
}
public static function isFeed()
{
return class_exists('RegularLabs\Library\Document') &&
RL_Document::isFeed();
}
public static function script($file, $version = '')
{
class_exists('RegularLabs\Library\Document') &&
RL_Document::script($file, $version);
}
public static function stylesheet($file, $version = '')
{
class_exists('RegularLabs\Library\Document') &&
RL_Document::stylesheet($file, $version);
}
public static function addScriptVersion($url)
{
jimport('joomla.filesystem.file');
$version = '';
if (file_exists(JPATH_SITE . $url))
{
$version = filemtime(JPATH_SITE . $url);
}
self::script($url, $version);
}
public static function addStyleSheetVersion($url)
{
jimport('joomla.filesystem.file');
$version = '';
if (file_exists(JPATH_SITE . $url))
{
$version = filemtime(JPATH_SITE . $url);
}
self::stylesheet($url, $version);
}
protected static function getFileByFolder($folder, $file)
{
return ! class_exists('RegularLabs\Library\File') ?
'' : RL_File::getMediaFile($folder, $file);
}
public static function getComponentBuffer()
{
return ! class_exists('RegularLabs\Library\Document') ?
'' : RL_Document::getBuffer();
}
public static function getAliasAndElement(&$name)
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getAliasAndElement($name);
}
public static function getNameByAlias($alias)
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getNameByAlias($alias);
}
public static function getAliasByName($name)
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getAliasByName($name);
}
public static function getElementByAlias($alias)
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getElementByAlias($alias);
}
public static function getXMLValue($key, $alias, $type =
'component', $folder = 'system')
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getXMLValue($key, $alias, $type, $folder);
}
public static function getXML($alias, $type = 'component',
$folder = 'system')
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getXML($alias, $type, $folder);
}
public static function getXMLFile($alias, $type = 'component',
$folder = 'system')
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getXMLFile($alias, $type, $folder);
}
public static function extensionInstalled($extension, $type =
'component', $folder = 'system')
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::isInstalled($extension, $type, $folder);
}
public static function getExtensionPath($extension =
'plg_system_regularlabs', $basePath = JPATH_ADMINISTRATOR,
$check_folder = '')
{
return ! class_exists('RegularLabs\Library\Extension') ?
'' : RL_Extension::getPath($extension, $basePath, $check_folder);
}
public static function loadLanguage($extension =
'plg_system_regularlabs', $basePath = '', $reload =
false)
{
return class_exists('RegularLabs\Library\Language') &&
RL_Language::load($extension, $basePath, $reload);
}
public static function xmlToObject($url, $root = '')
{
return ! class_exists('RegularLabs\Library\Xml') ? ''
: RL_Xml::toObject($url, $root);
}
}
groupfield.php000064400000001102151166122740007414 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLFormGroupField
extends \RegularLabs\Library\FieldGroup
{
}
helper.php000064400000144146151166122740006553 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Filesystem\Folder;
use Joomla\CMS\Filesystem\Path;
use Joomla\CMS\Plugin\PluginHelper;
require_once JPATH_ROOT .
'/components/com_sppagebuilder/builder/classes/base.php';
class SppagebuilderHelperSite
{
/**
* Addon structures
*
* @var array
*/
private static $addonFieldStructures = [];
/**
* Column settings structure
*
* @var array
*/
private static $columnFieldStructures = [];
/**
* Section/row settings structure
*
* @var array
*/
private static $sectionFieldStructures = [];
/**
* Section field types
*
* @var array
*/
private static $sectionFieldTypes = [];
/**
* Column field types
*
* @var array
*/
private static $columnFieldTypes = [];
/**
* The fields types
*
* @var array
*/
private static $addonFieldTypes = [];
/**
* Check if the data come from the version 3 or bellow.
*
* @var boolean
*/
private static $isLegacyData = false;
private static function getAddonGlobalFieldStructures()
{
$structures = [];
$globalSettings = SpPgaeBuilderBase::addonOptions();
foreach ($globalSettings as $setting)
{
$structures = array_merge($structures, $setting);
}
return $structures;
}
/**
* Load the addon structure from the admin.php files.
*
* @return void
*/
private static function prepareAddonFieldStructures()
{
self::loadLanguage();
SpPgaeBuilderBase::loadAddons();
$addons = SpAddonsConfig::$addons;
$globalStructures = self::getAddonGlobalFieldStructures();
foreach ($addons as &$addon)
{
$addon = AddonsHelper::modernizeAddonStructure($addon);
$addon['addon_name'] = preg_replace('/^sp_/i',
'', $addon['addon_name']);
$addon['settings'] = array_merge($addon['settings'],
$globalStructures);
}
unset($addon);
self::$addonFieldStructures = $addons;
}
private static function prepareSectionFieldStructures()
{
$sectionSettings = SpPgaeBuilderBase::getRowGlobalSettings();
foreach ($sectionSettings as $setting)
{
self::$sectionFieldStructures =
array_merge(self::$sectionFieldStructures, $setting);
}
}
private static function prepareColumnFieldStructures()
{
$columnSettings = SpPgaeBuilderBase::getColumnGlobalSettings();
foreach ($columnSettings as $setting)
{
self::$columnFieldStructures = array_merge(self::$columnFieldStructures,
$setting);
}
}
/**
* Predict the column's fill style if it is fit in a single line
* or multiple line.
*
* @param array $columns The columns array.
*
* @return stdClass The fit value after prediction.
* @since 4.0.0
*/
private static function predictColumnFillStyle(array $columns): stdClass
{
$fitObject = (object) ['xl' => false, 'lg' =>
false, 'md' => false, 'sm' => false,
'xs' => false];
foreach (['xl', 'lg', 'md', 'sm',
'xs'] as $key)
{
$total = 0;
foreach ($columns as $column)
{
$width = self::getColumnWidth($column);
$total += (float) $width->$key;
}
if ($total <= 100)
{
$fitObject->$key = true;
}
}
return $fitObject;
}
/**
* Generate the column widths from the columns class_name property.
*
* @param stdClass $column The column object.
*
* @return stdClass The generated width object for
multiple device.
* @since 4.0.0
*/
public static function getColumnWidth(stdClass $column): stdClass
{
$width = (object) ['xl' => '100%', 'lg'
=> '100%', 'md' => '100%',
'sm' => '100%', 'xs' =>
'100%'];
$size = (int) \substr($column->class_name, 7);
$value = self::calculateColumnPercent($size);
$width->xl = $value;
if (!empty($column->settings->sm_col))
{
$smSize = (int) \substr($column->settings->sm_col, 7);
$width->md = self::calculateColumnPercent($smSize);
$width->lg = self::calculateColumnPercent($smSize);
}
if (!empty($column->settings->xs_col))
{
$xsSize = (int) \substr($column->settings->xs_col, 7);
$width->xs = self::calculateColumnPercent($xsSize);
$width->sm = self::calculateColumnPercent($xsSize);
}
return $width;
}
private static function isValidWidthValue($width)
{
return preg_match("@^\d+(\.\d+)?%$@", $width);
}
public static function purifyColumnWidth($width)
{
$defaultDevice = SpPgaeBuilderBase::$defaultDevice;
$smallDevices = ['sm', 'xs'];
if (\is_object($width))
{
$deviceData = $width->$defaultDevice;
foreach ($width as $device => $value)
{
if (!self::isValidWidthValue($value))
{
if (\in_array($device, $smallDevices))
{
$width->$device = '100%';
}
else
{
$width->$device = !empty($deviceData) ? $deviceData :
'100%';
}
}
}
}
return $width;
}
/**
* Calculate the column percentage from the column size.
*
* @param int $size The size value ranged from 1 to 12.
*
* @return string The percentage value w.r.t the the size.
* @since 4.0.0
*/
private static function calculateColumnPercent(int $size): string
{
return ((100 / 12) * (int) $size) . '%';
}
// Generate unique id
public static function nanoid(int $size = 21): string
{
$urlAlphabet =
"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
$id = "";
$i = $size;
while ($i--)
{
$id .= $urlAlphabet[rand(0, 63) | 0];
}
return $id;
}
// Generate unique id
public static function numberNanoid(int $size = 21): string
{
$urlAlphabet = "0123456789";
$id = "";
$i = $size;
while ($i--)
{
$id .= $urlAlphabet[rand(0, 9) | 0];
}
return intval($id);
}
private static function parseRow(array &$rows, \stdClass &$row)
{
if (isset($row->settings))
{
$row->settings = self::shiftResponsiveSettings($row->settings);
}
if (!empty($row->columns))
{
if (!isset($row->settings->fit_columns))
{
$row->settings->fit_columns =
self::predictColumnFillStyle($row->columns);
}
foreach ($row->columns as $i => &$column)
{
/** Predict the width from the column class name for the old layouts.
*/
if (!isset($column->width))
{
$width = self::getColumnWidth($column);
$column->width = $width;
}
if (\is_array($column->settings))
{
$column->settings = (object) $column->settings;
}
if (!isset($column->settings->width))
{
$width = !empty($column->width) ? $column->width :
self::getColumnWidth($column);
$column->settings->width = $width;
if (isset($column->settings->width->unit))
{
unset($column->settings->width->unit);
}
}
$column->settings->width =
self::purifyColumnWidth($column->settings->width);
if (isset($column->settings))
{
$column
->settings = self::shiftResponsiveSettings($column->settings);
}
if (!empty($column->addons))
{
foreach ($column->addons as $j => &$addon)
{
if (isset($addon->settings))
{
$addon->settings =
self::shiftResponsiveSettings($addon->settings);
}
/** Migrate the slideshow items. */
if (isset($addon->name) && $addon->name ===
'js_slideshow')
{
if (!empty($addon->settings->slideshow_items))
{
foreach ($addon->settings->slideshow_items as $x =>
&$slideshowItem)
{
if (isset($slideshowItem->slider_overlay_options) &&
$slideshowItem->slider_overlay_options === 'gradient_overaly')
{
$slideshowItem->slider_overlay_options =
'gradient_overlay';
}
if (isset($slideshowItem->slider_bg_gradient_overlay)
&& !isset($slideshowItem->slider_bg_gradient_overlay->type))
{
$slideshowItem->slider_bg_gradient_overlay->type =
'linear';
}
$slideshowItem = self::shiftResponsiveSettings($slideshowItem);
if (!empty($slideshowItem->slideshow_inner_items))
{
foreach ($slideshowItem->slideshow_inner_items as $y =>
&$innerItem)
{
$innerItem = self::shiftResponsiveSettings($innerItem);
}
unset($innerItem);
}
}
unset($slideshowItem);
}
}
/** Migrate the responsive settings for the repeatable items. */
if (isset($addon->name) && \in_array($addon->name,
['accordion', 'tab']))
{
$repeatableKey = 'sp_' . $addon->name .
'_item';
if (!empty($addon->settings->$repeatableKey))
{
foreach ($addon->settings->$repeatableKey as
&$itemSetting)
{
$itemSetting = self::shiftResponsiveSettings($itemSetting);
}
unset($itemSetting);
}
}
if (isset($addon->name) && \in_array($addon->name,
['accordion', 'tab']))
{
list($outerRows, $_addon) = self::migrateDeepAddon($addon,
'sp_' . $addon->name . '_item', $row, $column);
$addon = $_addon;
array_push($rows, ...$outerRows);
}
if (isset($addon->name) && $addon->name ===
'table_advanced')
{
$nodeId = self::generateUUID();
if (isset($addon->settings->sp_table_advanced_item))
{
foreach ($addon->settings->sp_table_advanced_item as $th
=> $thead)
{
if (isset($thead->content) &&
!\is_array($thead->content))
{
$thead = ['id' => $nodeId++, 'name' =>
'text_block', 'visibility' => true,
'reference_id' => $addon->id, 'settings' =>
['text' => $thead->content]];
$thead = \json_decode(\json_encode($thead));
$addon
->settings
->sp_table_advanced_item[$th]
->content = [];
$addon
->settings
->sp_table_advanced_item[$th]
->content[] = $thead;
}
elseif (isset($thead->content) &&
\is_array($thead->content))
{
$contents = [];
foreach ($thead->content as $content)
{
$content->reference_id = $addon->id;
$contents[] = $content;
}
$addon
->settings
->sp_table_advanced_item[$th]
->content = $contents;
}
}
}
foreach ($addon->settings->table_advanced_item as $r =>
$tRow)
{
if (isset($tRow->table_advanced_item))
{
foreach ($tRow->table_advanced_item as $c => $tCell)
{
if (isset($tCell->content) &&
!\is_array($tCell->content))
{
$td = ['id' => $nodeId++, 'name' =>
'text_block', 'visibility' => true,
'reference_id' => $addon->id, 'settings' =>
['text' => $tCell->content]];
$td = \json_decode(\json_encode($td));
$addon
->settings
->table_advanced_item[$r]
->table_advanced_item[$c]
->content = [];
$addon
->settings
->table_advanced_item[$r]
->table_advanced_item[$c]
->content[] = $td;
}
elseif (isset($tCell->content) &&
\is_array($tCell->content))
{
$contents = [];
foreach ($tCell->content as &$content)
{
$content->reference_id = $addon->id;
$contents[] = $content;
}
$addon
->settings
->table_advanced_item[$r]
->table_advanced_item[$c]
->content = $contents;
unset($content);
}
}
}
}
}
if (isset($addon->type) && $addon->type ===
'inner_row')
{
$addon->id = self::nanoid();
$nestedRowAddon = new \stdClass;
$nestedRowAddon->type = 'nested_row';
$nestedRowAddon->name = 'row';
$nestedRowAddon->id = $addon->id;
$addon->parent = new \stdClass;
$addon->parent->rowId = $row->id;
$addon->parent->columnId = $column->id;
$rows[] = $addon;
$addon = $nestedRowAddon;
}
}
unset($addon);
}
}
unset($column);
}
}
/**
* sanitize import json for making the old data valid for the data
structure.
*
* @param string $text The json text of the page builder data.
*
* @return string The sanitized text.
*
* @since 4.0.0
*/
public static function sanitizeImportJSON(string $text): string
{
$rows = json_decode($text);
if (is_string($rows))
{
$rows = json_decode($rows);
}
if (!empty($rows))
{
foreach ($rows as $key => &$row)
{
self::parseRow($rows, $row);
}
unset($row);
}
else
{
return $text;
}
return json_encode($rows);
}
private static $defaultValueWithUnit = ['value' =>
'', 'unit' => 'px'];
private static function getDefaultTypographyData()
{
$deviceData = [
'xl' => self::$defaultValueWithUnit,
'lg' => self::$defaultValueWithUnit,
'md' => self::$defaultValueWithUnit,
'sm' => self::$defaultValueWithUnit,
'xs' => self::$defaultValueWithUnit,
];
return (object) [
'font' => '',
'size' => $deviceData,
'line_height' => $deviceData,
'letter_spacing' => $deviceData,
'uppercase' => false,
'italic' => false,
'underline' => false,
'weight' => '',
'type' => 'google',
];
}
private static function isUnitValue($data)
{
return isset($data->value) && isset($data->unit);
}
private static function handleDeviceValues($data, $fieldKey)
{
$deviceData = [
'xl' => self::$defaultValueWithUnit,
'lg' => self::$defaultValueWithUnit,
'md' => self::$defaultValueWithUnit,
'sm' => self::$defaultValueWithUnit,
'xs' => self::$defaultValueWithUnit,
];
$responsiveKeys = ['size', 'line_height',
'letter_spacing'];
$pattern = "@px|rem|em|%@i";
if (in_array($fieldKey, $responsiveKeys))
{
if (\is_object($data))
{
$finalValue = self::$defaultValueWithUnit;
foreach ($data as $device => $value)
{
if (self::isUnitValue($value))
{
$finalValue = (array) $value;
$finalValue['value'] = preg_match($pattern,
$finalValue['value']) ? (float) $finalValue['value'] :
$finalValue['value'];
$finalValue['value'] = (string)
$finalValue['value'];
}
else
{
$finalValue['value'] = $value ?? '';
$finalValue['value'] = preg_match($pattern,
$finalValue['value']) ? (float) $finalValue['value'] :
$finalValue['value'];
$finalValue['value'] = (string)
$finalValue['value'];
}
$deviceData[$device] = $finalValue;
}
}
else
{
$deviceData['xl']['value'] = preg_match($pattern,
$data) ? (float) $data : $data;
$deviceData['xl']['value'] = (string)
$deviceData['xl']['value'];
}
if (!empty($deviceData['md']['value']) &&
empty($deviceData['xl']['value']))
{
$deviceData['xl'] = $deviceData['md'];
}
return (object) $deviceData;
}
return $data;
}
private static function getFieldsWithFallbacks($settings)
{
$fieldArray = [];
if (empty($settings))
{
return $fieldArray;
}
foreach ($settings as $setting)
{
if (!empty($setting['fields']))
{
foreach ($setting['fields'] as $fieldName => &$field)
{
if (isset($field['type']) &&
$field['type'] === 'repeatable' &&
!empty($field['attr']))
{
$field['attr'] =
self::getFieldsWithFallbacks($field['attr'] ?? []);
if (!empty($field['attr']))
{
$fieldArray[$fieldName] = $field;
}
}
if (!empty($field['fallbacks']))
{
$fieldArray[$fieldName] = $field;
}
}
unset($field);
}
}
return $fieldArray;
}
private static function getFieldStructureForTypography()
{
$fallbackFields = [];
foreach (self::$addonFieldStructures as &$addon)
{
$addonName = $addon['addon_name'];
$fallbackFields[$addonName] =
self::getFieldsWithFallbacks($addon['settings'] ?? []);
}
unset($addon);
return $fallbackFields;
}
private static function retrieveFieldTypesFromSettings($settings)
{
$types = [];
foreach ($settings as $group)
{
if (!empty($group['fields']))
{
foreach ($group['fields'] as $key => $field)
{
$fieldtype = $field['type'] ?? '';
if ($fieldtype === 'repeatable')
{
$types[$key] = [
'type' => 'repeatable',
'fields' =>
self::retrieveFieldTypesFromSettings($field['attr'])
];
}
else
{
$types[$key] = $fieldtype;
}
}
}
}
return $types;
}
private static function processFieldTypes($type)
{
switch ($type)
{
case 'section':
self::$sectionFieldTypes =
self::retrieveFieldTypesFromSettings(self::$sectionFieldStructures);
break;
case 'column':
self::$columnFieldTypes =
self::retrieveFieldTypesFromSettings(self::$columnFieldStructures);
break;
case 'addon':
foreach (self::$addonFieldStructures as $addon)
{
$addonName = $addon['addon_name'];
$addonFieldTypes[$addonName] =
self::retrieveFieldTypesFromSettings($addon['settings']);
}
self::$addonFieldTypes = $addonFieldTypes;
break;
}
}
private static function parseResponsiveTypography($data)
{
if (!is_object($data))
{
return $data;
}
$keys = ['letter_spacing', 'size',
'line_height'];
foreach ($keys as $key)
{
$typographyItem = $data->$key ?? null;
if (!$typographyItem)
{
continue;
}
if (!empty($typographyItem->md->value) &&
empty($typographyItem->xl->value))
{
$data->$key->xl = clone $typographyItem->md;
}
}
return $data;
}
private static function getFallbackValues($settings, string $fieldName,
$field)
{
$fallbacks = $field['fallbacks'] ?? [];
if (!isset($settings->$fieldName))
{
$settings->$fieldName = new stdClass;
$isTypographyField = isset($field['type']) &&
$field['type'] === 'typography';
if ($isTypographyField)
{
$settings->$fieldName = self::getDefaultTypographyData();
}
foreach ($fallbacks as $fieldKey => $referenceKey)
{
$fallbackParts = explode('.', $referenceKey, 2);
$masterKey = $fallbackParts[0] ?? null;
$slaveKey = $fallbackParts[1] ?? null;
if (!empty($masterKey) && !empty($slaveKey))
{
$fallbackValue = isset($settings->$masterKey->$slaveKey) ?
$settings->$masterKey->$slaveKey : '';
}
elseif (!empty($masterKey) && empty($slaveKey))
{
$fallbackValue = isset($settings->$masterKey) ?
$settings->$masterKey : '';
}
if ($isTypographyField)
{
$settings->$fieldName->$fieldKey =
self::handleDeviceValues($fallbackValue, $fieldKey);
}
else
{
$settings->$fieldName->$fieldKey = $fallbackValue;
}
}
}
else
{
$settings->$fieldName =
self::parseResponsiveTypography($settings->$fieldName);
}
return $settings;
}
/**
* Read the fallback values of the typography fields.
*
* @param stdClass $settings
* @param string $addonName
*
* @return stdClass The modified settings value.
* @since 5.0.0
*/
private static function getTypographyFromFallbacks($settings, $addonName)
{
$fieldStructures = self::getFieldStructureForTypography();
$fieldStructureByAddon = $fieldStructures[$addonName] ?? null;
if (empty($fieldStructureByAddon))
{
return $settings;
}
foreach ($settings as $key => &$setting)
{
$field = !empty($fieldStructureByAddon[$key]) ?
$fieldStructureByAddon[$key] : [];
if (!empty($field['type']) && $field['type']
=== 'repeatable' && !empty($field['attr']))
{
$attributes = $field['attr'];
foreach ($attributes as $fieldName => $attribute)
{
$fallbacks = $attribute['fallbacks'] ?? [];
if (is_array($setting) && !empty($setting))
{
foreach ($setting as &$value)
{
$value = self::getFallbackValues($value, $fieldName, $attribute);
}
unset($value);
}
}
}
}
unset($setting);
foreach ($fieldStructureByAddon as $fieldName => $field)
{
$fallbacks = $field['fallbacks'] ?? [];
if (!empty($fallbacks))
{
$settings = self::getFallbackValues($settings, $fieldName, $field);
}
}
return $settings;
}
private static function reshapeSpacingValues($spacing, $forceModern =
false)
{
$isLegacy = self::$isLegacyData && !$forceModern;
$reshapedValue = $isLegacy ? ['', '', '',
''] : ['0px', '0px', '0px',
'0px'];
$spacing = \ctype_space((string) $spacing) || $spacing === '' ?
[] : explode(' ', $spacing);
$spacing = array_map(function($value) use($isLegacy) {
if (!$isLegacy && $value === '') {
return '0px';
}
return $value;
}, $spacing);
$spacing = array_filter($spacing, function ($value)
{
return isset($value) && $value !== '';
});
$spacing = array_values($spacing);
$newSpacing = [];
switch (count($spacing))
{
case 0:
$newSpacing = [''];
break;
case 1:
$newSpacing = $isLegacy
? array_fill(0, 4, $spacing[0])
: array_replace($reshapedValue, $spacing);
break;
case 2:
$newSpacing = $isLegacy
? [$spacing[0], $spacing[1], $spacing[0], $spacing[1]]
: array_replace($reshapedValue, $spacing);
break;
case 3:
$newSpacing = $isLegacy
? [$spacing[0], $spacing[1], $spacing[2], $spacing[1]]
: array_replace($reshapedValue, $spacing);
break;
case 4:
$newSpacing = $spacing;
break;
}
return implode(" ", $newSpacing);
}
private static function transformSpacingValues($value, $forceModern =
false)
{
if (self::hasMultiDeviceSettings($value))
{
foreach ($value as $device => $deviceData)
{
$value->$device = !empty($deviceData) ?
self::reshapeSpacingValues($deviceData, $forceModern) : $deviceData;
}
}
elseif (is_string($value))
{
$value = self::reshapeSpacingValues($value, $forceModern);
}
return $value;
}
private static function traverseSettingsToFixSpacingAnomalies($settings,
$fieldTypes, $forceModern = false)
{
if ($fieldTypes === null)
{
return $settings;
}
if (!empty($settings))
{
foreach ($settings as $key => &$value)
{
$fieldType = $fieldTypes[$key] ?? null;
if ($fieldType === null || (is_string($fieldType) &&
!in_array($fieldType, ['padding', 'margin'])))
{
continue;
}
if (is_array($fieldType))
{
$repeatableTypes = $fieldType['fields'];
if (is_array($value))
{
foreach ($value as &$repeatableValue)
{
$repeatableValue =
self::traverseSettingsToFixSpacingAnomalies($repeatableValue,
$repeatableTypes, false);
}
}
}
else
{
$value = self::transformSpacingValues($value, $forceModern);
}
}
unset($value);
}
return $settings;
}
private static function parsingSpacingValues($settings, $type, $addonName
= '')
{
if ($type === 'addon' && (empty($addonName) ||
!isset(self::$addonFieldTypes[$addonName])))
{
return $settings;
}
switch ($type)
{
case 'section':
$fieldTypes = self::$sectionFieldTypes;
break;
case 'column':
$fieldTypes = self::$columnFieldTypes;
break;
case 'addon':
$fieldTypes = self::$addonFieldTypes[$addonName];
break;
}
return self::traverseSettingsToFixSpacingAnomalies($settings,
$fieldTypes, in_array($type, ['section', 'column']));
}
private static function hasLegacyDataInsideSettings($settings)
{
if (!empty($settings))
{
foreach ($settings as $setting)
{
if (self::hasMultiDeviceSettings($setting) &&
isset($setting->xl))
{
return false;
}
}
}
return true;
}
private static function isLegacyDataStructure($content)
{
foreach ($content as $row)
{
$settings = $row->settings;
if (!self::hasLegacyDataInsideSettings($settings))
{
return false;
}
}
return true;
}
public static function prepareSpacingData($text)
{
self::prepareSectionFieldStructures();
self::prepareColumnFieldStructures();
self::prepareAddonFieldStructures();
self::processFieldTypes('section');
self::processFieldTypes('column');
self::processFieldTypes('addon');
$content = is_string($text) ? json_decode($text) : $text;
self::$isLegacyData = self::isLegacyDataStructure($content);
if (!empty($content))
{
foreach ($content as &$section)
{
$section->settings =
self::parsingSpacingValues($section->settings, 'section');
if (!empty($section->columns))
{
foreach ($section->columns as &$column)
{
$column->settings =
self::parsingSpacingValues($column->settings, 'column');
if (!empty($column->addons))
{
foreach ($column->addons as &$addon)
{
if (!empty($addon->settings))
{
$addon->settings =
self::parsingSpacingValues($addon->settings, 'addon',
$addon->name ?? '');
}
}
unset($addon);
}
}
unset($column);
}
}
unset($section);
}
return json_encode($content);
}
/**
* sanitize contents for making the old data valid for the data structure.
*
* @param string $text The json text of the page builder data.
*
* @return string The sanitized text.
*
* @since 4.0.0
*/
public static function sanitize(string $text): string
{
if (empty(self::$addonFieldStructures))
{
self::prepareAddonFieldStructures();
}
$rows = json_decode($text);
if (!empty($rows))
{
foreach ($rows as $key => &$row)
{
if (isset($rows[$key]->settings))
{
$rows[$key]->settings =
self::shiftResponsiveSettings($row->settings);
$rows[$key]->settings = self::fixRowSettings($row->settings);
}
if (!empty($row->columns))
{
if (!isset($row->settings->fit_columns))
{
$row->settings->fit_columns =
self::predictColumnFillStyle($row->columns);
}
foreach ($row->columns as $i => &$column)
{
/** Predict the width from the column class name for the old layouts.
*/
if (!isset($column->width))
{
$width = self::getColumnWidth($column);
$column->width = $width;
}
if (\is_array($column->settings))
{
$column->settings = (object) $column->settings;
}
if (!isset($column->settings->width))
{
$width = !empty($column->width) ? $column->width :
self::getColumnWidth($column);
$column->settings->width = $width;
if (isset($column->settings->width->unit))
{
unset($column->settings->width->unit);
}
}
$column->settings->width =
self::purifyColumnWidth($column->settings->width);
if (isset($rows[$key]->columns[$i]->settings))
{
$rows[$key]
->columns[$i]
->settings =
self::shiftResponsiveSettings($rows[$key]->columns[$i]->settings);
}
if (!empty($column->addons))
{
foreach ($column->addons as $j => &$addon)
{
if (isset($rows[$key]->columns[$i]->addons[$j]->settings))
{
$rows[$key]
->columns[$i]
->addons[$j]
->settings =
self::shiftResponsiveSettings($rows[$key]->columns[$i]->addons[$j]->settings);
if (isset($addon->name) && $addon->name ===
'image_layouts')
{
$addonSettings = $addon->settings;
$isBtnTextExist = property_exists($addonSettings,
'btn_text');
$isButtonTextExist = property_exists($addonSettings,
'button_text');
if (!$isButtonTextExist && $isBtnTextExist)
{
$addonSettings->button_text = $addonSettings->btn_text;
}
$isBtnTypeExist = property_exists($addonSettings,
'btn_type');
$isButtonTypeExist = property_exists($addonSettings,
'button_type');
if (!$isButtonTypeExist && $isBtnTypeExist)
{
$addonSettings->button_type = $addonSettings->btn_type;
}
$isBtnShapeExist = property_exists($addonSettings,
'btn_shape');
$isButtonShapeExist = property_exists($addonSettings,
'button_shape');
if (!$isButtonShapeExist && $isBtnShapeExist)
{
$addonSettings->button_shape = $addonSettings->btn_shape;
}
$isBtnSizeExist = property_exists($addonSettings,
'btn_size');
$isButtonSizeExist = property_exists($addonSettings,
'button_size');
if (!$isButtonSizeExist && $isBtnSizeExist)
{
$addonSettings->button_size = $addonSettings->btn_size;
}
$isBtnColorExist = property_exists($addonSettings,
'btn_color');
$isButtonColorExist = property_exists($addonSettings,
'button_color');
if (!$isButtonColorExist && $isBtnColorExist)
{
$addonSettings->button_color = $addonSettings->btn_color;
}
$isBtnColorHoverExist = property_exists($addonSettings,
'btn_color_hover');
$isButtonColorHoverExist = property_exists($addonSettings,
'button_color_hover');
if (!$isButtonColorHoverExist && $isBtnColorHoverExist)
{
$addonSettings->button_color_hover =
$addonSettings->btn_color_hover;
}
$isBtnAppearanceExist = property_exists($addonSettings,
'btn_appearance');
$isButtonAppearanceExist = property_exists($addonSettings,
'button_appearance');
if (!$isButtonAppearanceExist && $isBtnAppearanceExist)
{
$addonSettings->button_appearance =
$addonSettings->btn_appearance;
}
$isBtnBackgroundColorExist = property_exists($addonSettings,
'btn_background_color');
$isButtonBackgroundColorExist = property_exists($addonSettings,
'button_background_color');
if (!$isButtonBackgroundColorExist &&
$isBtnBackgroundColorExist)
{
$addonSettings->button_background_color =
$addonSettings->btn_background_color;
}
$isBtnBackgroundColorHoverExist = property_exists($addonSettings,
'btn_background_color_hover');
$isButtonBackgroundColorHoverExist =
property_exists($addonSettings, 'button_background_color_hover');
if (!$isButtonBackgroundColorHoverExist &&
$isBtnBackgroundColorHoverExist)
{
$addonSettings->button_background_color_hover =
$addonSettings->btn_background_color_hover;
}
$isBtnBackgroundGradientExist = property_exists($addonSettings,
'btn_background_gradient');
$isButtonBackgroundGradientExist =
property_exists($addonSettings, 'button_background_gradient');
if (!$isButtonBackgroundGradientExist &&
$isBtnBackgroundGradientExist)
{
$addonSettings->button_background_gradient =
$addonSettings->btn_background_gradient;
}
$isBtnBackgroundGradientHoverExist =
property_exists($addonSettings, 'btn_background_gradient_hover');
$isButtonBackgroundGradientHoverExist =
property_exists($addonSettings,
'button_background_gradient_hover');
if (!$isButtonBackgroundGradientHoverExist &&
$isBtnBackgroundGradientHoverExist)
{
$addonSettings->button_background_gradient_hover =
$addonSettings->btn_background_gradient_hover;
}
}
}
if (isset($addon->name) && isset($addon->settings))
{
$addon->settings =
self::getTypographyFromFallbacks($addon->settings, $addon->name);
}
/** Migrate the slideshow items. */
if (isset($addon->name) && $addon->name ===
'js_slideshow')
{
if (!empty($addon->settings->slideshow_items))
{
foreach ($addon->settings->slideshow_items as $x =>
&$slideshowItem)
{
if (isset($slideshowItem->slider_overlay_options) &&
$slideshowItem->slider_overlay_options === 'gradient_overaly')
{
$slideshowItem->slider_overlay_options =
'gradient_overlay';
}
if (isset($slideshowItem->slider_bg_gradient_overlay)
&& !isset($slideshowItem->slider_bg_gradient_overlay->type))
{
$slideshowItem->slider_bg_gradient_overlay->type =
'linear';
}
$slideshowItem = self::shiftResponsiveSettings($slideshowItem);
if (!empty($slideshowItem->slideshow_inner_items))
{
foreach ($slideshowItem->slideshow_inner_items as $y =>
&$innerItem)
{
$innerItem = self::shiftResponsiveSettings($innerItem);
}
unset($innerItem);
}
}
unset($slideshowItem);
}
}
/** Migrate the responsive settings for the repeatable items. */
if (isset($addon->name) && \in_array($addon->name,
['accordion', 'tab']))
{
$repeatableKey = 'sp_' . $addon->name .
'_item';
if (!empty($addon->settings->$repeatableKey))
{
foreach
($rows[$key]->columns[$i]->addons[$j]->settings->$repeatableKey
as &$itemSetting)
{
$itemSetting = self::shiftResponsiveSettings($itemSetting);
}
unset($itemSetting);
}
}
if (isset($addon->name) && \in_array($addon->name,
['accordion', 'tab']))
{
list($outerRows, $addon) = self::migrateDeepAddon($addon,
'sp_' . $addon->name . '_item', $row, $column);
$rows[$key]->columns[$i]->addons[$j] = $addon;
array_push($rows, ...$outerRows);
}
if (isset($addon->name) && $addon->name ===
'table_advanced')
{
$nodeId = self::generateUUID();
if (isset($addon->settings->sp_table_advanced_item))
{
foreach ($addon->settings->sp_table_advanced_item as $th
=> $thead)
{
if (isset($thead->content) &&
!\is_array($thead->content))
{
$thead = ['id' => $nodeId++, 'name'
=> 'text_block', 'visibility' => true,
'reference_id' => $addon->id, 'settings' =>
['text' => $thead->content]];
$thead = \json_decode(\json_encode($thead));
$rows[$key]
->columns[$i]
->addons[$j]
->settings
->sp_table_advanced_item[$th]
->content = [];
$rows[$key]
->columns[$i]
->addons[$j]
->settings
->sp_table_advanced_item[$th]
->content[] = $thead;
}
elseif (isset($thead->content) &&
\is_array($thead->content))
{
$contents = [];
foreach ($thead->content as $content)
{
$content->reference_id = $addon->id;
$contents[] = $content;
}
$rows[$key]
->columns[$i]
->addons[$j]
->settings
->sp_table_advanced_item[$th]
->content = $contents;
}
}
}
foreach ($addon->settings->table_advanced_item as $r =>
$tRow)
{
if (isset($tRow->table_advanced_item))
{
foreach ($tRow->table_advanced_item as $c => $tCell)
{
if (isset($tCell->content) &&
!\is_array($tCell->content))
{
$td = ['id' => $nodeId++, 'name' =>
'text_block', 'visibility' => true,
'reference_id' => $addon->id, 'settings' =>
['text' => $tCell->content]];
$td = \json_decode(\json_encode($td));
$rows[$key]
->columns[$i]
->addons[$j]
->settings
->table_advanced_item[$r]
->table_advanced_item[$c]
->content = [];
$rows[$key]
->columns[$i]
->addons[$j]
->settings
->table_advanced_item[$r]
->table_advanced_item[$c]
->content[] = $td;
}
elseif (isset($tCell->content) &&
\is_array($tCell->content))
{
$contents = [];
foreach ($tCell->content as &$content)
{
$content->reference_id = $addon->id;
$contents[] = $content;
}
$rows[$key]
->columns[$i]
->addons[$j]
->settings
->table_advanced_item[$r]
->table_advanced_item[$c]
->content = $contents;
unset($content);
}
}
}
}
}
if (isset($addon->type) && $addon->type ===
'inner_row')
{
$nestedRowAddon = new \stdClass;
$nestedRowAddon->type = 'nested_row';
$nestedRowAddon->name = 'row';
$nestedRowAddon->id = $addon->id;
$addon->parent = new \stdClass;
$addon->parent->rowId = $row->id;
$addon->parent->columnId = $column->id;
unset($addon->type);
$rows[] = $addon;
$rows[$key]->columns[$i]->addons[$j] = $nestedRowAddon;
}
}
unset($addon);
}
}
unset($column);
}
}
unset($row);
}
else
{
return $text;
}
return json_encode($rows);
}
public static function fixRowSettings($settings)
{
if (isset($settings->background_type))
{
return $settings;
}
$settings->background_type = 'none';
$keyMap = [
'background_image' => 'image',
'background_color' => 'color',
'background_gradient' => 'gradient',
'background_video' => 'video',
'background_video_mp4' => 'video',
'background_video_ogv' => 'video',
'background_external_video' => 'video'
];
foreach ($keyMap as $key => $value)
{
if (!empty($settings->$key))
{
$settings->background_type = $value;
break;
}
}
return $settings;
}
/**
* Migrate the accordion addon to the current structure.
*
* @param \stdClass $addon The accordion addon object.
*
* @return array
* @since 4.0.0
*/
private static function migrateDeepAddon(\stdClass $addon, $key, $row,
$column): array
{
$addon = json_decode(json_encode($addon));
$addonCollection = [];
$outerRows = [];
if (!isset($addon->parent) || (isset($addon->parent) &&
!$addon->parent))
{
$addon->id = self::nanoid();
}
if (isset($addon->settings->$key))
{
foreach ($addon->settings->$key as $itemIndex => $item)
{
$addonCollection = [];
if (isset($item->content) && \is_array($item->content))
{
foreach ($item->content as $deepAddon)
{
if (isset($deepAddon->type) && $deepAddon->type ===
'nested_row')
{
continue;
}
$addonCollection[] = $deepAddon;
}
if (\count($addonCollection) > 0)
{
$_parent = ['rowId' => $row->id, 'columnId'
=> $column->id];
$_parent = (object) $_parent;
$row = self::createRow('12', $addonCollection, $_parent);
$row->parent_addon = $addon->id;
$outerRows[] = $row;
$nestedRow = ['type' => 'nested_row',
'id' => $row->id, 'name' => 'row'];
$nestedRow = (object) $nestedRow;
$addon->settings->$key[$itemIndex]->content = [];
$addon->settings->$key[$itemIndex]->content[] = $nestedRow;
}
}
else if (isset($item->content) &&
\is_string($item->content))
{
$textAddon = ['id' => self::nanoid(), 'name'
=> 'text_block', 'settings' => ['text'
=> $item->content]];
$addonCollection[] = $textAddon;
$_parent = ['rowId' => $row->id, 'columnId'
=> $column->id];
$_parent = (object) $_parent;
$row = self::createRow('12', $addonCollection, $_parent);
$row->parent_addon = $addon->id;
$outerRows[] = $row;
$nestedRow = ['type' => 'nested_row',
'id' => $row->id, 'name' => 'row'];
$nestedRow = (object) $nestedRow;
$addon->settings->$key[$itemIndex]->content = [];
$addon->settings->$key[$itemIndex]->content[] = $nestedRow;
}
}
}
return [$outerRows, $addon];
}
/**
* Create Row function
*
* @param string $layout Default layout size
* @param array $addons Addons
* @param mixed $parent Parent row.
*
* @return object
*
* @since 4.0.0
*/
public static function createRow(string $layout = '12', array
$addons = [], $parent = null)
{
$rowId = self::nanoid();
$layouts = explode('+', $layout);
$rowDefaultValues = EditorUtils::getSectionSettingsDefaultValues();
$columnDefaultValues = EditorUtils::getColumnSettingsDefaultValues();
$rowDefaultValues = json_decode(json_encode($rowDefaultValues));
$columnDefaultValues = json_decode(json_encode($columnDefaultValues));
$columns = array_map(function ($col) use ($columnDefaultValues, $addons)
{
$width = (float) ((100 / (12 / (int) $col))) . '%';
$widthObject = ['xl' => $width, 'lg' =>
$width, 'md' => $width, 'sm' => '100%',
'xs' => '100%'];
$widthObject = (object) $widthObject;
$columnObject = [
'id' => self::nanoid(),
'class_name' => 'row-column',
'visibility' => true,
'settings' => $columnDefaultValues,
'addons' => $addons,
'width' => $widthObject,
];
return (object) $columnObject;
}, $layouts);
$rowDefaultValues->padding = '5px 0px 5px 0px';
$rowDefaultValues->margin = '0px 0px 0px 0px';
$rowObject = [
'id' => $rowId,
'visibility' => true,
'collapse' => false,
'settings' => $rowDefaultValues,
'layout' => $layout,
'columns' => $columns,
'parent' => $parent ? $parent : false,
];
return (object) $rowObject;
}
/**
* Generate a unique ID by using microtime.
*
* @return integer
* @since 4.0.0
*/
public static function generateUUID(): int
{
return (int) (microtime(true) * 1000);
}
/**
* Shift responsive device settings for with the new device structure.
*
* @param \stdClass $settings The settings value.
*
* @return \stdClass | null
* @since 4.0.0
*/
public static function shiftResponsiveSettings($settings)
{
if (!empty($settings))
{
foreach ($settings as $key => $setting)
{
if (\is_object($setting) && isset($setting->md) &&
!isset($setting->xl))
{
$tmp = (object) ['xl' => '', 'lg'
=> '', 'md' => '', 'sm' =>
'', 'xs' => ''];
if (isset($setting->md))
{
$tmp->xl = $setting->md;
}
if (isset($setting->sm))
{
$tmp->lg = $setting->sm;
$tmp->md = $setting->sm;
}
if (isset($setting->xs))
{
$tmp->sm = $setting->xs;
$tmp->xs = $setting->xs;
}
if (isset($setting->unit))
{
$tmp->unit = $setting->unit;
}
$settings->$key = $tmp;
}
}
if (isset($settings->hidden_md) &&
!isset($settings->hidden_xl))
{
if (isset($settings->hidden_md))
{
$settings->hidden_xl = $settings->hidden_md;
}
if (isset($settings->hidden_sm))
{
$settings->hidden_lg = $settings->hidden_sm;
$settings->hidden_md = $settings->hidden_sm;
}
if (isset($settings->hidden_xs))
{
$settings->hidden_sm = $settings->hidden_xs;
$settings->hidden_xs = $settings->hidden_xs;
}
}
}
return $settings;
}
/**
* Remove sp_ from the addon name
*
* @return void
* @since 4.0.0
*/
public static function sanitize_addon_name($addon_name)
{
$from = '/' . preg_quote('sp_', '/') .
'/';
return preg_replace($from, '', $addon_name, 1);
}
/**
* Load Language File
*
* @param boolean $forceLoad
* @return void
*/
public static function loadLanguage($forceLoad = false)
{
$lang = Factory::getLanguage();
$app = Factory::getApplication();
$template = $app->getTemplate();
if ($app->isClient('administrator'))
{
$template = self::getTemplate();
}
$com_option = $app->input->get('option', '',
'STR');
$com_view = $app->input->get('view', '',
'STR');
$com_id = $app->input->get('id', 0, 'INT');
if (($com_option == 'com_sppagebuilder' && $com_view ==
'form' && $com_id) || $forceLoad)
{
$lang->load('com_sppagebuilder', JPATH_ADMINISTRATOR, null,
true);
}
// Load template language file
$lang->load('tpl_' . $template, JPATH_SITE, null, true);
self::setPluginsAddonsLanguage();
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/helpers/language.php';
}
private static function getTemplate()
{
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select('template')
->from($db->quoteName('#__template_styles'))
->where($db->quoteName('client_id') . ' = 0')
->where($db->quoteName('home') . ' = 1');
$db->setQuery($query);
return $db->loadResult();
}
/**
* Load Plugin addons language files.
*
* @return void
*/
private static function setPluginsAddonsLanguage()
{
$path = JPATH_PLUGINS . '/sppagebuilder';
if (!Folder::exists($path)) return;
$plugins = Folder::folders($path);
if (!count((array) $plugins)) return;
foreach ($plugins as $plugin)
{
if (PluginHelper::isEnabled('sppagebuilder', $plugin))
{
$lang = Factory::getLanguage();
$lang->load('plg_' . $plugin, JPATH_ADMINISTRATOR, null,
true);
}
}
}
/**
* Convert Padding Margin Value.
*
* @param string $main_value CSS value
* @param string $type CSS property
*
* @return string
*
* @since 4.0.0
*/
public static function getPaddingMargin($main_value, $type): string
{
$css = '';
$pos = array('top', 'right', 'bottom',
'left');
if (is_string($main_value) && trim($main_value) != "")
{
$values = explode(' ', $main_value);
foreach ($values as $key => $value)
{
$value = preg_replace('@/s@', '', $value);
if ($value !== "")
{
$css .= $type . '-' . $pos[$key] . ': ' . $value .
';';
}
}
}
return $css;
}
public static function getSvgShapes()
{
$shape_path = JPATH_ROOT .
'/components/com_sppagebuilder/assets/shapes';
$shapes = Folder::files($shape_path, '.svg');
$shapeArray = array();
if (count((array) $shapes))
{
foreach ($shapes as $shape)
{
$shapeArray[str_replace('.svg', '', $shape)] =
base64_encode(file_get_contents($shape_path . '/' . $shape));
}
}
return $shapeArray;
}
public static function getSvgShapeCode($shapeName, $invert)
{
if ($invert)
{
$shape_path = JPATH_ROOT .
'/components/com_sppagebuilder/assets/shapes/' . $shapeName .
'-invert.svg';
}
else
{
$shape_path = JPATH_ROOT .
'/components/com_sppagebuilder/assets/shapes/' . $shapeName .
'.svg';
}
$shapeCode = '';
if (file_exists($shape_path))
{
$shapeCode = file_get_contents($shape_path);
}
return is_string($shapeCode) ? $shapeCode : '';
}
// Convert json code to plain text
public static function getPrettyText($sections)
{
if (!class_exists('AddonParser'))
{
require_once JPATH_ROOT .
'/components/com_sppagebuilder/parser/addon-parser.php';
}
if (!class_exists('SpPageBuilderAddonHelper'))
{
require_once JPATH_ROOT .
'/components/com_sppagebuilder/builder/classes/addon.php';
}
$sections = SpPageBuilderAddonHelper::__($sections);
$content = json_decode($sections);
$htmlContent = AddonParser::viewAddons($content);
$htmlContent = str_replace('><', '> <',
$htmlContent);
return trim(strip_tags($htmlContent));
}
public static function addScript($script, $client = 'site',
$version = true)
{
$doc = Factory::getDocument();
$script_url = Uri::base(true) . ($client == 'admin' ?
'/administrator' : '') .
'/components/com_sppagebuilder/assets/js/' . $script;
if ($version)
{
$script_url .= '?' . self::getVersion(true);
}
$doc->addScript($script_url);
}
public static function addStylesheet($stylesheet, $client =
'site', $version = true)
{
$doc = Factory::getDocument();
$stylesheet_url = Uri::base(true) . ($client == 'admin' ?
'/administrator' : '') .
'/components/com_sppagebuilder/assets/css/' . $stylesheet;
if ($version)
{
$stylesheet_url .= '?' . self::getVersion(true);
}
$doc->addStylesheet($stylesheet_url);
}
public static function addContainerMaxWidth()
{
$doc = Factory::getDocument();
$params = ComponentHelper::getParams('com_sppagebuilder');
$containerMaxWidth = $params->get('container_max_width',
1320);
$doc->addStyleDeclaration("@media(min-width: 1400px)
{.sppb-row-container { max-width: " . $containerMaxWidth . "px;
}}");
}
public static function getVersion($md5 = false)
{
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select('e.manifest_cache')
->select($db->quoteName('e.manifest_cache'))
->from($db->quoteName('#__extensions', 'e'))
->where($db->quoteName('e.element') . ' = ' .
$db->quote('com_sppagebuilder'));
$db->setQuery($query);
$manifest_cache = json_decode($db->loadResult());
if (isset($manifest_cache->version) &&
$manifest_cache->version)
{
if ($md5)
{
return md5($manifest_cache->version);
}
return $manifest_cache->version;
}
return '1.0';
}
/**
* Load Assets form database table.
*
* @return void
*/
public static function loadAssets()
{
$doc = Factory::getDocument();
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName(array('a.name',
'a.css_path')))
->from($db->quoteName('#__sppagebuilder_assets',
'a'))
->where($db->quoteName('a.published') . ' =
1');
$db->setQuery($query);
$assets = $db->loadObjectList();
if (!empty($assets))
{
foreach ($assets as $asset)
{
$asset_url = Uri::base(true) . '/' . $asset->css_path .
'?' . self::getVersion(true);
$doc->addStylesheet($asset_url);
}
}
}
/**
* Get the current template name form database.
*
* @return void
*/
public static function getTemplateName()
{
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(['template']))
->from($db->quoteName('#__template_styles'))
->where($db->quoteName('client_id') . ' = 0')
->where($db->quoteName('home') . ' = 1');
$db->setQuery($query);
return $db->loadObject()->template;
}
/**
* Get installed google fonts from database.
*
* @return array
*/
public static function getInstalledGoogleFonts()
{
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select('family_name')
->from($db->quoteName('#__sppagebuilder_fonts'))
->where($db->quoteName('type') . ' = ' .
$db->quote('google'));
$db->setQuery($query);
try
{
return $db->loadColumn() ?? [];
}
catch (Exception $e)
{
return [];
}
}
/**
* Checking multi device settings
*
* @param mixed $value
* @return boolean
*
* @since 5.0.0
*/
public static function hasMultiDeviceSettings($value): bool
{
return isset($value->xl)
|| isset($value->lg)
|| isset($value->md)
|| isset($value->sm)
|| isset($value->xs);
}
/**
* Checking media item
*
* @param mixed $value
* @return boolean
*
* @since 5.0.0
*/
public static function isMediaItemData($value): bool
{
return isset($value->src);
}
/**
* Clean media path
*
* @param string $path
* @return string
*
* @since 5.0.3
*/
public static function cleanPath($path): string
{
$cleanedPath = Path::clean($path);
$cleanedPath = str_replace("/\\","\\", $cleanedPath);
$cleanedPath = str_replace("\\","/", $cleanedPath);
return $cleanedPath;
}
}
html.php000064400000001656151166122740006236 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Form as RL_Form;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLHtml
{
static function selectlist(&$options, $name, $value, $id, $size = 0,
$multiple = 0, $simple = 0)
{
return RL_Form::selectList($options, $name, $value, $id, $size,
$multiple, $simple);
}
static function selectlistsimple(&$options, $name, $value, $id, $size
= 0, $multiple = 0)
{
return RL_Form::selectListSimple($options, $name, $value, $id, $size,
$multiple);
}
}
htmlfix.php000064400000001205151166122740006733 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Html as RL_Html;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLHtmlFix
{
public static function _($string)
{
return RL_Html::fix($string);
}
}
licenses.php000064400000001354151166122740007072 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\License as RL_License;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLLicenses
{
public static function render($name, $check_pro = false)
{
return ! class_exists('RegularLabs\Library\License') ?
'' : RL_License::getMessage($name, $check_pro);
}
}
mobile_detect.php000064400000001232151166122740010057 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLMobile_Detect extends \RegularLabs\Library\MobileDetect
{
public function isMac()
{
return $this->match('(Mac OS|Mac_PowerPC|Macintosh)');
}
}
parameters.php000064400000001236151166122740007427 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Parameters as RL_Parameters;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLParameters
{
public static function getInstance()
{
return RL_Parameters::getInstance();
}
}
protect.php000064400000014604151166122740006747 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Document as RL_Document;
use RegularLabs\Library\Protect as RL_Protect;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLProtect
{
public static function isProtectedPage($extension_alias = '',
$hastags = false, $exclude_formats = ['pdf'])
{
if ( ! class_exists('RegularLabs\Library\Protect'))
{
return true;
}
if (RL_Protect::isDisabledByUrl($extension_alias))
{
return true;
}
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::isRestrictedPage($hastags, $exclude_formats);
}
public static function isAdmin($block_login = false)
{
return class_exists('RegularLabs\Library\Document') &&
RL_Document::isAdmin($block_login);
}
public static function isEditPage()
{
return class_exists('RegularLabs\Library\Document') &&
RL_Document::isEditPage();
}
public static function isRestrictedComponent($restricted_components, $area
= 'component')
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::isRestrictedComponent($restricted_components, $area);
}
public static function isComponentInstalled($extension_alias)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::isComponentInstalled($extension_alias);
}
public static function isSystemPluginInstalled($extension_alias)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::isSystemPluginInstalled($extension_alias);
}
public static function getFormRegex($regex_format = false)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::getFormRegex($regex_format);
}
public static function protectFields(&$string, $search_strings = [])
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectFields($string, $search_strings);
}
public static function protectScripts(&$string)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectScripts($string);
}
public static function protectHtmlTags(&$string)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectHtmlTags($string);
}
public static function protectByRegex(&$string, $regex)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectByRegex($string, $regex);
}
public static function protectTags(&$string, $tags = [],
$include_closing_tags = true)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectTags($string, $tags, $include_closing_tags);
}
public static function unprotectTags(&$string, $tags = [],
$include_closing_tags = true)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::unprotectTags($string, $tags, $include_closing_tags);
}
public static function protectInString(&$string, $unprotected = [],
$protected = [])
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectInString($string, $unprotected, $protected);
}
public static function unprotectInString(&$string, $unprotected = [],
$protected = [])
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::unprotectInString($string, $unprotected, $protected);
}
public static function protectSourcerer(&$string)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectSourcerer($string);
}
public static function protectForm(&$string, $tags = [],
$include_closing_tags = true)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectForm($string, $tags, $include_closing_tags);
}
public static function unprotect(&$string)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::unprotect($string);
}
public static function convertProtectionToHtmlSafe(&$string)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::convertProtectionToHtmlSafe($string);
}
public static function unprotectHtmlSafe(&$string)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::unprotectHtmlSafe($string);
}
public static function protectString($string, $is_tag = false)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectString($string, $is_tag);
}
public static function unprotectString($string, $is_tag = false)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::unprotectString($string, $is_tag);
}
public static function protectTag($string)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectTag($string);
}
public static function protectArray($array, $is_tag = false)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::protectArray($array, $is_tag);
}
public static function unprotectArray($array, $is_tag = false)
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::unprotectArray($array, $is_tag);
}
public static function unprotectForm(&$string, $tags = [])
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::unprotectForm($string, $tags);
}
public static function removeInlineComments(&$string, $name)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::removeInlineComments($string, $name);
}
public static function removePluginTags(&$string, $tags,
$character_start = '{', $character_end = '{',
$keep_content = true)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::removePluginTags($string, $tags, $character_start,
$character_end, $keep_content);
}
public static function removeFromHtmlTagContent(&$string, $tags,
$include_closing_tags = true, $html_tags = ['title'])
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::removeFromHtmlTagContent($string, $tags, $include_closing_tags,
$html_tags);
}
public static function removeFromHtmlTagAttributes(&$string, $tags,
$attributes = 'ALL', $include_closing_tags = true)
{
class_exists('RegularLabs\Library\Protect') &&
RL_Protect::removeFromHtmlTagAttributes($string, $tags, $attributes,
$include_closing_tags);
}
public static function articlePassesSecurity(&$article,
$securtiy_levels = [])
{
return class_exists('RegularLabs\Library\Protect') &&
RL_Protect::articlePassesSecurity($article, $securtiy_levels);
}
public static function isJoomla3()
{
return true;
}
}
search.php000064400000013547151166122750006542 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/**
* BASE ON JOOMLA CORE FILE:
* /components/com_search/models/search.php
*/
/**
* @package Joomla.Site
* @subpackage com_search
*
* @copyright Copyright (C) 2005 - 2019 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\Factory as JFactory;
use Joomla\CMS\MVC\Model\BaseDatabaseModel as JModel;
use Joomla\CMS\Pagination\Pagination as JPagination;
use Joomla\CMS\Plugin\PluginHelper as JPluginHelper;
/**
* Search Component Search Model
*
* @since 1.5
*/
class SearchModelSearch extends JModel
{
/**
* Search data array
*
* @var array
*/
protected $_data = null;
/**
* Search total
*
* @var integer
*/
protected $_total = null;
/**
* Search areas
*
* @var integer
*/
protected $_areas = null;
/**
* Pagination object
*
* @var object
*/
protected $_pagination = null;
/**
* Constructor
*
* @since 1.5
*/
public function __construct()
{
parent::__construct();
// Get configuration
$app = JFactory::getApplication();
$config = JFactory::getConfig();
// Get the pagination request variables
$this->setState('limit',
$app->getUserStateFromRequest('com_search.limit',
'limit', $config->get('list_limit'),
'uint'));
$this->setState('limitstart',
$app->input->get('limitstart', 0, 'uint'));
// Get parameters.
$params = $app->getParams();
if ($params->get('searchphrase') == 1)
{
$searchphrase = 'any';
}
elseif ($params->get('searchphrase') == 2)
{
$searchphrase = 'exact';
}
else
{
$searchphrase = 'all';
}
// Set the search parameters
$keyword =
urldecode($app->input->getString('searchword'));
$match = $app->input->get('searchphrase',
$searchphrase, 'word');
$ordering = $app->input->get('ordering',
$params->get('ordering', 'newest'),
'word');
$this->setSearch($keyword, $match, $ordering);
// Set the search areas
$areas = $app->input->get('areas', null,
'array');
$this->setAreas($areas);
}
/**
* Method to set the search parameters
*
* @param string $keyword string search string
* @param string $match matching option, exact|any|all
* @param string $ordering option, newest|oldest|popular|alpha|category
*
* @return void
*
* @access public
*/
public function setSearch($keyword, $match = 'all', $ordering =
'newest')
{
if (isset($keyword))
{
$this->setState('origkeyword', $keyword);
if ($match !== 'exact')
{
$keyword = preg_replace('#\xE3\x80\x80#s', ' ',
$keyword);
}
$this->setState('keyword', $keyword);
}
if (isset($match))
{
$this->setState('match', $match);
}
if (isset($ordering))
{
$this->setState('ordering', $ordering);
}
}
/**
* Method to get weblink item data for the category
*
* @access public
* @return array
*/
public function getData()
{
// Lets load the content if it doesn't already exist
if (empty($this->_data))
{
$areas = $this->getAreas();
JPluginHelper::importPlugin('search');
$dispatcher = JEventDispatcher::getInstance();
$results = $dispatcher->trigger('onContentSearch', [
$this->getState('keyword'),
$this->getState('match'),
$this->getState('ordering'),
$areas['active'],
]
);
$rows = [];
foreach ($results as $result)
{
$rows = array_merge((array) $rows, (array) $result);
}
$this->_total = count($rows);
if ($this->getState('limit') > 0)
{
$this->_data = array_splice($rows,
$this->getState('limitstart'),
$this->getState('limit'));
}
else
{
$this->_data = $rows;
}
/* >>> ADDED: Run content plugins over results */
$params =
JFactory::getApplication()->getParams('com_content');
$params->set('rl_search', 1);
foreach ($this->_data as $item)
{
if (empty($item->text))
{
continue;
}
$dispatcher->trigger('onContentPrepare',
['com_search.search.article', &$item, &$params, 0]);
if (empty($item->title))
{
continue;
}
// strip html tags from title
$item->title = strip_tags($item->title);
}
/* <<< */
}
return $this->_data;
}
/**
* Method to get the total number of weblink items for the category
*
* @access public
*
* @return integer
*/
public function getTotal()
{
return $this->_total;
}
/**
* Method to set the search areas
*
* @param array $active areas
* @param array $search areas
*
* @return void
*
* @access public
*/
public function setAreas($active = [], $search = [])
{
$this->_areas['active'] = $active;
$this->_areas['search'] = $search;
}
/**
* Method to get a pagination object of the weblink items for the category
*
* @access public
* @return integer
*/
public function getPagination()
{
// Lets load the content if it doesn't already exist
if (empty($this->_pagination))
{
$this->_pagination = new JPagination($this->getTotal(),
$this->getState('limitstart'),
$this->getState('limit'));
}
return $this->_pagination;
}
/**
* Method to get the search areas
*
* @return int
*
* @since 1.5
*/
public function getAreas()
{
// Load the Category data
if (empty($this->_areas['search']))
{
$areas = [];
JPluginHelper::importPlugin('search');
$dispatcher = JEventDispatcher::getInstance();
$searchareas =
$dispatcher->trigger('onContentSearchAreas');
foreach ($searchareas as $area)
{
if (is_array($area))
{
$areas = array_merge($areas, $area);
}
}
$this->_areas['search'] = $areas;
}
return $this->_areas;
}
}
string.php000064400000000716151166122750006575 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
jimport('joomla.string.string');
abstract class RLString extends JString
{
}
tags.php000064400000012022151166122750006216 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Html as RL_Html;
use RegularLabs\Library\PluginTag as RL_PluginTag;
use RegularLabs\Library\RegEx as RL_RegEx;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLTags
{
static $protected_characters = [
'=' => '[[:EQUAL:]]',
'"' => '[[:QUOTE:]]',
',' => '[[:COMMA:]]',
'|' => '[[:BAR:]]',
':' => '[[:COLON:]]',
];
public static function getValuesFromString($string = '',
$main_key = 'title', $known_boolean_keys = [], $keep_escaped =
[','])
{
return RL_PluginTag::getAttributesFromString($string, $main_key,
$known_boolean_keys, $keep_escaped);
}
public static function protectSpecialChars(&$string)
{
RL_PluginTag::protectSpecialChars($string);
}
public static function unprotectSpecialChars(&$string,
$keep_escaped_chars = [])
{
RL_PluginTag::unprotectSpecialChars($string, $keep_escaped_chars);
}
public static function replaceKeyAliases(&$values, $key_aliases = [],
$handle_plurals = false)
{
RL_PluginTag::replaceKeyAliases($values, $key_aliases, $handle_plurals);
}
public static function convertOldSyntax(&$values, $known_boolean_keys
= [], $extra_key = 'class')
{
RL_PluginTag::convertOldSyntax($values, $known_boolean_keys, $extra_key);
}
public static function getRegexSpaces($modifier = '+')
{
return RL_PluginTag::getRegexSpaces($modifier);
}
public static function getRegexInsideTag()
{
return RL_PluginTag::getRegexInsideTag();
}
public static function getRegexSurroundingTagPre($elements =
['p', 'span'])
{
return RL_PluginTag::getRegexSurroundingTagPre($elements);
}
public static function getRegexSurroundingTagPost($elements =
['p', 'span'])
{
return RL_PluginTag::getRegexSurroundingTagPost($elements);
}
public static function getRegexTags($tags, $include_no_attributes = true,
$include_ending = true, $required_attributes = [])
{
return RL_PluginTag::getRegexTags($tags, $include_no_attributes,
$include_ending, $required_attributes);
}
public static function fixBrokenHtmlTags($string)
{
return RL_Html::fix($string);
}
public static function cleanSurroundingTags($tags, $elements =
['p', 'span'])
{
return RL_Html::cleanSurroundingTags($tags, $elements);
}
public static function fixSurroundingTags($tags)
{
return RL_Html::fixArray($tags);
}
public static function removeEmptyHtmlTagPairs($string, $elements =
['p', 'span'])
{
return RL_Html::removeEmptyTagPairs($string, $elements);
}
public static function getDivTags($start_tag = '', $end_tag =
'', $tag_start = '{', $tag_end = '}')
{
$tag_start = RL_RegEx::unquote($tag_start);
$tag_end = RL_RegEx::unquote($tag_end);
return RL_PluginTag::getDivTags($start_tag, $end_tag, $tag_start,
$tag_end);
}
public static function getTagValues($string = '', $keys =
['title'], $separator = '|', $equal = '=',
$limit = 0)
{
return RL_PluginTag::getAttributesFromStringOld($string, $keys,
$separator, $equal, $limit);
}
/* @Deprecated */
public static function setSurroundingTags($pre, $post, $tags = 0)
{
if ($tags == 0)
{
// tags that have a matching ending tag
$tags = [
'div', 'p', 'span', 'pre',
'a',
'h1', 'h2', 'h3', 'h4',
'h5', 'h6',
'strong', 'b', 'em', 'i',
'u', 'big', 'small', 'font',
// html 5 stuff
'header', 'nav', 'section',
'article', 'aside', 'footer',
'figure', 'figcaption', 'details',
'summary', 'mark', 'time',
];
}
$a = explode('<', $pre);
$b = explode('</', $post);
if (count($b) < 2 || count($a) < 2)
{
return [trim($pre), trim($post)];
}
$a = array_reverse($a);
$a_pre = array_pop($a);
$b_pre = array_shift($b);
$a_tags = $a;
foreach ($a_tags as $i => $a_tag)
{
$a[$i] = '<' . trim($a_tag);
$a_tags[$i] = RL_RegEx::replace('^([a-z0-9]+).*$',
'\1', trim($a_tag));
}
$b_tags = $b;
foreach ($b_tags as $i => $b_tag)
{
$b[$i] = '</' . trim($b_tag);
$b_tags[$i] = RL_RegEx::replace('^([a-z0-9]+).*$',
'\1', trim($b_tag));
}
foreach ($b_tags as $i => $b_tag)
{
if (empty($b_tag) || ! in_array($b_tag, $tags))
{
continue;
}
foreach ($a_tags as $j => $a_tag)
{
if ($b_tag != $a_tag)
{
continue;
}
$a_tags[$i] = '';
$b[$i] = trim(RL_RegEx::replace('^</' . $b_tag .
'.*?>', '', $b[$i]));
$a[$j] = trim(RL_RegEx::replace('^<' . $a_tag .
'.*?>', '', $a[$j]));
break;
}
}
foreach ($a_tags as $i => $tag)
{
if (empty($tag) || ! in_array($tag, $tags))
{
continue;
}
array_unshift($b, trim($a[$i]));
$a[$i] = '';
}
$a = array_reverse($a);
list($pre, $post) = [implode('', $a), implode('',
$b)];
return [trim($pre), trim($post)];
}
}
text.php000064400000011417151166122750006253 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Alias as RL_Alias;
use RegularLabs\Library\ArrayHelper as RL_Array;
use RegularLabs\Library\Date as RL_Date;
use RegularLabs\Library\Form as RL_Form;
use RegularLabs\Library\Html as RL_Html;
use RegularLabs\Library\HtmlTag as RL_HtmlTag;
use RegularLabs\Library\PluginTag as RL_PluginTag;
use RegularLabs\Library\RegEx as RL_RegEx;
use RegularLabs\Library\StringHelper as RL_String;
use RegularLabs\Library\Title as RL_Title;
use RegularLabs\Library\Uri as RL_Uri;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLText
{
/* Date functions */
public static function fixDate(&$date)
{
$date = RL_Date::fix($date);
}
public static function fixDateOffset(&$date)
{
RL_Date::applyTimezone($date);
}
public static function dateToDateFormat($dateFormat)
{
return RL_Date::strftimeToDateFormat($dateFormat);
}
public static function dateToStrftimeFormat($dateFormat)
{
return RL_Date::dateToStrftimeFormat($dateFormat);
}
/* String functions */
public static function html_entity_decoder($string, $quote_style =
ENT_QUOTES, $charset = 'UTF-8')
{
return RL_String::html_entity_decoder($string, $quote_style, $charset);
}
public static function stringContains($haystacks, $needles)
{
return RL_String::contains($haystacks, $needles);
}
public static function is_alphanumeric($string)
{
return RL_String::is_alphanumeric($string);
}
public static function splitString($string, $delimiters = [], $max_length
= 10000, $maximize_parts = true)
{
return RL_String::split($string, $delimiters, $max_length,
$maximize_parts);
}
public static function strReplaceOnce($search, $replace, $string)
{
return RL_String::replaceOnce($search, $replace, $string);
}
/* Array functions */
public static function toArray($data, $separator = '')
{
return RL_Array::toArray($data, $separator);
}
public static function createArray($data, $separator = ',')
{
return RL_Array::toArray($data, $separator, true);
}
/* RegEx functions */
public static function regexReplace($pattern, $replacement, $string)
{
return RL_RegEx::replace($pattern, $replacement, $string);
}
public static function pregQuote($string = '', $delimiter =
'#')
{
return RL_RegEx::quote($string, $delimiter);
}
public static function pregQuoteArray($array = [], $delimiter =
'#')
{
return RL_RegEx::quoteArray($array, $delimiter);
}
/* Title functions */
public static function cleanTitle($string, $strip_tags = false,
$strip_spaces = true)
{
return RL_Title::clean($string, $strip_tags, $strip_spaces);
}
public static function createUrlMatches($titles = [])
{
return RL_Title::getUrlMatches($titles);
}
/* Alias functions */
public static function createAlias($string)
{
return RL_Alias::get($string);
}
/* Uri functions */
public static function getURI($hash = '')
{
return RL_Uri::get($hash);
}
/* Plugin Tag functions */
public static function getTagRegex($tags, $include_no_attributes = true,
$include_ending = true, $required_attributes = [])
{
return RL_PluginTag::getRegexTags($tags, $include_no_attributes,
$include_ending, $required_attributes);
}
/* HTML functions */
public static function getBody($html)
{
return RL_Html::getBody($html);
}
public static function getContentContainingSearches($string,
$start_searches = [], $end_searches = [], $start_offset = 1000, $end_offset
= null)
{
return RL_Html::getContentContainingSearches($string, $start_searches,
$end_searches, $start_offset, $end_offset);
}
public static function convertWysiwygToPlainText($string)
{
return RL_Html::convertWysiwygToPlainText($string);
}
public static function combinePTags(&$string)
{
RL_Html::combinePTags($string);
}
/* HTML Tag functions */
public static function combineTags($tag1, $tag2)
{
return RL_HtmlTag::combine($tag1, $tag2);
}
public static function getAttribute($key, $string)
{
return RL_HtmlTag::getAttributeValue($key, $string);
}
public static function getAttributes($string)
{
return RL_HtmlTag::getAttributes($string);
}
public static function combineAttributes($string1, $string2)
{
return RL_HtmlTag::combineAttributes($string1, $string2);
}
/* Form functions */
public static function prepareSelectItem($string, $published = 1, $type =
'', $remove_first = 0)
{
return RL_Form::prepareSelectItem($string, $published, $type,
$remove_first);
}
}
versions.php000064400000002413151166122750007133 0ustar00<?php
/**
* @package Regular Labs Library
* @version 21.2.19653
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2021 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
/* @DEPRECATED */
defined('_JEXEC') or die;
use RegularLabs\Library\Version as RL_Version;
if (is_file(JPATH_LIBRARIES . '/regularlabs/autoload.php'))
{
require_once JPATH_LIBRARIES . '/regularlabs/autoload.php';
}
class RLVersions
{
public static function getXMLVersion($alias, $urlformat = false, $type =
'component', $folder = 'system')
{
return ! class_exists('RegularLabs\Library\Version') ?
'' : RL_Version::get($alias, $type, $folder);
}
public static function getPluginXMLVersion($alias, $folder =
'system')
{
return ! class_exists('RegularLabs\Library\Version') ?
'' : RL_Version::getPluginVersion($alias, $folder);
}
public static function render($alias)
{
return ! class_exists('RegularLabs\Library\Version') ?
'' : RL_Version::getMessage($alias);
}
public static function getFooter($name, $copyright = 1)
{
return ! class_exists('RegularLabs\Library\Version') ?
'' : RL_Version::getFooter($name, $copyright);
}
}
html/utility.php000064400000005212151166710710007731 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;
/**
* Jea Utility helper
*
* @package Joomla.Site
* @subpackage com_jea
*
* @since 2.0
*/
abstract class JHtmlUtility
{
/**
* @var Joomla\Registry\Registry
*/
protected static $params = null;
/**
* Format price following the component configuration.
* If price is empty, return a default string value.
*
* @param float|int $price The price as number
* @param string $default Default value if price equals 0
*
* @return string
*/
public static function formatPrice($price = 0, $default = '')
{
$params = self::getParams();
if (! empty($price))
{
$currency_symbol = $params->get('currency_symbol',
'€');
$price = self::formaNumber($price);
// Is currency symbol before or after price ?
if ($params->get('symbol_position', 1))
{
$price = $price . ' ' . $currency_symbol;
}
else
{
$price = $currency_symbol . ' ' . $price;
}
return $price;
}
else
{
return $default;
}
}
/**
* Format surface following the component configuration.
* If surface is empty, return a default string value.
*
* @param float|int $surface The surface as number
* @param string $default Default value if surface equals 0
*
* @return string
*/
public static function formatSurface($surface = 0, $default =
'')
{
$params = self::getParams();
if (!empty($surface))
{
$surfaceMeasure = $params->get('surface_measure',
'm²');
$surface = self::formaNumber($surface);
return $surface . ' ' . $surfaceMeasure;
}
return $default;
}
/**
* Format number following the component configuration.
*
* @param float|int $number The number to format
*
* @return string
*/
public static function formaNumber($number = O)
{
$params = self::getParams();
$number = (float) $number;
$decimal_separator = $params->get('decimals_separator',
',');
$thousands_separator = $params->get('thousands_separator',
' ');
$decimals = (int) $params->get('decimals_number',
'0');
return number_format($number, $decimals, $decimal_separator,
$thousands_separator);
}
/**
* Get JEA params
*
* @return Joomla\Registry\Registry
*/
protected static function getParams()
{
if (self::$params == null)
{
self::$params = JComponentHelper::getParams('com_jea');
}
return self::$params;
}
}
html/amenities.php000064400000005776151166710710010223 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;
/**
* Jea Amenities HTML helper
*
* @package Joomla.Site
* @subpackage com_jea
*
* @since 2.0
*/
abstract class JHtmlAmenities
{
/**
* @var stdClass[]
*/
protected static $amenities = null;
/**
* Method to get an HTML list of amenities
*
* @param mixed $value string or array of amenities ids
* @param string $format The wanted format (ol, li, raw (default))
*
* @return string HTML for the list.
*/
static public function bindList($value = 0, $format = 'raw')
{
if (is_string($value) && !empty($value))
{
$ids = explode('-', $value);
}
elseif (empty($value))
{
$ids = array();
}
else
{
$ids = ArrayHelper::toInteger($value);
}
$html = '';
$amenities = self::getAmenities();
$items = array();
foreach ($amenities as $row)
{
if (in_array($row->id, $ids))
{
if ($format == 'ul')
{
$items[] = "<li>{$row->value}</li>\n";
}
else
{
$items[] = $row->value;
}
}
}
if ($format == 'ul')
{
$html = "<ul>\n" . implode("\n", $items) .
"</ul>\n";
}
else
{
$html = implode(', ', $items);
}
return $html;
}
/**
* Return HTML list of amenities as checkboxes
*
* @param array $values The checkboxes values
* @param string $name The attribute name for the checkboxes
* @param string $idSuffix An optional ID suffix for the checkboxes
*
* @return string Html list
*/
static public function checkboxes($values = array(), $name =
'amenities', $idSuffix = '')
{
$amenities = self::getAmenities();
$values = (array) $values;
$html = '';
if (!empty($amenities))
{
$html .= "<ul>\n";
foreach ($amenities as $row)
{
$checked = '';
$id = 'amenity' . $row->id . $idSuffix;
if (in_array($row->id, $values))
{
$checked = 'checked="checked"';
}
$html .= '<li><input name="' . $name .
'[]" id="' . $id . '"
type="checkbox" value="' . $row->id . '"
' . $checked . ' /> '
. '<label for="' . $id . '">' .
$row->value . '</label></li>' . "\n";
}
$html .= "</ul>";
}
return $html;
}
/**
* Get Jea amenities from database
*
* @return array An array of amenity row objects
*/
static public function getAmenities()
{
if (self::$amenities === null)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('a.id , a.value');
$query->from('#__jea_amenities AS a');
$query->where('a.language in (' .
$db->quote(JFactory::getLanguage()->getTag()) . ',' .
$db->quote('*') . ')');
$query->order('a.ordering');
$db->setQuery($query);
self::$amenities = $db->loadObjectList();
}
return self::$amenities;
}
}
html/users.php000064400000010624151167156210007372 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;
/**
* Users Html Helper
*
* @since 1.6
*/
abstract class JHtmlUsers
{
/**
* Get the sanitized value
*
* @param mixed $value Value of the field
*
* @return mixed String/void
*
* @since 1.6
*/
public static function value($value)
{
if (is_string($value))
{
$value = trim($value);
}
if (empty($value))
{
return JText::_('COM_USERS_PROFILE_VALUE_NOT_FOUND');
}
elseif (!is_array($value))
{
return htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
}
}
/**
* Get the space symbol
*
* @param mixed $value Value of the field
*
* @return string
*
* @since 1.6
*/
public static function spacer($value)
{
return '';
}
/**
* Get the sanitized helpsite link
*
* @param mixed $value Value of the field
*
* @return mixed String/void
*
* @since 1.6
*/
public static function helpsite($value)
{
if (empty($value))
{
return static::value($value);
}
$text = $value;
if ($xml = simplexml_load_file(JPATH_ADMINISTRATOR .
'/help/helpsites.xml'))
{
foreach ($xml->sites->site as $site)
{
if ((string) $site->attributes()->url == $value)
{
$text = (string) $site;
break;
}
}
}
$value = htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
if (strpos($value, 'http') === 0)
{
return '<a href="' . $value . '">' .
$text . '</a>';
}
return '<a href="http://' . $value .
'">' . $text . '</a>';
}
/**
* Get the sanitized template style
*
* @param mixed $value Value of the field
*
* @return mixed String/void
*
* @since 1.6
*/
public static function templatestyle($value)
{
if (empty($value))
{
return static::value($value);
}
else
{
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('title')
->from('#__template_styles')
->where('id = ' . $db->quote($value));
$db->setQuery($query);
$title = $db->loadResult();
if ($title)
{
return htmlspecialchars($title, ENT_COMPAT, 'UTF-8');
}
else
{
return static::value('');
}
}
}
/**
* Get the sanitized language
*
* @param mixed $value Value of the field
*
* @return mixed String/void
*
* @since 1.6
*/
public static function admin_language($value)
{
if (empty($value))
{
return static::value($value);
}
else
{
$file = JLanguageHelper::getLanguagePath(JPATH_ADMINISTRATOR, $value) .
'/' . $value . '.xml';
$result = null;
if (is_file($file))
{
$result = JLanguageHelper::parseXMLLanguageFile($file);
}
if ($result)
{
return htmlspecialchars($result['name'], ENT_COMPAT,
'UTF-8');
}
else
{
return static::value('');
}
}
}
/**
* Get the sanitized language
*
* @param mixed $value Value of the field
*
* @return mixed String/void
*
* @since 1.6
*/
public static function language($value)
{
if (empty($value))
{
return static::value($value);
}
else
{
$file = JLanguageHelper::getLanguagePath(JPATH_SITE, $value) .
'/' . $value . '.xml';
$result = null;
if (is_file($file))
{
$result = JLanguageHelper::parseXMLLanguageFile($file);
}
if ($result)
{
return htmlspecialchars($result['name'], ENT_COMPAT,
'UTF-8');
}
else
{
return static::value('');
}
}
}
/**
* Get the sanitized editor name
*
* @param mixed $value Value of the field
*
* @return mixed String/void
*
* @since 1.6
*/
public static function editor($value)
{
if (empty($value))
{
return static::value($value);
}
else
{
$db = JFactory::getDbo();
$lang = JFactory::getLanguage();
$query = $db->getQuery(true)
->select('name')
->from('#__extensions')
->where('element = ' . $db->quote($value))
->where('folder = ' . $db->quote('editors'));
$db->setQuery($query);
$title = $db->loadResult();
if ($title)
{
$lang->load("plg_editors_$value.sys", JPATH_ADMINISTRATOR,
null, false, true)
|| $lang->load("plg_editors_$value.sys", JPATH_PLUGINS .
'/editors/' . $value, null, false, true);
$lang->load($title . '.sys');
return JText::_($title);
}
else
{
return static::value('');
}
}
}
}
legacyrouter.php000064400000013710151167156210007771 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;
/**
* Legacy routing rules class from com_users
*
* @since 3.6
* @deprecated 4.0
*/
class UsersRouterRulesLegacy implements JComponentRouterRulesInterface
{
/**
* Constructor for this legacy router
*
* @param JComponentRouterAdvanced $router The router this rule
belongs to
*
* @since 3.6
* @deprecated 4.0
*/
public function __construct($router)
{
$this->router = $router;
}
/**
* Preprocess the route for the com_users component
*
* @param array &$query An array of URL arguments
*
* @return void
*
* @since 3.6
* @deprecated 4.0
*/
public function preprocess(&$query)
{
}
/**
* Build the route for the com_users component
*
* @param array &$query An array of URL arguments
* @param array &$segments The URL arguments to use to assemble
the subsequent URL.
*
* @return void
*
* @since 3.6
* @deprecated 4.0
*/
public function build(&$query, &$segments)
{
// Declare static variables.
static $items;
static $default;
static $registration;
static $profile;
static $login;
static $remind;
static $resend;
static $reset;
// Get the relevant menu items if not loaded.
if (empty($items))
{
// Get all relevant menu items.
$items = $this->router->menu->getItems('component',
'com_users');
// Build an array of serialized query strings to menu item id mappings.
foreach ($items as $item)
{
if (empty($item->query['view']))
{
continue;
}
// Check to see if we have found the resend menu item.
if (empty($resend) && $item->query['view'] ===
'resend')
{
$resend = $item->id;
continue;
}
// Check to see if we have found the reset menu item.
if (empty($reset) && $item->query['view'] ===
'reset')
{
$reset = $item->id;
continue;
}
// Check to see if we have found the remind menu item.
if (empty($remind) && $item->query['view'] ===
'remind')
{
$remind = $item->id;
continue;
}
// Check to see if we have found the login menu item.
if (empty($login) && $item->query['view'] ===
'login' && (empty($item->query['layout']) ||
$item->query['layout'] === 'default'))
{
$login = $item->id;
continue;
}
// Check to see if we have found the registration menu item.
if (empty($registration) && $item->query['view']
=== 'registration')
{
$registration = $item->id;
continue;
}
// Check to see if we have found the profile menu item.
if (empty($profile) && $item->query['view'] ===
'profile')
{
$profile = $item->id;
}
}
// Set the default menu item to use for com_users if possible.
if ($profile)
{
$default = $profile;
}
elseif ($registration)
{
$default = $registration;
}
elseif ($login)
{
$default = $login;
}
}
if (!empty($query['view']))
{
switch ($query['view'])
{
case 'reset':
if ($query['Itemid'] = $reset)
{
unset($query['view']);
}
else
{
$query['Itemid'] = $default;
}
break;
case 'resend':
if ($query['Itemid'] = $resend)
{
unset($query['view']);
}
else
{
$query['Itemid'] = $default;
}
break;
case 'remind':
if ($query['Itemid'] = $remind)
{
unset($query['view']);
}
else
{
$query['Itemid'] = $default;
}
break;
case 'login':
if ($query['Itemid'] = $login)
{
unset($query['view']);
}
else
{
$query['Itemid'] = $default;
}
break;
case 'registration':
if ($query['Itemid'] = $registration)
{
unset($query['view']);
}
else
{
$query['Itemid'] = $default;
}
break;
default:
case 'profile':
if (!empty($query['view']))
{
$segments[] = $query['view'];
}
unset($query['view']);
if ($query['Itemid'] = $profile)
{
unset($query['view']);
}
else
{
$query['Itemid'] = $default;
}
// Only append the user id if not "me".
$user = JFactory::getUser();
if (!empty($query['user_id']) &&
($query['user_id'] != $user->id))
{
$segments[] = $query['user_id'];
}
unset($query['user_id']);
break;
}
}
$total = count($segments);
for ($i = 0; $i < $total; $i++)
{
$segments[$i] = str_replace(':', '-',
$segments[$i]);
}
}
/**
* Parse the segments of a URL.
*
* @param array &$segments The segments of the URL to parse.
* @param array &$vars The URL attributes to be used by the
application.
*
* @return void
*
* @since 3.6
* @deprecated 4.0
*/
public function parse(&$segments, &$vars)
{
$total = count($segments);
for ($i = 0; $i < $total; $i++)
{
$segments[$i] = preg_replace('/-/', ':',
$segments[$i], 1);
}
// Only run routine if there are segments to parse.
if (count($segments) < 1)
{
return;
}
// Get the package from the route segments.
$userId = array_pop($segments);
if (!is_numeric($userId))
{
$vars['view'] = 'profile';
return;
}
if (is_numeric($userId))
{
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('id') . ' = ' . (int)
$userId);
$db->setQuery($query);
$userId = $db->loadResult();
}
// Set the package id if present.
if ($userId)
{
// Set the package id.
$vars['user_id'] = (int) $userId;
// Set the view to package if not already set.
if (empty($vars['view']))
{
$vars['view'] = 'profile';
}
}
else
{
JError::raiseError(404,
JText::_('JGLOBAL_RESOURCE_NOT_FOUND'));
}
}
}
addon-helper.php000064400000021324151200771650007625 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Router\Route;
/** No direct access. */
defined('_JEXEC') or die('Restricted access');
/**
* The helper class for migrating from 3.x to 4.x
*
* @since 4.0.0
*/
final class AddonHelper
{
public static $deviceList = ["xl", "lg",
"md", "sm", "xs"];
/**
* Generate the media query with respect to the device
*
* @param string $device
*
* @return string
* @since 4.0.0
*/
public static function mediaQuery(string $device): string
{
$MEDIA_QUERY_MAP = [
'xl' => '@media (max-width: 1399.98px) {',
'lg' => '@media (max-width: 1199.98px) {',
'md' => '@media (max-width: 991.98px) {',
'sm' => '@media (max-width: 767.98px) {',
'xs' => '@media (max-width: 575.98px) {',
];
return $MEDIA_QUERY_MAP[$device];
}
/**
* Initialize the device object with help of the device list.
*
* @param string $type The type value. Accepted values are
'string', 'number', 'boolean'
*
* @return \stdClass
* @since 4.0.0
*/
public static function initDeviceObject(string $type =
'string'): \stdClass
{
$DEVICE_MAP = ['string' => '', 'number'
=> 0, 'boolean' => false];
$deviceObject = new \stdClass;
foreach (self::$deviceList as $device)
{
$deviceObject->$device = $DEVICE_MAP[$type];
}
return $deviceObject;
}
/**
* Generate Multiple device wise object from settings object.
*
* @param \stdClass $settings The settings object.
* @param string $prop The settings property.
* @param string $cssProp The CSS property.
* @param string $device The device value.
* @param boolean $important If the CSS property need to append the
!important keyword.
* @param string $unit The unit of the CSS property.
*
* @return \stdClass
* @since 4.0.0
*/
public static function generateMultiDeviceObject($settings, $prop,
$cssProp, $device, $important = false, $unit = "px")
{
$data = self::initDeviceObject();
if (!isset($settings->$prop)) return $data;
if (\is_string($cssProp))
{
$cssProp = [$cssProp];
}
$value = $settings->$prop;
if (empty($unit))
{
$unit = '';
}
else
{
if (!empty($value->unit))
{
$unit = $value->unit;
}
}
if (\is_object($value))
{
foreach ($data as $key => $value)
{
if (isset($settings->$prop->$key))
{
if (\is_object($settings->$prop->$key))
{
$_value = $settings->$prop->$key->value;
if (preg_replace("@\s+@", '', $_value) !==
'')
{
$_unit = $settings->$prop->$key->unit;
foreach ($cssProp as $css)
{
$data->$key = strpos($css, '%s') !== false
? \sprintf($css, $_value)
: $css . ': ' . ($_value ?? '');
$data->$key .= $_unit ?? '';
$data->$key .= $important ? ' !important;' :
';';
}
}
}
else
{
if (preg_replace("@\s+@", '',
$settings->$prop->$key) !== '')
{
foreach ($cssProp as $css)
{
$data->$key .= strpos($css, '%s') !== false
? \sprintf($css, $settings->$prop->$key)
: $css . ': ' . ($settings->$prop->$key ??
'');
$data->$key .= $unit ?? '';
$data->$key .= $important ? ' !important;' :
';';
}
}
}
}
}
}
else
{
if (isset($settings->$prop))
{
if (preg_replace("@\s+@", '', $settings->$prop)
!== '')
{
foreach ($cssProp as $css)
{
$data->$device .= strpos($css, '%s') !== false
? \sprintf($css, $settings->$prop)
: $css . ': ' . ($settings->$prop ?? '');
$data->$device .= $unit;
$data->$device .= $important ? ' !important;' :
';';
}
}
}
}
return $data;
}
/**
* Generate Spacing object from settings object.
*
* @param \stdClass $settings The settings object.
* @param string $type The spacing type, i.e. padding or margin
* @param string $device The device.
*
* @return \stdClass
* @since 4.0.0
*/
public static function generateSpacingObject($settings, $prop, $cssProp,
$device)
{
$object = self::initDeviceObject();
$positions = ["top", "right", "bottom",
"left"];
$borderRadiusPositions = ["top-left", "top-right",
"bottom-right", "bottom-left"];
if (\is_string($cssProp))
{
$cssProp = [$cssProp];
}
$value = $settings->$prop;
if (!isset($settings->$prop) || empty($settings->$prop)) return
$object;
if (\is_object($settings->$prop))
{
foreach ($object as $key => $_)
{
if (isset($settings->$prop->$key))
{
$value = (string) $settings->$prop->$key;
$value = \preg_replace("@\s+@", ' ', $value);
$valueArray = \ctype_space((string)$value) || $value === ''
? [] : explode(' ', $value);
if (!empty($valueArray))
{
$object->$key = implode(
"\r\n",
array_map(function ($x, $i) use ($cssProp, $positions,
$borderRadiusPositions)
{
$str = '';
foreach ($cssProp as $attr)
{
$x = strpos($x, '%s') !== false ? \sprintf($attr, $x) :
$x;
if ($attr === "border-radius")
{
$attr = explode('-', $attr);
$str .= isset($x) && !\ctype_space((string)$x) &&
!empty((string) $x) ? $attr[0] . '-' . $borderRadiusPositions[$i]
. '-' . $attr[1] . ': ' . $x . ';' :
'';
}
else
{
$str .= isset($x) && !\ctype_space((string) $x)
&& !empty((string) $x) ? $attr . '-' . $positions[$i] .
': ' . $x . ';' : '';
}
}
return $str;
}, $valueArray, array_keys($valueArray))
);
}
}
}
}
else
{
$value = isset($settings->$prop) ? (string) $settings->$prop :
'';
$value = \preg_replace("@\s+@", ' ', $value);
$valueArray = \ctype_space((string)$value) || $value === '' ?
[] : explode(' ', $value);
$object->$device = implode(
"\r\n",
array_map(function ($x, $i) use ($cssProp, $positions,
$borderRadiusPositions)
{
$str = '';
foreach ($cssProp as $attr)
{
$x = strpos($x, '%s') !== false ? \sprintf($attr, $x) : $x;
if ($attr === "border-radius")
{
$attr = explode('-', $attr);
$str .= isset($x) ? $attr[0] . '-' .
$borderRadiusPositions[$i] . '-' . $attr[1] . ': ' . $x
. ';' : '';
}
else
{
$str .= isset($x) ? $attr . '-' . $positions[$i] . ':
' . $x . ';' : '';
}
}
return $str;
}, $valueArray, array_keys($valueArray))
);
}
return $object;
}
/**
* Convert new link form old link.
*
* @param \stdClass $settings The settings object.
* @param string $prop The settings property.
* @param array $fallback The fallback settings property.
*
* @return array
* @since 4.0.0
*/
public static function parseLink($settings, $prop, $fallback = [])
{
$hasFallback = !empty($fallback) && !isset($settings->$prop);
if ($hasFallback)
{
$url = array_key_exists('url', $fallback) ?
$fallback['url'] : '';
$newTab = array_key_exists('new_tab', $fallback) ?
$fallback['new_tab'] : '';
$nofollow = array_key_exists('nofollow', $fallback) ?
$fallback['nofollow'] : '';
$noreferrer = array_key_exists('noreferrer', $fallback) ?
$fallback['noreferrer'] : '';
$noopener = array_key_exists('noopener', $fallback) ?
$fallback['noopener'] : '';
$settings->$prop = new \stdClass;
$settings->$prop->url = isset($settings->$url) &&
\is_string($settings->$url) ? $settings->$url : '';
$settings->$prop->new_tab = $settings->$newTab ?? 0;
$settings->$prop->nofollow = $settings->$nofollow ?? 0;
$settings->$prop->noreferrer = $settings->$noreferrer ?? 0;
$settings->$prop->noopener = $settings->$noopener ?? 0;
$settings->$prop->type = 'url';
}
if (empty($settings->$prop)) return ['', ''];
$link = $settings->$prop;
if (\is_string($link))
{
return [$link, ''];
}
$url = '';
$target = '';
$rel = '';
if (!empty($link->type))
{
switch ($link->type)
{
case 'menu':
!empty($link->menu) ? $url = Route::_($link->menu) : $url =
'';
break;
case 'page':
!empty($link->page) ? $url = Uri::root(true) .
'/index.php?option=com_sppagebuilder&view=page&id=' .
$link->page : $url = '';
break;
case 'url':
$url = $link->url;
break;
default:
$url = '';
$target = '';
break;
}
}
if (!empty($link->new_tab))
{
$target .= 'target="_blank"';
}
if (!empty($link->nofollow))
{
$rel = "nofollow";
}
if (!empty($link->noreferrer))
{
$rel .= " noreferrer";
}
if (!empty($link->noopener))
{
$rel .= " noopener";
}
$target .= !empty($rel) ? ' rel="' . trim($rel) .
'"' : '';
return [$url, $target];
}
}
ajax.php000064400000015221151200771650006205 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Filesystem\Folder;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Http\Http;
$cParams = ComponentHelper::getParams('com_sppagebuilder');
$app = Factory::getApplication();
$input = $app->input;
$http = new Http;
// Load Page Template List
if ($action === 'pre-page-list')
{
$cache_path = JPATH_CACHE . '/sppagebuilder';
$cache_file = $cache_path . '/templates.json';
$output = array('status' => false, 'data' =>
'Templates not found.');
$templates = array(); // All pre-defined templates list
$templatesData = '';
if (!Folder::exists($cache_path))
{
Folder::create($cache_path, 0755);
}
if (File::exists($cache_file) && (filemtime($cache_file) >
(time() - (24 * 60 * 60))))
{
$templatesData = file_get_contents($cache_file);
}
else
{
$templateApi =
'https://www.joomshaper.com/index.php?option=com_layouts&view=templates&layout=json&support=4beyond';
$templatesResponse = $http->get($templateApi);
$templatesData = $templatesResponse->body;
if ($templatesResponse->code !== 200)
{
$output = ['status' => false, 'data' =>
$templatesData->error->message];
}
if (!empty($templatesData))
{
File::write($cache_file, $templatesData);
}
}
if (!empty($templatesData))
{
$templates = json_decode($templatesData);
$pages = [];
foreach ($templates as $template)
{
if (!empty($template->templates))
{
foreach ($template->templates as $item)
{
if (!empty($item->layouts))
{
foreach ($item->layouts as $layout)
{
$key = strtolower($layout->title);
$pages[$key] = (object) [
'label' => $layout->title,
'value' => $key
];
}
}
}
}
}
if (!empty($templates))
{
$response = [
'status' => true,
'data' => [
'pages' => array_values($pages),
'layouts' => $templates
]
];
echo json_encode($response);
die();
}
}
echo json_encode($output);
die();
}
// Load Page Template List
if ($action === 'get-pre-page-data')
{
$layout_id = $input->post->get('layout_id', '',
'NUMBER');
$output = array('status' => false, 'data' =>
'Page not found.');
$args = '&email=' .
$cParams->get('joomshaper_email') . '&api_key='
. $cParams->get('joomshaper_license_key');
$pageApi =
'https://www.joomshaper.com/index.php?option=com_layouts&task=template.download&support=4beyond&id='
. $layout_id . $args;
$pageResponse = $http->get($pageApi);
$pageData = $pageResponse->body;
if ($pageResponse->code !== 200)
{
$output = ['status' => false, 'data' =>
$pageData->error->message];
}
if (!empty($pageData))
{
$pageData = json_decode($pageData);
if (isset($pageData->status) && $pageData->status)
{
$output['status'] = true;
$output['data'] = $pageData->content;
echo json_encode($output);
die();
}
elseif (isset($pageData->authorised))
{
$output['status'] = false;
$output['data'] = $pageData->authorised;
echo json_encode($output);
die();
}
}
echo json_encode($output);
die();
}
if ($action === 'pre-section-list')
{
$cache_path = JPATH_CACHE . '/sppagebuilder';
$cache_file = $cache_path . '/sections.json';
$output = array('status' => false, 'data' =>
'Sections not found.');
$sections = array(); // All pre-defined templates list
$sectionsData = '';
if (!Folder::exists($cache_path))
{
Folder::create($cache_path, 0755);
}
if (File::exists($cache_file) && (filemtime($cache_file) >
(time() - (24 * 60 * 60))))
{
$sectionsData = file_get_contents($cache_file);
}
else
{
$args = '&email=' .
$cParams->get('joomshaper_email') . '&api_key='
. $cParams->get('joomshaper_license_key');
$sectionApi =
'https://www.joomshaper.com/index.php?option=com_layouts&task=block.list&support=4beyond'
. $args;
$sectionResponse = $http->get($sectionApi);
$sectionsData = $sectionResponse->body;
if ($sectionResponse->code !== 200)
{
$output = ['status' => false, 'data' =>
$sectionsData->error->message];
}
if (!empty($sectionsData))
{
File::write($cache_file, $sectionsData);
}
}
if (!empty($sectionsData))
{
$sections = json_decode($sectionsData);
/** Sanitize the blocks data before sending. */
if (!empty($sections->blocks))
{
foreach ($sections->blocks as $i => &$groups)
{
if (!empty($groups->blocks))
{
foreach ($groups->blocks as $j => &$block)
{
if (!empty($block->json))
{
$content = json_decode($block->json);
if (\is_object($content))
{
$content = json_encode([$content]);
}
elseif (\is_array($content))
{
$content = json_encode($content);
}
$json = SppagebuilderHelperSite::sanitize($content);
// $parse = json_decode($json);
// if (\is_array($parse) && !empty($parse))
// {
// $json = json_encode($parse[0]);
// }
$block->json = $json;
}
}
unset($block);
}
}
unset($groups);
}
if ((is_array($sections) && count($sections)) ||
is_object($sections))
{
$output['status'] = true;
$output['data'] = $sections;
echo json_encode($output);
die();
}
}
echo json_encode($output);
die();
}
// Load page from uploaded page
if ($action === 'upload-page')
{
if (isset($_FILES['page']) &&
$_FILES['page']['error'] === 0)
{
$file_name = $_FILES['page']['name'];
$file_extension = substr($file_name, -5);
$file_extension_lower = strtolower($file_extension);
if ($file_extension_lower === '.json')
{
$content =
file_get_contents($_FILES['page']['tmp_name']);
$importingContent = (object)['template' => '',
'css' => ''];
if (!empty($content))
{
$parsedContent = json_decode($content);
if (!isset($parsedContent->template))
{
$importingContent->template = json_decode($content);
}
else
{
$importingContent = $parsedContent;
}
}
if (!empty($importingContent))
{
require_once JPATH_COMPONENT_SITE .
'/builder/classes/addon.php';
$content =
ApplicationHelper::sanitizePageText(json_encode($importingContent->template));
$content = json_encode($content);
/** Sanitize the old data with new data format. */
$importingContent->template =
SppagebuilderHelperSite::sanitizeImportJSON($content);
echo json_encode(array('status' => true, 'data'
=> $importingContent));
die;
}
}
}
echo json_encode(array('status' => false, 'data'
=> 'Something wrong there.'));
die;
}
articles.php000064400000037017151200771650007077 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined ('_JEXEC') or die ('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Access\Access;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Helper\TagsHelper;
use Joomla\Utilities\ArrayHelper;
if(!class_exists('ContentHelperRoute')) require_once (JPATH_SITE
. '/components/com_content/helpers/route.php');
abstract class SppagebuilderHelperArticles
{
public static function getArticles( $count = 5, $ordering =
'latest', $catid = '', $include_subcategories = true,
$post_format = '', $tagids = array() ) {
$authorised =
Access::getAuthorisedViewLevels(Factory::getUser()->get('id'));
$app = Factory::getApplication();
$db = Factory::getDbo();
$nullDate = $db->quote($db->getNullDate());
$nowDate = $db->quote(Factory::getDate()->toSql());
$query = $db->getQuery(true);
$query
->select('a.*')
->from($db->quoteName('#__content', 'a'))
->select($db->quoteName('b.alias',
'category_alias'))
->select($db->quoteName('b.title', 'category'))
->join('LEFT', $db->quoteName('#__categories',
'b') . ' ON (' . $db->quoteName('a.catid')
. ' = ' . $db->quoteName('b.id') . ')')
->where($db->quoteName('b.extension') . ' = ' .
$db->quote('com_content'));
if($post_format) {
$query->where('('.$db->quoteName('a.attribs')
. ' LIKE ' .
$db->quote('%"post_format":"'. $post_format
.'"%') . ' OR ' .
$db->quoteName('a.attribs') . ' LIKE ' .
$db->quote('%"helix_ultimate_article_format":"'.
$post_format .'"%').')');
}
$query->where($db->quoteName('a.state') . ' = '
. $db->quote(1));
// Category filter
if (!is_array($catid))
{
$catid = [$catid];
}
if (!empty($catid))
{
$categories = self::getCategories($catid, $include_subcategories );
$categories = array_filter(array_merge($categories, $catid));
$query->where($db->quoteName('a.catid')." IN
(" . implode( ',', $categories ) . ")");
}
// tags filter
if (is_array($tagids) && count($tagids)) {
$tagId = implode(',', ArrayHelper::toInteger($tagids));
if ($tagId) {
$subQuery = $db->getQuery(true)
->select('DISTINCT content_item_id')
->from($db->quoteName('#__contentitem_tag_map'))
->where('tag_id IN (' . $tagId . ')')
->where('type_alias = ' .
$db->quote('com_content.article'));
$query->innerJoin('(' . (string) $subQuery . ') AS
tagmap ON tagmap.content_item_id = a.id');
}
}
// publishing
if ( JVERSION < 4)
{
$query->where('(a.publish_up = ' . $nullDate . ' OR
a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR
a.publish_down >= ' . $nowDate . ')');
}
else
{
$nowDate = Factory::getDate()->toSql();
$query->extendWhere(
'AND',
[
$db->quoteName('a.publish_up') . ' IS NULL',
$db->quoteName('a.publish_up') . ' <=
:publishUp',
],
'OR'
)->extendWhere(
'AND',
[
$db->quoteName('a.publish_down') . ' IS NULL',
$db->quoteName('a.publish_down') . ' >=
:publishDown',
],
'OR'
)->bind([':publishUp', ':publishDown'],
$nowDate);
}
// has order by
if ($ordering == 'hits') {
$query->order($db->quoteName('a.hits') . '
DESC');
} elseif($ordering == 'featured') {
$query->where($db->quoteName('a.featured') . ' =
' . $db->quote(1));
$query->order($db->quoteName('a.publish_up') . '
DESC');
} elseif($ordering == 'oldest') {
$query->order($db->quoteName('a.publish_up') . '
ASC');
} elseif($ordering == 'alphabet_asc') {
$query->order($db->quoteName('a.title') . '
ASC');
} elseif($ordering == 'alphabet_desc') {
$query->order($db->quoteName('a.title') . '
DESC');
} elseif($ordering == 'random') {
$query->order($query->Rand());
} else {
$query->order($db->quoteName('a.publish_up') . '
DESC');
}
// Language filter
if ($app->isClient('site') &&
$app->getLanguageFilter()) {
$query->where('a.language IN (' .
$db->Quote(Factory::getLanguage()->getTag()) . ',' .
$db->Quote('*') . ')');
}
// continue query
$query->where($db->quoteName('a.access')." IN
(" . implode( ',', $authorised ) . ")");
$query->order($db->quoteName('a.created') . '
DESC')
->setLimit($count);
$db->setQuery($query);
$items = $db->loadObjectList();
foreach ($items as &$item) {
$item->slug = $item->id . ':' . $item->alias;
$item->catslug = $item->catid . ':' .
$item->category_alias;
$item->username = Factory::getUser($item->created_by)->name;
$item->link = Route::_(version_compare(JVERSION, '4.0.0',
'>=') ?
Joomla\Component\Content\Site\Helper\RouteHelper::getArticleRoute($item->slug,
$item->catid, $item->language) :
ContentHelperRoute::getArticleRoute($item->slug, $item->catid,
$item->language));
$attribs = json_decode($item->attribs);
$item->tags = new TagsHelper;
$item->tags->getItemTags('com_content.article',
$item->id);
$feature_img = '';
if (isset($attribs->helix_ultimate_image) &&
$attribs->helix_ultimate_image) {
$feature_img = $attribs->helix_ultimate_image;
} elseif (isset($attribs->spfeatured_image) &&
$attribs->spfeatured_image) {
$feature_img = $attribs->spfeatured_image;
}
// Featured Image
if(isset($feature_img) && $feature_img != NULL) {
$item->featured_image = $featured_image = $feature_img;
$img_baseurl = basename($featured_image);
//Small
$small = JPATH_ROOT . '/' . dirname($featured_image) .
'/' . File::stripExt($img_baseurl) . '_small.' .
File::getExt($img_baseurl);
if(file_exists($small)) {
$item->image_small = Uri::root(true) . '/' .
dirname($featured_image) . '/' . File::stripExt($img_baseurl) .
'_small.' . File::getExt($img_baseurl);
}
//Thumb
$thumbnail = JPATH_ROOT . '/' . dirname($featured_image) .
'/' . File::stripExt($img_baseurl) . '_thumbnail.' .
File::getExt($img_baseurl);
if(file_exists($thumbnail)) {
$item->image_thumbnail = Uri::root(true) . '/' .
dirname($featured_image) . '/' . File::stripExt($img_baseurl) .
'_thumbnail.' . File::getExt($img_baseurl);
} else {
$item->image_thumbnail = Uri::root(true) . '/' .
$item->featured_image;
}
//Medium
$medium = JPATH_ROOT . '/' . dirname($featured_image) .
'/' . File::stripExt($img_baseurl) . '_medium.' .
File::getExt($img_baseurl);
if(file_exists($medium)) {
$item->image_medium = Uri::root(true) . '/' .
dirname($featured_image) . '/' . File::stripExt($img_baseurl) .
'_medium.' . File::getExt($img_baseurl);
}
//Large
$large = JPATH_ROOT . '/' . dirname($featured_image) .
'/' . File::stripExt($img_baseurl) . '_large.' .
File::getExt($img_baseurl);
if(file_exists($large)) {
$item->image_large = Uri::root(true) . '/' .
dirname($featured_image) . '/' . File::stripExt($img_baseurl) .
'_large.' . File::getExt($img_baseurl);
}
} else {
$images = json_decode($item->images);
if(isset($images->image_intro) && $images->image_intro) {
if(strpos($images->image_intro, "http://") !== false ||
strpos($images->image_intro, "https://") !== false){
$item->image_thumbnail = $images->image_intro;
} else {
$item->image_thumbnail = Uri::root(true) . '/' .
$images->image_intro;
}
} elseif (isset($images->image_fulltext) &&
$images->image_fulltext) {
if(strpos($images->image_fulltext, "http://") !== false
|| strpos($images->image_fulltext, "https://") !== false){
$item->image_thumbnail = $images->image_fulltext;
} else {
$item->image_thumbnail = Uri::root(true) . '/' .
$images->image_fulltext;
}
} else {
$item->image_thumbnail = false;
}
}
// Post Format
$item->post_format = 'standard';
if(isset($attribs->helix_ultimate_article_format) &&
$attribs->helix_ultimate_article_format != '') {
$item->post_format = $attribs->helix_ultimate_article_format;
} elseif(isset($attribs->post_format) &&
$attribs->post_format != '') {
$item->post_format = $attribs->post_format;
}
// Post Format Video
if(isset($item->post_format) && $item->post_format ==
'video') {
$video_url = '';
if (isset($attribs->helix_ultimate_video) &&
$attribs->helix_ultimate_video) {
$video_url = $attribs->helix_ultimate_video;
} elseif (isset($attribs->video) && $attribs->video) {
$video_url = $attribs->video;
}
if(isset($video_url) && $video_url != NULL) {
$video = parse_url($video_url);
$video_src = '';
switch($video['host']) {
case 'youtu.be':
$video_id = trim($video['path'],'/');
$video_src = '//www.youtube.com/embed/' . $video_id;
break;
case 'www.youtube.com':
case 'youtube.com':
parse_str($video['query'], $query);
$video_id = $query['v'];
$video_src = '//www.youtube.com/embed/' . $video_id;
break;
case 'vimeo.com':
case 'www.vimeo.com':
$video_id = trim($video['path'],'/');
$video_src = "//player.vimeo.com/video/" . $video_id;
}
$item->video_src = $video_src;
} else {
$item->video_src = '';
}
}
// Post Format Audio
if(isset($item->post_format) && $item->post_format ==
'audio') {
$audio_url = '';
if (isset($attribs->helix_ultimate_audio) &&
$attribs->helix_ultimate_audio) {
$audio_url = $attribs->helix_ultimate_audio;
} elseif (isset($attribs->audio) && $attribs->audio) {
$audio_url = $attribs->audio;
}
if(isset($audio_url) && $audio_url != NULL) {
$item->audio_embed = $audio_url;
} else {
$item->audio_embed = '';
}
}
// Post Format Quote
if(isset($item->post_format) && $item->post_format ==
'quote') {
if(isset($attribs->quote_text) && $attribs->quote_text !=
NULL) {
$item->quote_text = $attribs->quote_text;
} else {
$item->quote_text = '';
}
if(isset($attribs->quote_author) &&
$attribs->quote_author != NULL) {
$item->quote_author = $attribs->quote_author;
} else {
$item->quote_author = '';
}
}
// Post Format Status
if(isset($item->post_format) && $item->post_format ==
'status') {
if(isset($attribs->post_status) && $attribs->post_status
!= NULL) {
$item->post_status = $attribs->post_status;
} else {
$item->post_status = '';
}
}
// Post Format Link
if(isset($item->post_format) && $item->post_format ==
'link') {
if(isset($attribs->link_title) && $attribs->link_title !=
NULL) {
$item->link_title = $attribs->link_title;
} else {
$item->link_title = '';
}
if(isset($attribs->link_url) && $attribs->link_url !=
NULL) {
$item->link_url = $attribs->link_url;
} else {
$item->link_url = '';
}
}
// Post Format Gallery
if(isset($item->post_format) && $item->post_format ==
'gallery') {
$gallery_imgs = '';
if (isset($attribs->helix_ultimate_gallery) &&
$attribs->helix_ultimate_gallery) {
$gallery_imgs = $attribs->helix_ultimate_gallery;
} elseif (isset($attribs->gallery) && $attribs->gallery)
{
$gallery_imgs = $attribs->gallery;
}
$item->imagegallery = new stdClass();
$gallery_imgs;
if(isset($gallery_imgs) && $gallery_imgs != NULL) {
$gallery_img_decode = json_decode($gallery_imgs);
$gallery_all_images = '';
if (isset($gallery_img_decode->helix_ultimate_gallery_images)
&& $gallery_img_decode->helix_ultimate_gallery_images) {
$gallery_all_images =
$gallery_img_decode->helix_ultimate_gallery_images;
} elseif (isset($gallery_img_decode->gallery_images) &&
$gallery_img_decode->gallery_images) {
$gallery_all_images = $gallery_img_decode->gallery_images;
}
$gallery_images = array();
if(isset($gallery_all_images) &&
is_array($gallery_all_images)){
foreach ($gallery_all_images as $key=>$value) {
$gallery_images[$key]['full'] = $value;
$gallery_img_baseurl = basename($value);
//Small
$small = JPATH_ROOT . '/' . dirname($value) .
'/' . File::stripExt($gallery_img_baseurl) . '_small.'
. File::getExt($gallery_img_baseurl);
if(file_exists($small)) {
$gallery_images[$key]['small'] = Uri::root(true) .
'/' . dirname($value) . '/' .
File::stripExt($gallery_img_baseurl) . '_small.' .
File::getExt($gallery_img_baseurl);
}
//Thumbnail
$thumbnail = JPATH_ROOT . '/' . dirname($value) .
'/' . File::stripExt($gallery_img_baseurl) .
'_thumbnail.' . File::getExt($gallery_img_baseurl);
if(file_exists($thumbnail)) {
$gallery_images[$key]['thumbnail'] = Uri::root(true) .
'/' . dirname($value) . '/' .
File::stripExt($gallery_img_baseurl) . '_thumbnail.' .
File::getExt($gallery_img_baseurl);
}
//Medium
$medium = JPATH_ROOT . '/' . dirname($value) .
'/' . File::stripExt($gallery_img_baseurl) .
'_medium.' . File::getExt($gallery_img_baseurl);
if(file_exists($medium)) {
$gallery_images[$key]['medium'] = Uri::root(true) .
'/' . dirname($value) . '/' .
File::stripExt($gallery_img_baseurl) . '_medium.' .
File::getExt($gallery_img_baseurl);
}
//Large
$large = JPATH_ROOT . '/' . dirname($value) .
'/' . File::stripExt($gallery_img_baseurl) . '_large.'
. File::getExt($gallery_img_baseurl);
if(file_exists($large)) {
$gallery_images[$key]['large'] = Uri::root(true) .
'/' . dirname($value) . '/' .
File::stripExt($gallery_img_baseurl) . '_large.' .
File::getExt($gallery_img_baseurl);
}
}
}
$item->imagegallery->images = $gallery_images;
} else {
$item->imagegallery->images = array();
}
}
}
return $items;
}
public static function getCategories($parent_id = [1],
$include_subcategories = true, $child = false, $cats = array()) {
$app = Factory::getApplication();
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query
->select('*')
->from($db->quoteName('#__categories'))
->where($db->quoteName('extension') . ' = ' .
$db->quote('com_content'))
->where($db->quoteName('published') . ' = ' .
$db->quote(1))
->where($db->quoteName('access')." IN (" .
implode( ',', Factory::getUser()->getAuthorisedViewLevels() )
. ")")
->where($db->quoteName('language')." IN (" .
$db->Quote(Factory::getLanguage()->getTag()).",
".$db->Quote('*') . ")");
if (!empty(array_filter($parent_id)))
{
$query->where($db->quoteName('parent_id')." IN
(" . implode( ',', $parent_id ) . ")");
}
$query->order($db->quoteName('lft') . ' ASC');
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ($rows as $row) {
if($include_subcategories) {
array_push($cats, $row->id);
if (self::hasChildren($row->id)) {
$cats = self::getCategories(array($row->id),
$include_subcategories, true, $cats);
}
}
}
return $cats;
}
private static function hasChildren($parent_id = 1) {
$app = Factory::getApplication();
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query
->select('*')
->from($db->quoteName('#__categories'))
->where($db->quoteName('extension') . ' = ' .
$db->quote('com_content'))
->where($db->quoteName('published') . ' = ' .
$db->quote(1))
->where($db->quoteName('access')." IN (" .
implode( ',', Factory::getUser()->getAuthorisedViewLevels() )
. ")")
->where($db->quoteName('language')." IN (" .
$db->Quote(Factory::getLanguage()->getTag()).",
".$db->Quote('*') . ")")
->where($db->quoteName('parent_id') . ' = ' .
$db->quote($parent_id))
->order($db->quoteName('created_time') . '
DESC');
$db->setQuery($query);
$childrens = $db->loadObjectList();
if(is_array($childrens) && count($childrens)) {
return true;
}
return false;
}
}
assets-css-parser.php000064400000003745151200771650010654 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined('_JEXEC') or die('Restricted access');
/**
* Assets Css Parser Class
*
* @since 4.0.0
*/
class SppbAssetCssParser
{
private static $instance;
/**
* Get the parsed class list
*
* @param string $css css file for parsing
* @return object
* @since 4.0.0
*/
public static function getClassName($css, $prefix, $force = false)
{
if (empty(trim($css)))
{
return false;
}
if (self::$instance === null)
{
self::$instance = new SppbAssetCssParser();
}
$parsedClassName = self::$instance->parseCssSelectors($css,
$prefix, $force);
return $parsedClassName;
}
/**
* Parse CSS Selectors
*
* @param [type] $css CSS file to parse.
* @param [type] $prefix Prefix.
* @param boolean $force Add extra prefix.
* @return void
*/
private function parseCssSelectors($css, $prefix, $force = false)
{
$result = [];
/**
* Check css comment
* preg_match_all('/([\/][\*]).*./',$css,$match);
*/
preg_match_all('/([^\{\}]+)\{([^\}]*)\}|([\/\*])/ims',
$css, $match);
foreach ($match[0] as $i => $x)
{
$selector = trim($match[1][$i]);
if (preg_match_all("/(^\." . $prefix.
"\-)\w+(\-\w+)?(\-\w+)?(:before)/m", $selector))
{
if ($force)
{
$result[] = $prefix . ' ' .
(explode(':', explode('.', $selector)[1])[0]);
}
else
{
$result[] = explode(':',
explode('.', $selector)[1])[0];
}
}
}
return json_encode($result);
}
}auth-helper.php000064400000007424151200771650007506 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
/** No direct access. */
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\User\User;
use Joomla\CMS\User\UserHelper;
/**
* The authentication helper class for authenticating user.
*
* @since 4.0.0
*/
class AuthHelper
{
/**
* Securely login user by the username.
*
* @param string $username The username.
*
* @return void
* @since 4.0.0
*/
public static function loginUserByUsername(string $username)
{
$user = User::getInstance();
$userId = UserHelper::getUserId($username);
if (!empty($userId))
{
/** Load the user data by using the ID. */
$user->load($userId);
$isAuthorisedUser = $user->authorise('core.login.site');
if ($isAuthorisedUser)
{
$user->guest = 0;
$session = Factory::getSession();
/** Preserve the old session ID. */
$prevSessionId = $session->getId();
/** Fork the session and create a new instance. */
$session->fork();
/** Update the user information to the session. */
$session->set('user', $user);
$app = Factory::getApplication();
$app->checkSession();
/** Delete the old session from the database. */
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->delete('#__session')
->where($db->quoteName('session_id') . ' = '
. $db->quote($prevSessionId));
$db->setQuery($query);
try
{
$db->execute();
}
catch (Exception $e)
{
$app->enqueueMessage('Error deleting session: ' .
$e->getMessage());
}
/** Pass through method to the table for setting the last visit date.
*/
$user->setLastVisit();
/** Update the cookie. */
$app->input->cookie->set(
'joomla_user_state',
'logged_in',
0,
$app->get('cookie_path', '/'),
$app->get('cookie_domain', ''),
$app->isHttpsForced(),
true
);
}
}
}
/**
* Generate the secure link for visiting from administrator to site.
*
* @return string The generated link url.
* @since 4.0.0
*/
public static function generateLink(string $path = '')
{
$user = Factory::getUser();
$link = Uri::root() .
'index.php?option=com_sppagebuilder&view=dashboard&tmpl=component';
$link .= '&username=' . urlencode($user->username);
$link .= '&password=' . urlencode($user->password);
$link .= '#/' . $path;
return $link;
}
private static function checkCredibility($username, $password)
{
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select('username')
->from($db->quoteName('#__users'))
->where($db->quoteName('username') . ' = ' .
$db->quote($username))
->where($db->quoteName('password') . ' = ' .
$db->quote($password));
$db->setQuery($query);
try
{
return !empty($db->loadResult());
}
catch (Exception $e)
{
return false;
}
return false;
}
/**
* Check the user credibility before visiting the dashboard.
*
* @return void
* @since 4.0.0
*/
public static function loginBeforePassThrough()
{
$app = Factory::getApplication();
$input = $app->input;
$user = Factory::getUser();
$username = $input->get('username', '',
'raw');
$password = $input->get('password', '',
'raw');
if (!$user->authorise('core.admin',
'com_sppagebuilder') && self::checkCredibility($username,
$password))
{
self::loginUserByUsername($username);
}
if (!empty($username) || !empty($password))
{
$GET = $input->get->getArray([]);
unset($GET['username']);
unset($GET['password']);
$url = http_build_query($GET);
header('Location: ' . Uri::current() . '?' . $url);
exit;
}
return false;
}
}
autoload.php000064400000006334151200771650007077 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
/** No direct access. */
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Uri\Uri;
/**
* Autoload the required classes in a required scope.
*
* @since 4.0.0
*/
class BuilderAutoload
{
/**
* Load the required classes for the application.
*
* @return void
* @since 4.0.0
*/
public static function loadClasses()
{
require_once JPATH_ROOT .
'/components/com_sppagebuilder/helpers/route.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/helpers/helper.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/helpers/auth-helper.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/builder/classes/base.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/builder/classes/config.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/parser/helper-base.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/parser/lodash.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/parser/css-helper.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/parser/addon-utils.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/builder/classes/addon.php';
require_once JPATH_ROOT .
'/components/com_sppagebuilder/helpers/helper.php';
}
public static function loadHelperClasses()
{
if (!class_exists('AddonsHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/editor/helpers/AddonsHelper.php';
}
if (!class_exists('ApplicationHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/editor/helpers/ApplicationHelper.php';
}
if (!class_exists('SecurityHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/editor/helpers/SecurityHelper.php';
}
if (!class_exists('EditorUtils'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/editor/helpers/EditorUtils.php';
}
if (!class_exists('FontHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/editor/helpers/FontHelper.php';
}
if (!class_exists('IconHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/editor/helpers/IconHelper.php';
}
if (!class_exists('LanguageHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/editor/helpers/LanguageHelper.php';
}
if (!class_exists('SppagebuilderHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/helpers/sppagebuilder.php';
}
if (!class_exists('BuilderMediaHelper'))
{
require_once JPATH_ROOT .
'/administrator/components/com_sppagebuilder/helpers/media-helper.php';
}
}
/**
* Load the global assets to the whole application.
*
* @return void
* @since 4.0.0
*/
public static function loadGlobalAssets()
{
$doc = Factory::getDocument();
$doc->addScript(Uri::root(true) .
'/components/com_sppagebuilder/assets/js/common.js');
HTMLHelper::_('behavior.core');
}
}
constants.php000064400000000502151200771650007272 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
define('LAZYLOAD_PLACEHOLDER',
'/components/com_sppagebuilder/assets/images/lazyloading-placeholder.svg');css-parser.php000064400000023474151200771650007355
0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined('_JEXEC') or die('Restricted access');
if (!class_exists('SppbCustomCssParser'))
{
/**
* Class Parse CSS code for SP Page Builder
*
* @since 4.0.0
*/
class SppbCustomCssParser
{
/**
* CSS date
*
* @var array
* @since 1.0.0
*/
protected $cssData;
protected static $propCounter;
/**
* CSS value
*
* @var string
* @since 1.0.0
*/
protected $css;
/**
* Generated New CSS string
*
* @var string
* @since 1.0.0
*/
protected $newCss;
/**
* TAG ID
*
* @var string
* @since 1.0.0
*/
protected $id;
/**
* Addon Wrapper ID
*
* @var string
* @since 1.0.0
*/
protected $addonWrapperId;
/**
* Class instance
*
* @var SppbCustomCssParser
* @since 1.0.0
*/
private static $instance;
/**
* Generate new CSS value
*
* @param string $css CSS value
* @param string $id Tag ID
* @param string $addonWrapperId Addon Wrapper ID
*
* @return void
* @since 1.0.0
*/
public function cssWork($addonName, $css, $id, $addonWrapperId)
{
$this->cssData = ['all'=>[]];
$this->css = $css;
$this->id = $id;
$this->addonWrapperId = $addonWrapperId;
$this->parseCss();
$this->addId($addonName);
return $this->newCss;
}
/**
* Get Generated CSS value.
*
* @param string $css CSS value
* @param string $id Tag ID
* @param string $addonWrapperId Addon Wrapper ID
*
* @return void
* @since 1.0.0
*/
public static function getCss($addonName, $css, $id, $addonWrapperId
= null)
{
if (empty(trim($css)))
{
return false;
}
if (self::$instance === null)
{
self::$instance = new SppbCustomCssParser();
}
$parsedCss = self::$instance->cssWork($addonName, $css, $id,
$addonWrapperId);
return $parsedCss;
}
/**
* Add Id into section
*
* @return void
* @since 1.0.0
*/
protected function addId($addonName)
{
$newCss = '';
$id = $this->id;
$addonWrapperId = $this->addonWrapperId;
if (count((array) $this->cssData))
{
foreach ($this->cssData as $media => $mediaCss)
{
if ($media != 'all')
{
$newCss .= "@media ${media}{";
}
foreach ($mediaCss as $selector => $values)
{
$selectors = explode(',', $selector);
$newSelectors = array();
foreach ($selectors as $tmpSelector)
{
if (preg_match("/#addonId/", $tmpSelector))
{
$tmpSelector = str_replace("#addonId",
$id, $tmpSelector);
$tmpSelector =
str_replace("#addonWrapper", $addonWrapperId, $tmpSelector);
$newSelectors[] = "${tmpSelector}";
}
elseif(preg_match("/#addonWrapper/",
$tmpSelector))
{
$tmpSelector = str_replace("#addonWrapper",
$addonWrapperId, $tmpSelector);
$newSelectors[] = "${tmpSelector}";
}
else
{
$newSelectors[] = $addonName === 'div' ?
"${id}${tmpSelector}" : "${id} ${tmpSelector}";
}
}
$newSelector = implode(',', $newSelectors);
$newCss .= "${newSelector}{";
foreach ($values as $cssProp => $cssValue)
{
$newCss .= "${cssProp}:${cssValue};";
}
$newCss .= "}";
}
if ($media != 'all')
{
$newCss .= "}";
}
}
}
$this->newCss = $newCss;
}
/**
* Parse CSS
*
* @return void
* @since 1.0.0
*/
protected function parseCss()
{
$currentMedia = 'all';
$mediaList = array();
$section = false;
$css = trim($this->css);
if (strlen($css) == 0)
{
return false;
}
$css = preg_replace('/\/\*.*\*\//Us', '',
$css);
while
(preg_match('/^\s*(\@(media|import|local)([^\{\}]+)(\{)|([^\{\}]+)(\{)|([^\{\}]*)(\}))/Usi',
$css, $match))
{
if (isset($match[8]) && ($match[8] == '}'))
{
if ($section !== false)
{
$code = trim($match[7]);
if (empty($code) || is_null($code))
{
break;
}
$idx = 0;
$inQuote = false;
$property = false;
$codeLen = strlen($code);
$parenthesis = array();
while ($idx < $codeLen)
{
$c = isset($code[$idx]) ? $code[$idx] : '';
$idx++;
if ($inQuote !== false)
{
if ($inQuote === $c)
{
$inQuote = false;
}
}
elseif (($inQuote === false) && ($c ==
'('))
{
array_push($parenthesis, '(');
}
elseif (($inQuote === false) && ($c ==
')'))
{
array_pop($parenthesis);
}
elseif (($c == '\'') || ($c ==
'"'))
{
$inQuote = $c;
}
elseif (($property === false) && ($c ==
':'))
{
$property = trim(substr($code, 0, $idx - 1));
if (preg_match('/^(.*)\[([0-9]*)\]$/Us',
$property, $propMatch))
{
$property =
$propMatch[1].'['.static::$propCounter.']';
static::$propCounter += 1;
}
$code = substr($code, $idx);
$idx = 0;
}
elseif((count((array) $parenthesis) == 0) && ($c ==
';'))
{
$value = trim(substr($code, 0, $idx - 1));
$code = substr($code, $idx);
$idx = 0;
$this->AddProperty($currentMedia, $section, $property,
$value);
$property = false;
}
}
if (($idx > 0) && ($property !== false))
{
$value = trim($code);
$this->AddProperty($currentMedia, $section, $property,
$value);
}
$section = false;
}
elseif(count((array) $mediaList) > 0)
{
array_pop($mediaList);
if (count((array) $mediaList) > 0)
{
$currentMedia = end($mediaList);
}
else
{
$currentMedia = 'all';
}
}
}
elseif (isset($match[6]) && ($match[6] == '{'))
{
$section = trim($match[5]);
if (!isset($this->cssData[$currentMedia][$section]))
{
$this->cssData[$currentMedia][$section] = array();
}
}
elseif (isset($match[4]) && ($match[4] == '{'))
{
if ($match[2] == 'media')
{
// New media
$media = trim($match[3]);
$mediaList[] = $media;
$currentMedia = $media;
if (!isset($this->cssData[$currentMedia]))
{
$this->cssData[$currentMedia] = array();
}
}
}
$stripCount = strlen($match[0]);
$css = trim(substr($css, $stripCount));
}
}
/**
* Add CSS value into a property
*
* @param string $media Media type value
* @param string $section HTML Section
* @param string $property CSS Property
* @param string $value CSS Value
*
* @return void
* @since 1.0.0
*/
protected function AddProperty($media, $section, $property, $value)
{
$media = trim($media);
if ($media == '')
{
$media = 'all';
}
$section = trim($section);
$property = trim($property);
if (strlen($property) > 0)
{
$value = trim($value);
if ($media == 'all')
{
$this->cssData[$media][$section][$property] = $value;
$keys = array_keys($this->cssData);
foreach ($keys as $key)
{
if (!isset($this->cssData[$key][$section]))
{
$this->cssData[$key][$section] = array();
}
$this->cssData[$key][$section][$property] = $value;
}
}
else
{
if (!isset($this->cssData[$media]))
{
$this->cssData[$media] =
$this->cssData['all'];
}
if (!isset($this->cssData[$media][$section]))
{
$this->cssData[$media][$section] = array();
}
$this->cssData[$media][$section][$property] = $value;
}
}
}
}
}image.php000064400000005755151200771650006357 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined('_JEXEC') or die('Restricted access');
class SppagebuilderHelperImage
{
public $height;
public $width;
private $src;
public function __construct($src = '')
{
$this->src = $src;
list($this->width, $this->height) = getimagesize($src);
}
public function getDimension()
{
return [$this->width, $this->height];
}
/**
* Create thumb image with specifice height and width and with their ratio
*/
public function createThumb($size, $destination, $base_name, $ext,
$quality = 100)
{
$img = $this->createImageFromType($ext);
if (count((array) $size) && $img != null)
{
$targetWidth = $size[0];
$targetHeight = $size[1];
$ratio_thumb = $targetWidth / $targetHeight;
$ratio_original = $this->width / $this->height;
if ($ratio_original >= $ratio_thumb)
{
$height = $this->height;
$width = ceil(($height * $targetWidth) / $targetHeight);
$x = ceil(($this->width - $width) / 2);
$y = 0;
}
else
{
$width = $this->width;
$height = ceil(($width * $targetHeight) / $targetWidth);
$y = ceil(($this->height - $height) / 2);
$x = 0;
}
$targetWidth = (int) $targetWidth;
$targetHeight = (int) $targetHeight;
$new = imagecreatetruecolor($targetWidth, $targetHeight);
if ($ext == "gif" or $ext == "png")
{
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0,
127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
imagecopyresampled($new, $img, 0, 0, $x, $y, $targetWidth,
$targetHeight, $width, $height);
$dest = $destination . '/' . $base_name . '.' .
$ext;
$this->cloneImage($ext, $new, $dest, $quality);
return true;
}
return false;
}
/**
* Clone Image from original to destination source based on extension
*/
private function cloneImage($ext, $new, $dest, $quality)
{
switch ($ext)
{
case 'bmp':
imagewbmp($new, $dest);
break;
case 'webp':
imagewebp($new, $dest, $quality);
break;
case 'gif':
imagegif($new, $dest);
break;
case 'jpg':
imagejpeg($new, $dest, $quality);
break;
case 'jpeg':
imagejpeg($new, $dest, $quality);
break;
case 'png':
imagepng($new, $dest, floor($quality / 11));
break;
}
}
/**
* Create Image from their specific extension
*/
private function createImageFromType($ext)
{
switch ($ext)
{
case 'bmp':
$img = imagecreatefromwbmp($this->src);
break;
case 'webp':
$img = imagecreatefromwebp($this->src);
break;
case 'gif':
$img = imagecreatefromgif($this->src);
break;
case 'jpg':
$img = imagecreatefromjpeg($this->src);
break;
case 'jpeg':
$img = imagecreatefromjpeg($this->src);
break;
case 'png':
$img = imagecreatefrompng($this->src);
break;
}
return $img;
}
}
integration-helper.php000064400000002044151200771660011062 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
use Joomla\CMS\Language\Text;
/** No direct access. */
defined('_JEXEC') or die('Restricted access');
/**
* Integration helper for the builder.
*
* @since 4.0.0
*/
class BuilderIntegrationHelper
{
public static function getIntegrations(): array
{
return [
'content' => [
'title' =>
Text::_("COM_SPPAGEBUILDER_JOOMLA_ARTICLE"),
'group' => 'content',
'name' => 'sppagebuilder',
'view' => 'article',
'id_alias' => 'id'
],
'spsimpleportfolio' => [
'title' =>
Text::_("COM_SPPAGEBUILDER_SP_SIMPLE_PORTFOLIO"),
'group' => 'spsimpleportfolio',
'name' => 'sppagebuilder',
'view' => 'item',
'id_alias' => 'id',
'frontend_only' => true,
],
'k2' => [
'title' => 'K2',
'group' => 'k2',
'name' => 'sppagebuilder',
'view' => 'item',
'id_alias' => 'cid'
]
];
}
}
k2.php000064400000020161151200771660005576 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined ('_JEXEC') or die ('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Access\Access;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\HTML\HTMLHelper;
$k2Route = JPATH_SITE . '/components/com_k2/helpers/route.php';
$k2Unilities = JPATH_SITE .
'/components/com_k2/helpers/utilities.php';
if(!file_exists($k2Route) && !file_exists($k2Unilities)) {
$k2cats = array(''=>'K2 Isn\'t installed');
return false;
} else {
require_once $k2Route;
require_once $k2Unilities;
}
abstract class SppagebuilderHelperK2{
public static function getItems( $count = 5, $ordering =
'latest', $catid = '', $include_subcategories = true,
$post_format = '' ) {
$authorised =
Access::getAuthorisedViewLevels(Factory::getUser()->get('id'));
$componentParams = ComponentHelper::getParams('com_k2');
$app = Factory::getApplication();
$db = Factory::getDbo();
$query = $db->getQuery(true);
$jnow = Factory::getDate();
$nowDate = K2_JVERSION == '15' ? $jnow->toMySQL() :
$jnow->toSql();
$nullDate = $db->getNullDate();
$query
->select('a.*')
->from($db->quoteName('#__k2_items', 'a'))
->select($db->quoteName('b.alias',
'category_alias'))
->select($db->quoteName('b.name', 'category'))
->join('LEFT',
$db->quoteName('#__k2_categories', 'b') . ' ON
(' . $db->quoteName('a.catid') . ' = ' .
$db->quoteName('b.id') . ')');
$query->where($db->quoteName('a.published') . ' =
' . $db->quote(1));
$query->where($db->quoteName('a.trash') . ' !=
' . $db->quote(1));
$query->where('(a.publish_up = ' . $db->Quote($nullDate)
. ' OR a.publish_up <= ' . $db->Quote($nowDate) .
')');
$query->where('(a.publish_down = ' .
$db->Quote($nullDate) . ' OR a.publish_down >= ' .
$db->Quote($nowDate) . ')');
// Category filter
if ( ($catid != '' || is_array($catid)) ) {
if (!is_array($catid)) {
$catid = array($catid);
}
if (!in_array('', $catid)) {
$categories = self::getCategories( $catid, $include_subcategories );
$categories = array_merge($categories, $catid);
$query->where($db->quoteName('a.catid')." IN
(" . implode( ',', $categories ) . ")");
}
}
// has order by
if ($ordering == 'hits') {
$query->order($db->quoteName('a.hits') . '
DESC');
}elseif($ordering == 'featured'){
$query->where($db->quoteName('a.featured') . ' =
' . $db->quote(1));
$query->order($db->quoteName('a.created') . '
DESC');
}else{
$query->order($db->quoteName('a.created') . '
DESC');
}
// Language filter
if ($app->isClient('site') &&
$app->getLanguageFilter()) {
$query->where('a.language IN (' .
$db->Quote(Factory::getLanguage()->getTag()) . ',' .
$db->Quote('*') . ')');
}
// continue query
$query->where($db->quoteName('a.access')." IN
(" . implode( ',', $authorised ) . ")");
$query->order($db->quoteName('a.created') . '
DESC')
->setLimit($count);
$db->setQuery($query);
$items = $db->loadObjectList();
foreach ($items as &$item) {
$item->slug = $item->id . ':' . $item->alias;
$item->catslug = $item->catid . ':' .
$item->category_alias;
$item->username = Factory::getUser($item->created_by)->name;
$item->link =
urldecode(Route::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias),
$item->catid.':'.urlencode($item->category_alias))));
$date = Factory::getDate($item->modified);
$timestamp = '?t='.$date->toUnix();
$item->image_thumbnail = false;
if
(File::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_XS.jpg'))
{
$item->image_thumbnail = true;
$item->imageXSmall =
Uri::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_XS.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageXSmall .= $timestamp;
}
}
if
(File::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_S.jpg'))
{
$item->image_thumbnail = true;
$item->image_small =
Uri::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_S.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->image_small .= $timestamp;
}
}
if
(File::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_M.jpg'))
{
$item->image_thumbnail = true;
$item->image_medium =
Uri::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_M.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->image_medium .= $timestamp;
}
}
if
(File::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_L.jpg'))
{
$item->image_thumbnail = true;
$item->image_large =
Uri::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_L.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->image_large .= $timestamp;
}
}
if
(File::exists(JPATH_SITE.DS.'media'.DS.'k2'.DS.'items'.DS.'cache'.DS.md5("Image".$item->id).'_Generic.jpg'))
{
$item->image_thumbnail = true;
$item->imageGeneric =
Uri::base(true).'/media/k2/items/cache/'.md5("Image".$item->id).'_Generic.jpg';
if ($componentParams->get('imageTimestamp'))
{
$item->imageGeneric .= $timestamp;
}
}
}
return $items;
}
public static function getCategories($parent_id = 0,
$include_subcategories = true, $child = false, $cats = array() ) {
$app = Factory::getApplication();
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query
->select('*')
->from($db->quoteName('#__k2_categories'))
->where($db->quoteName('published') . ' = ' .
$db->quote(1))
->where($db->quoteName('access')." IN (" .
implode( ',', Factory::getUser()->getAuthorisedViewLevels() )
. ")")
->where($db->quoteName('language')." IN (" .
$db->Quote(Factory::getLanguage()->getTag()).",
".$db->Quote('*') . ")")
//->where($db->quoteName('parent') . ' = ' .
$db->quote($parent_id))
->where($db->quoteName('parent')." IN (" .
implode( ',', $parent_id ) . ")")
->order($db->quoteName('ordering') . ' ASC');
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ($rows as $row) {
if($include_subcategories) {
array_push($cats, $row->id);
if (self::hasChildren($row->id)) {
$cats = self::getCategories(array($row->id),
$include_subcategories, true, $cats);
}
}
}
return $cats;
}
private static function hasChildren($parent_id = 1) {
$app = Factory::getApplication();
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query
->select('*')
->from($db->quoteName('#__k2_categories'))
->where($db->quoteName('published') . ' = ' .
$db->quote(1))
->where($db->quoteName('access')." IN (" .
implode( ',', Factory::getUser()->getAuthorisedViewLevels() )
. ")")
->where($db->quoteName('language')." IN (" .
$db->Quote(Factory::getLanguage()->getTag()).",
".$db->Quote('*') . ")")
->where($db->quoteName('parent') . ' = ' .
$db->quote($parent_id))
->order($db->quoteName('ordering') . ' DESC');
$db->setQuery($query);
$childrens = $db->loadObjectList();
if(count((array) $childrens)) {
return true;
}
return false;
}
public static function getcatTree(){
$db = Factory::getDBO();
$query = 'SELECT m.* FROM #__k2_categories m WHERE trash = 0 ORDER
BY parent, ordering';
$db->setQuery($query);
$mitems = $db->loadObjectList();
$children = array();
if ($mitems)
{
foreach ($mitems as $v)
{
if (K2_JVERSION != '15')
{
$v->title = $v->name;
$v->parent_id = $v->parent;
}
$pt = $v->parent;
$list = @$children[$pt] ? $children[$pt] : array();
array_push($list, $v);
$children[$pt] = $list;
}
}
$list = HTMLHelper::_('menu.treerecurse', 0, '',
array(), $children, 9999, 0, 0);
$mitems = array();
foreach ($list as $item)
{
$item->treename = JString::str_ireplace(' ',
'- ', $item->treename);
$mitems[] = HTMLHelper::_('select.option', $item->id,
' '.$item->treename);
}
return $mitems;
}
}
tweet/helper.php000064400000005344151200771660007677 0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined ('_JEXEC') or die ('Restricted access');
require_once __DIR__ . '/twitteroauth/twitteroauth.php';
jimport( 'joomla.filesystem.folder' );
class sppbAddonHelperTweet
{
public static function getTweets( $username='joomshaper',
$consumerkey='', $consumersecret='',
$accesstoken='', $accesstokensecret='', $count=5,
$ignore_replies=false, $include_rts=false )
{
$cache_path = JPATH_CACHE .
'/com_sppagebuilder/addons/tweet';
$cache_file = $cache_path . '/cache.txt';
$cachetime = 60*15;
$tweets = '';
//Create cache folder if not exists
if(!JFolder::exists( $cache_path )) JFolder::create( $cache_path );
$cache_file_created = ((Jfile::exists($cache_file))) ?
filemtime($cache_file) : 0;
if (time() - $cachetime < $cache_file_created)
{
$tweets = json_decode(file_get_contents( $cache_file ) );
}
else
{
$connection = new TwitterOAuth($consumerkey, $consumersecret,
$accesstoken, $accesstokensecret);
if($connection)
{
$get_tweets =
$connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$username."&count=".$count."&include_rts=".$include_rts."&exclude_replies=".$ignore_replies);
$tweets = json_encode($get_tweets);
JFile::write( $cache_file, $tweets );
$tweets = $get_tweets;
}
}
return $tweets;
}
public static function timeago($timestamp) {
$time_arr = explode(" ",$timestamp);
$year = $time_arr[5];
$day = $time_arr[2];
$time = $time_arr[3];
$time_array = explode(":",$time);
$month_name = $time_arr[1];
$month = array (
'Jan' => 1,
'Feb' => 2,
'Mar' => 3,
'Apr' => 4,
'May' => 5,
'Jun' => 6,
'Jul' => 7,
'Aug' => 8,
'Sep' => 9,
'Oct' => 10,
'Nov' => 11,
'Dec' => 12
);
$delta = gmmktime(0, 0, 0, 0, 0) - mktime(0, 0, 0, 0, 0);
$timestamp = mktime($time_array[0], $time_array[1], $time_array[2],
$month[$month_name], $day, $year);
$etime = time() - ($timestamp + $delta);
if ($etime < 1) {
return '0 ' . JText::_('COM_SPPAGEBUILDER_SECONDS');
}
$a = array( 12 * 30 * 24 * 60 * 60 => 'YEAR',
30 * 24 * 60 * 60 => 'MONTH',
24 * 60 * 60 => 'DAY',
60 * 60 => 'HOUR',
60 => 'MINUTE',
1 => 'SECOND'
);
foreach ($a as $secs => $str) {
$d = $etime / $secs;
if ($d >= 1) {
$r = round($d);
return $r . ' ' . JText::_( 'COM_SPPAGEBUILDER_' .
$str . ($r > 1 ? 'S' : '')) . ' ' .
JText::_( 'COM_SPPAGEBUILDER_AGO');
}
}
}
}
tweet/twitteroauth/OAuth.php000064400000064201151200771660012200
0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined ('_JEXEC') or die ('Restricted access');
// vim: foldmethod=marker
/* Generic exception class
*/
class OAuthException extends Exception {
// pass
}
class OAuthConsumer {
public $key;
public $secret;
function __construct($key, $secret, $callback_url=NULL) {
$this->key = $key;
$this->secret = $secret;
$this->callback_url = $callback_url;
}
function __toString() {
return
"OAuthConsumer[key=$this->key,secret=$this->secret]";
}
}
class OAuthToken {
// access tokens and request tokens
public $key;
public $secret;
/**
* key = the token
* secret = the token secret
*/
function __construct($key, $secret) {
$this->key = $key;
$this->secret = $secret;
}
/**
* generates the basic string serialization of a token that a server
* would respond to request_token and access_token calls with
*/
function to_string() {
return "oauth_token=" .
OAuthUtil::urlencode_rfc3986($this->key) .
"&oauth_token_secret=" .
OAuthUtil::urlencode_rfc3986($this->secret);
}
function __toString() {
return $this->to_string();
}
}
/**
* A class for implementing a Signature Method
* See section 9 ("Signing Requests") in the spec
*/
abstract class OAuthSignatureMethod {
/**
* Needs to return the name of the Signature Method (ie HMAC-SHA1)
* @return string
*/
abstract public function get_name();
/**
* Build up the signature
* NOTE: The output of this function MUST NOT be urlencoded.
* the encoding is handled in OAuthRequest when the final
* request is serialized
* @param OAuthRequest $request
* @param OAuthConsumer $consumer
* @param OAuthToken $token
* @return string
*/
abstract public function build_signature($request, $consumer, $token);
/**
* Verifies that a given signature is correct
* @param OAuthRequest $request
* @param OAuthConsumer $consumer
* @param OAuthToken $token
* @param string $signature
* @return bool
*/
public function check_signature($request, $consumer, $token, $signature)
{
$built = $this->build_signature($request, $consumer, $token);
return $built == $signature;
}
}
/**
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as
defined in [RFC2104]
* where the Signature Base String is the text and the key is the
concatenated values (each first
* encoded per Parameter Encoding) of the Consumer Secret and Token Secret,
separated by an '&'
* character (ASCII code 38) even if empty.
* - Chapter 9.2 ("HMAC-SHA1")
*/
class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
function get_name() {
return "HMAC-SHA1";
}
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
return base64_encode(hash_hmac('sha1', $base_string, $key,
true));
}
}
/**
* The PLAINTEXT method does not provide any security protection and SHOULD
only be used
* over a secure channel such as HTTPS. It does not use the Signature Base
String.
* - Chapter 9.4 ("PLAINTEXT")
*/
class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
public function get_name() {
return "PLAINTEXT";
}
/**
* oauth_signature is set to the concatenated encoded values of the
Consumer Secret and
* Token Secret, separated by a '&' character (ASCII code
38), even if either secret is
* empty. The result MUST be encoded again.
* - Chapter 9.4.1 ("Generating Signatures")
*
* Please note that the second encoding MUST NOT happen in the
SignatureMethod, as
* OAuthRequest handles this!
*/
public function build_signature($request, $consumer, $token) {
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
$request->base_string = $key;
return $key;
}
}
/**
* The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature
algorithm as defined in
* [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the
hash function for
* EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA
public key in a
* verified way to the Service Provider, in a manner which is beyond the
scope of this
* specification.
* - Chapter 9.3 ("RSA-SHA1")
*/
abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
public function get_name() {
return "RSA-SHA1";
}
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
// (2) fetch via http using a url provided by the requester
// (3) some sort of specific discovery code based on request
//
// Either way should return a string representation of the certificate
protected abstract function fetch_public_cert(&$request);
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
//
// Either way should return a string representation of the certificate
protected abstract function fetch_private_cert(&$request);
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
// Fetch the private key cert based on the request
$cert = $this->fetch_private_cert($request);
// Pull the private key ID from the certificate
$privatekeyid = openssl_get_privatekey($cert);
// Sign using the key
$ok = openssl_sign($base_string, $signature, $privatekeyid);
// Release the key resource
openssl_free_key($privatekeyid);
return base64_encode($signature);
}
public function check_signature($request, $consumer, $token, $signature)
{
$decoded_sig = base64_decode($signature);
$base_string = $request->get_signature_base_string();
// Fetch the public key cert based on the request
$cert = $this->fetch_public_cert($request);
// Pull the public key ID from the certificate
$publickeyid = openssl_get_publickey($cert);
// Check the computed signature against the one passed in the query
$ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
// Release the key resource
openssl_free_key($publickeyid);
return $ok == 1;
}
}
class OAuthRequest {
private $parameters;
private $http_method;
private $http_url;
// for debug purposes
public $base_string;
public static $version = '1.0';
public static $POST_INPUT = 'php://input';
function __construct($http_method, $http_url, $parameters=NULL) {
@$parameters or $parameters = array();
$parameters = array_merge(
OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)),
$parameters);
$this->parameters = $parameters;
$this->http_method = $http_method;
$this->http_url = $http_url;
}
/**
* attempt to build up a request from what was passed to the server
*/
public static function from_request($http_method=NULL, $http_url=NULL,
$parameters=NULL) {
$scheme = (!isset($_SERVER['HTTPS']) ||
$_SERVER['HTTPS'] != "on")
? 'http'
: 'https';
@$http_url or $http_url = $scheme .
'://' .
$_SERVER['HTTP_HOST'] .
':' .
$_SERVER['SERVER_PORT'] .
$_SERVER['REQUEST_URI'];
@$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
// We weren't handed any parameters, so let's find the ones
relevant to
// this request.
// If you run XML-RPC or similar you should use this to provide your
own
// parsed parameter-list
if (!$parameters) {
// Find request headers
$request_headers = OAuthUtil::get_headers();
// Parse the query-string to find GET parameters
$parameters =
OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
// It's a POST request of the proper content-type, so parse POST
// parameters and add those overriding any duplicates from GET
if ($http_method == "POST"
&& @strstr($request_headers["Content-Type"],
"application/x-www-form-urlencoded")
) {
$post_data = OAuthUtil::parse_parameters(
file_get_contents(self::$POST_INPUT)
);
$parameters = array_merge($parameters, $post_data);
}
// We have a Authorization-header with OAuth data. Parse the header
// and add those overriding any duplicates from GET or POST
if (@substr($request_headers['Authorization'], 0, 6) ==
"OAuth ") {
$header_parameters = OAuthUtil::split_header(
$request_headers['Authorization']
);
$parameters = array_merge($parameters, $header_parameters);
}
}
return new OAuthRequest($http_method, $http_url, $parameters);
}
/**
* pretty much a helper function to set up the request
*/
public static function from_consumer_and_token($consumer, $token,
$http_method, $http_url, $parameters=NULL) {
@$parameters or $parameters = array();
$defaults = array("oauth_version" =>
OAuthRequest::$version,
"oauth_nonce" =>
OAuthRequest::generate_nonce(),
"oauth_timestamp" =>
OAuthRequest::generate_timestamp(),
"oauth_consumer_key" =>
$consumer->key);
if ($token)
$defaults['oauth_token'] = $token->key;
$parameters = array_merge($defaults, $parameters);
return new OAuthRequest($http_method, $http_url, $parameters);
}
public function set_parameter($name, $value, $allow_duplicates = true) {
if ($allow_duplicates && isset($this->parameters[$name])) {
// We have already added parameter(s) with this name, so add to the
list
if (is_scalar($this->parameters[$name])) {
// This is the first duplicate, so transform scalar (string)
// into an array so we can add the duplicates
$this->parameters[$name] = array($this->parameters[$name]);
}
$this->parameters[$name][] = $value;
} else {
$this->parameters[$name] = $value;
}
}
public function get_parameter($name) {
return isset($this->parameters[$name]) ? $this->parameters[$name]
: null;
}
public function get_parameters() {
return $this->parameters;
}
public function unset_parameter($name) {
unset($this->parameters[$name]);
}
/**
* The request parameters, sorted and concatenated into a normalized
string.
* @return string
*/
public function get_signable_parameters() {
// Grab all parameters
$params = $this->parameters;
// Remove oauth_signature if present
// Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be
excluded.")
if (isset($params['oauth_signature'])) {
unset($params['oauth_signature']);
}
return OAuthUtil::build_http_query($params);
}
/**
* Returns the base string of this request
*
* The base string defined as the method, the url
* and the parameters (normalized), each urlencoded
* and the concated with &.
*/
public function get_signature_base_string() {
$parts = array(
$this->get_normalized_http_method(),
$this->get_normalized_http_url(),
$this->get_signable_parameters()
);
$parts = OAuthUtil::urlencode_rfc3986($parts);
return implode('&', $parts);
}
/**
* just uppercases the http method
*/
public function get_normalized_http_method() {
return strtoupper($this->http_method);
}
/**
* parses the url and rebuilds it to be
* scheme://host/path
*/
public function get_normalized_http_url() {
$parts = parse_url($this->http_url);
$port = @$parts['port'];
$scheme = $parts['scheme'];
$host = $parts['host'];
$path = @$parts['path'];
$port or $port = ($scheme == 'https') ? '443' :
'80';
if (($scheme == 'https' && $port != '443')
|| ($scheme == 'http' && $port !=
'80')) {
$host = "$host:$port";
}
return "$scheme://$host$path";
}
/**
* builds a url usable for a GET request
*/
public function to_url() {
$post_data = $this->to_postdata();
$out = $this->get_normalized_http_url();
if ($post_data) {
$out .= '?'.$post_data;
}
return $out;
}
/**
* builds the data one would send in a POST request
*/
public function to_postdata() {
return OAuthUtil::build_http_query($this->parameters);
}
/**
* builds the Authorization: header
*/
public function to_header($realm=null) {
$first = true;
if($realm) {
$out = 'Authorization: OAuth realm="' .
OAuthUtil::urlencode_rfc3986($realm) . '"';
$first = false;
} else
$out = 'Authorization: OAuth';
$total = array();
foreach ($this->parameters as $k => $v) {
if (substr($k, 0, 5) != "oauth") continue;
if (is_array($v)) {
throw new OAuthException('Arrays not supported in
headers');
}
$out .= ($first) ? ' ' : ',';
$out .= OAuthUtil::urlencode_rfc3986($k) .
'="' .
OAuthUtil::urlencode_rfc3986($v) .
'"';
$first = false;
}
return $out;
}
public function __toString() {
return $this->to_url();
}
public function sign_request($signature_method, $consumer, $token) {
$this->set_parameter(
"oauth_signature_method",
$signature_method->get_name(),
false
);
$signature = $this->build_signature($signature_method, $consumer,
$token);
$this->set_parameter("oauth_signature", $signature,
false);
}
public function build_signature($signature_method, $consumer, $token) {
$signature = $signature_method->build_signature($this, $consumer,
$token);
return $signature;
}
/**
* util function: current timestamp
*/
private static function generate_timestamp() {
return time();
}
/**
* util function: current nonce
*/
private static function generate_nonce() {
$mt = microtime();
$rand = mt_rand();
return md5($mt . $rand); // md5s look nicer than numbers
}
}
class OAuthServer {
protected $timestamp_threshold = 300; // in seconds, five minutes
protected $version = '1.0'; // hi blaine
protected $signature_methods = array();
protected $data_store;
function __construct($data_store) {
$this->data_store = $data_store;
}
public function add_signature_method($signature_method) {
$this->signature_methods[$signature_method->get_name()] =
$signature_method;
}
// high level functions
/**
* process a request_token request
* returns the request token on success
*/
public function fetch_request_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// no token required for the initial token request
$token = NULL;
$this->check_signature($request, $consumer, $token);
// Rev A change
$callback = $request->get_parameter('oauth_callback');
$new_token = $this->data_store->new_request_token($consumer,
$callback);
return $new_token;
}
/**
* process an access_token request
* returns the access token on success
*/
public function fetch_access_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// requires authorized request token
$token = $this->get_token($request, $consumer, "request");
$this->check_signature($request, $consumer, $token);
// Rev A change
$verifier = $request->get_parameter('oauth_verifier');
$new_token = $this->data_store->new_access_token($token,
$consumer, $verifier);
return $new_token;
}
/**
* verify an api call, checks all the parameters
*/
public function verify_request(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
$token = $this->get_token($request, $consumer, "access");
$this->check_signature($request, $consumer, $token);
return array($consumer, $token);
}
// Internals from here
/**
* version 1
*/
private function get_version(&$request) {
$version = $request->get_parameter("oauth_version");
if (!$version) {
// Service Providers MUST assume the protocol version to be 1.0 if
this parameter is not present.
// Chapter 7.0 ("Accessing Protected Ressources")
$version = '1.0';
}
if ($version !== $this->version) {
throw new OAuthException("OAuth version '$version' not
supported");
}
return $version;
}
/**
* figure out the signature with some defaults
*/
private function get_signature_method(&$request) {
$signature_method =
@$request->get_parameter("oauth_signature_method");
if (!$signature_method) {
// According to chapter 7 ("Accessing Protected
Ressources") the signature-method
// parameter is required, and we can't just fallback to
PLAINTEXT
throw new OAuthException('No signature method parameter. This
parameter is required');
}
if (!in_array($signature_method,
array_keys($this->signature_methods))) {
throw new OAuthException(
"Signature method '$signature_method' not supported
" .
"try one of the following: " .
implode(", ", array_keys($this->signature_methods))
);
}
return $this->signature_methods[$signature_method];
}
/**
* try to find the consumer for the provided request's consumer key
*/
private function get_consumer(&$request) {
$consumer_key =
@$request->get_parameter("oauth_consumer_key");
if (!$consumer_key) {
throw new OAuthException("Invalid consumer key");
}
$consumer = $this->data_store->lookup_consumer($consumer_key);
if (!$consumer) {
throw new OAuthException("Invalid consumer");
}
return $consumer;
}
/**
* try to find the token for the provided request's token key
*/
private function get_token(&$request, $consumer,
$token_type="access") {
$token_field = @$request->get_parameter('oauth_token');
$token = $this->data_store->lookup_token(
$consumer, $token_type, $token_field
);
if (!$token) {
throw new OAuthException("Invalid $token_type token:
$token_field");
}
return $token;
}
/**
* all-in-one function to check the signature on a request
* should guess the signature method appropriately
*/
private function check_signature(&$request, $consumer, $token) {
// this should probably be in a different method
$timestamp = @$request->get_parameter('oauth_timestamp');
$nonce = @$request->get_parameter('oauth_nonce');
$this->check_timestamp($timestamp);
$this->check_nonce($consumer, $token, $nonce, $timestamp);
$signature_method = $this->get_signature_method($request);
$signature = $request->get_parameter('oauth_signature');
$valid_sig = $signature_method->check_signature(
$request,
$consumer,
$token,
$signature
);
if (!$valid_sig) {
throw new OAuthException("Invalid signature");
}
}
/**
* check that the timestamp is new enough
*/
private function check_timestamp($timestamp) {
if( ! $timestamp )
throw new OAuthException(
'Missing timestamp parameter. The parameter is required'
);
// verify that timestamp is recentish
$now = time();
if (abs($now - $timestamp) > $this->timestamp_threshold) {
throw new OAuthException(
"Expired timestamp, yours $timestamp, ours $now"
);
}
}
/**
* check that the nonce is not repeated
*/
private function check_nonce($consumer, $token, $nonce, $timestamp) {
if( ! $nonce )
throw new OAuthException(
'Missing nonce parameter. The parameter is required'
);
// verify that the nonce is uniqueish
$found = $this->data_store->lookup_nonce(
$consumer,
$token,
$nonce,
$timestamp
);
if ($found) {
throw new OAuthException("Nonce already used: $nonce");
}
}
}
class OAuthDataStore {
function lookup_consumer($consumer_key) {
// implement me
}
function lookup_token($consumer, $token_type, $token) {
// implement me
}
function lookup_nonce($consumer, $token, $nonce, $timestamp) {
// implement me
}
function new_request_token($consumer, $callback = null) {
// return a new token attached to this consumer
}
function new_access_token($token, $consumer, $verifier = null) {
// return a new access token attached to this consumer
// for the user associated with this token if the request token
// is authorized
// should also invalidate the request token
}
}
class OAuthUtil {
public static function urlencode_rfc3986($input) {
if (is_array($input)) {
return array_map(array('OAuthUtil',
'urlencode_rfc3986'), $input);
} else if (is_scalar($input)) {
return str_replace(
'+',
' ',
str_replace('%7E', '~', rawurlencode($input))
);
} else {
return '';
}
}
// This decode function isn't taking into consideration the above
// modifications to the encoding process. However, this method
doesn't
// seem to be used anywhere so leaving it as is.
public static function urldecode_rfc3986($string) {
return urldecode($string);
}
// Utility function for turning the Authorization: header into
// parameters, has to do some unescaping
// Can filter out any non-oauth parameters if needed (default behaviour)
public static function split_header($header, $only_allow_oauth_parameters
= true) {
$pattern =
'/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
$offset = 0;
$params = array();
while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE,
$offset) > 0) {
$match = $matches[0];
$header_name = $matches[2][0];
$header_content = (isset($matches[5])) ? $matches[5][0] :
$matches[4][0];
if (preg_match('/^oauth_/', $header_name) ||
!$only_allow_oauth_parameters) {
$params[$header_name] =
OAuthUtil::urldecode_rfc3986($header_content);
}
$offset = $match[1] + strlen($match[0]);
}
if (isset($params['realm'])) {
unset($params['realm']);
}
return $params;
}
// helper to try to sort out headers for people who aren't running
apache
public static function get_headers() {
if (function_exists('apache_request_headers')) {
// we need this to get the actual Authorization: header
// because apache tends to tell us it doesn't exist
$headers = apache_request_headers();
// sanitize the output of apache_request_headers because
// we always want the keys to be Cased-Like-This and arh()
// returns the headers in the same case as they are in the
// request
$out = array();
foreach( $headers AS $key => $value ) {
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("-", " ",
$key)))
);
$out[$key] = $value;
}
} else {
// otherwise we don't have apache and are just going to have to
hope
// that $_SERVER actually contains what we need
$out = array();
if( isset($_SERVER['CONTENT_TYPE']) )
$out['Content-Type'] =
$_SERVER['CONTENT_TYPE'];
if( isset($_ENV['CONTENT_TYPE']) )
$out['Content-Type'] = $_ENV['CONTENT_TYPE'];
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
// this is chaos, basically it is just there to capitalize the
first
// letter of every word that is not an initial HTTP and strip
HTTP
// code from przemek
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("_", " ",
substr($key, 5))))
);
$out[$key] = $value;
}
}
}
return $out;
}
// This function takes a input like a=b&a=c&d=e and returns the
parsed
// parameters like this
// array('a' => array('b','c'),
'd' => 'e')
public static function parse_parameters( $input ) {
if (!isset($input) || !$input) return array();
$pairs = explode('&', $input);
$parsed_parameters = array();
foreach ($pairs as $pair) {
$split = explode('=', $pair, 2);
$parameter = OAuthUtil::urldecode_rfc3986($split[0]);
$value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) :
'';
if (isset($parsed_parameters[$parameter])) {
// We have already recieved parameter(s) with this name, so add to
the list
// of parameters with this name
if (is_scalar($parsed_parameters[$parameter])) {
// This is the first duplicate, so transform scalar (string) into
an array
// so we can add the duplicates
$parsed_parameters[$parameter] =
array($parsed_parameters[$parameter]);
}
$parsed_parameters[$parameter][] = $value;
} else {
$parsed_parameters[$parameter] = $value;
}
}
return $parsed_parameters;
}
public static function build_http_query($params) {
if (!$params) return '';
// Urlencode both keys and values
$keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
$values = OAuthUtil::urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
// Parameters are sorted by name, using lexicographical byte value
ordering.
// Ref: Spec: 9.1.1 (1)
uksort($params, 'strcmp');
$pairs = array();
foreach ($params as $parameter => $value) {
if (is_array($value)) {
// If two or more parameters share the same name, they are sorted
by their value
// Ref: Spec: 9.1.1 (1)
natsort($value);
foreach ($value as $duplicate_value) {
$pairs[] = $parameter . '=' . $duplicate_value;
}
} else {
$pairs[] = $parameter . '=' . $value;
}
}
// For each parameter, the name is separated from the corresponding
value by an '=' character (ASCII code 61)
// Each name-value pair is separated by an '&' character
(ASCII code 38)
return implode('&', $pairs);
}
}
tweet/twitteroauth/twitteroauth.php000064400000017372151200771670013733
0ustar00<?php
/**
* @package SP Page Builder
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/
//no direct access
defined ('_JEXEC') or die ('Restricted access');
/*
* Abraham Williams (abraham@abrah.am) http://abrah.am
*
* The first PHP Library to support OAuth for Twitter's REST API.
*/
/* Load OAuth lib. You can find it at http://oauth.net */
require_once('OAuth.php');
/**
* Twitter OAuth class
*/
class TwitterOAuth {
/* Contains the last HTTP status code returned. */
public $http_code;
/* Contains the last API call. */
public $url;
/* Set up the API root URL. */
public $host = "https://api.twitter.com/1.1/";
/* Set timeout default. */
public $timeout = 30;
/* Set connect timeout. */
public $connecttimeout = 30;
/* Verify SSL Cert. */
public $ssl_verifypeer = FALSE;
/* Respons format. */
public $format = 'json';
/* Decode returned json data. */
public $decode_json = TRUE;
/* Contains the last HTTP headers returned. */
public $http_info;
/* Set the useragnet. */
public $useragent = 'TwitterOAuth v0.2.0-beta2';
/* Immediately retry the API call if the response was not successful. */
//public $retry = TRUE;
/**
* Set API URLS
*/
function accessTokenURL() { return
'https://api.twitter.com/oauth/access_token'; }
function authenticateURL() { return
'https://api.twitter.com/oauth/authenticate'; }
function authorizeURL() { return
'https://api.twitter.com/oauth/authorize'; }
function requestTokenURL() { return
'https://api.twitter.com/oauth/request_token'; }
/**
* Debug helpers
*/
function lastStatusCode() { return $this->http_status; }
function lastAPICall() { return $this->last_api_call; }
/**
* construct TwitterOAuth object
*/
function __construct($consumer_key, $consumer_secret, $oauth_token =
NULL, $oauth_token_secret = NULL) {
$this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->consumer = new OAuthConsumer($consumer_key,
$consumer_secret);
if (!empty($oauth_token) && !empty($oauth_token_secret)) {
$this->token = new OAuthConsumer($oauth_token,
$oauth_token_secret);
} else {
$this->token = NULL;
}
}
/**
* Get a request_token from Twitter
*
* @returns a key/value array containing oauth_token and
oauth_token_secret
*/
function getRequestToken($oauth_callback) {
$parameters = array();
$parameters['oauth_callback'] = $oauth_callback;
$request = $this->oAuthRequest($this->requestTokenURL(),
'GET', $parameters);
$token = OAuthUtil::parse_parameters($request);
$this->token = new OAuthConsumer($token['oauth_token'],
$token['oauth_token_secret']);
return $token;
}
/**
* Get the authorize URL
*
* @returns a string
*/
function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) {
if (is_array($token)) {
$token = $token['oauth_token'];
}
if (empty($sign_in_with_twitter)) {
return $this->authorizeURL() . "?oauth_token={$token}";
} else {
return $this->authenticateURL() .
"?oauth_token={$token}";
}
}
/**
* Exchange request token and secret for an access token and
* secret, to sign API calls.
*
* @returns array("oauth_token" =>
"the-access-token",
* "oauth_token_secret" =>
"the-access-secret",
* "user_id" => "9436992",
* "screen_name" => "abraham")
*/
function getAccessToken($oauth_verifier) {
$parameters = array();
$parameters['oauth_verifier'] = $oauth_verifier;
$request = $this->oAuthRequest($this->accessTokenURL(),
'GET', $parameters);
$token = OAuthUtil::parse_parameters($request);
$this->token = new OAuthConsumer($token['oauth_token'],
$token['oauth_token_secret']);
return $token;
}
/**
* One time exchange of username and password for access token and
secret.
*
* @returns array("oauth_token" =>
"the-access-token",
* "oauth_token_secret" =>
"the-access-secret",
* "user_id" => "9436992",
* "screen_name" => "abraham",
* "x_auth_expires" => "0")
*/
function getXAuthToken($username, $password) {
$parameters = array();
$parameters['x_auth_username'] = $username;
$parameters['x_auth_password'] = $password;
$parameters['x_auth_mode'] = 'client_auth';
$request = $this->oAuthRequest($this->accessTokenURL(),
'POST', $parameters);
$token = OAuthUtil::parse_parameters($request);
$this->token = new OAuthConsumer($token['oauth_token'],
$token['oauth_token_secret']);
return $token;
}
/**
* GET wrapper for oAuthRequest.
*/
function get($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'GET', $parameters);
if ($this->format === 'json' &&
$this->decode_json) {
return json_decode($response);
}
return $response;
}
/**
* POST wrapper for oAuthRequest.
*/
function post($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'POST',
$parameters);
if ($this->format === 'json' &&
$this->decode_json) {
return json_decode($response);
}
return $response;
}
/**
* DELETE wrapper for oAuthReqeust.
*/
function delete($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'DELETE',
$parameters);
if ($this->format === 'json' &&
$this->decode_json) {
return json_decode($response);
}
return $response;
}
/**
* Format and sign an OAuth / API request
*/
function oAuthRequest($url, $method, $parameters) {
if (strrpos($url, 'https://') !== 0 && strrpos($url,
'http://') !== 0) {
$url = "{$this->host}{$url}.{$this->format}";
}
$request = OAuthRequest::from_consumer_and_token($this->consumer,
$this->token, $method, $url, $parameters);
$request->sign_request($this->sha1_method, $this->consumer,
$this->token);
switch ($method) {
case 'GET':
return $this->http($request->to_url(), 'GET');
default:
return $this->http($request->get_normalized_http_url(),
$method, $request->to_postdata());
}
}
/**
* Make an HTTP request
*
* @return API results
*/
function http($url, $method, $postfields = NULL) {
$this->http_info = array();
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this,
'getHeader'));
curl_setopt($ci, CURLOPT_HEADER, FALSE);
switch ($method) {
case 'POST':
curl_setopt($ci, CURLOPT_POST, TRUE);
if (!empty($postfields)) {
curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
}
break;
case 'DELETE':
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
if (!empty($postfields)) {
$url = "{$url}?{$postfields}";
}
}
curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info,
curl_getinfo($ci));
$this->url = $url;
curl_close ($ci);
return $response;
}
/**
* Get the header info to store.
*/
function getHeader($ch, $header) {
$i = strpos($header, ':');
if (!empty($i)) {
$key = str_replace('-', '_',
strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2));
$this->http_header[$key] = $value;
}
return strlen($header);
}
}
tweet/twitteroauth/_notes/dwsync.xml000064400000000447151200771670013772
0ustar00<?xml version="1.0" encoding="utf-8"
?>
<dwsync>
<file name="OAuth.php"
server="94.229.171.25/httpdocs/" local="3453861278"
remote="319519907846699440" Dst="-1" />
<file
name="twitteroauth.php"
server="94.229.171.25/httpdocs/" local="3453861278"
remote="319519907846699440" Dst="-1"
/>
</dwsync>