/** * Constructor. * * @param array &$options Log object options. * * @since 11.1 */ public function __construct(array &$options) { // Call the parent constructor. parent::__construct($options); // The name of the text file defaults to 'error.php' if not explicitly given. if (empty($this->options['text_file'])) { $this->options['text_file'] = 'error.php'; } // The name of the text file path defaults to that which is set in configuration if not explicitly given. if (empty($this->options['text_file_path'])) { $this->options['text_file_path'] = Factory::getConfig()->get('log_path'); } // False to treat the log file as a php file. if (empty($this->options['text_file_no_php'])) { $this->options['text_file_no_php'] = false; } // Build the full path to the log file. $this->path = $this->options['text_file_path'] . '/' . $this->options['text_file']; // Use the default entry format unless explicitly set otherwise. if (!empty($this->options['text_entry_format'])) { $this->format = (string) $this->options['text_entry_format']; } // Build the fields array based on the format string. $this->parseFields(); }
/** * Renders a module script and returns the results as a string * * @param mixed $module The name of the module to render * @param array $attribs Associative array of values * @param string $content If present, module information from the buffer will be used * * @return string The output of the script * * @since 11.1 */ public function render($module, $attribs = array(), $content = null) { if (!is_object($module)) { $title = isset($attribs['title']) ? $attribs['title'] : null; $module = JModuleHelper::getModule($module, $title); if (!is_object($module)) { if (is_null($content)) { return ''; } else { /** * If module isn't found in the database but data has been pushed in the buffer * we want to render it */ $tmp = $module; $module = new stdClass(); $module->params = null; $module->module = $tmp; $module->id = 0; $module->user = 0; } } } // Get the user and configuration object // $user = JFactory::getUser(); $conf = Factory::getConfig(); // Set the module content if (!is_null($content)) { $module->content = $content; } // Get module parameters $params = new Registry(); $params->loadString($module->params); // Use parameters from template if (isset($attribs['params'])) { $template_params = new Registry(); $template_params->loadString(html_entity_decode($attribs['params'], ENT_COMPAT, 'UTF-8')); $params->merge($template_params); $module = clone $module; $module->params = (string) $params; } $contents = ''; // Default for compatibility purposes. Set cachemode parameter or use JModuleHelper::moduleCache from within the // module instead $cachemode = $params->get('cachemode', 'oldstatic'); if ($params->get('cache', 0) == 1 && $conf->get('caching') >= 1 && $cachemode != 'id' && $cachemode != 'safeuri') { // Default to itemid creating method and workarounds on $cacheparams = new stdClass(); $cacheparams->cachemode = $cachemode; $cacheparams->class = 'JModuleHelper'; $cacheparams->method = 'renderModule'; $cacheparams->methodparams = array($module, $attribs); $contents = JModuleHelper::ModuleCache($module, $params, $cacheparams); } else { $contents = JModuleHelper::renderModule($module, $attribs); } return $contents; }
/** * Method to get the field input markup. * * @return string The field input markup. * * @since 11.1 */ protected function getInput() { // Initialize some field attributes. $format = $this->element['format'] ? (string) $this->element['format'] : '%Y-%m-%d'; // Build the attributes array. $attributes = array(); if ($this->element['size']) { $attributes['size'] = (int) $this->element['size']; } if ($this->element['maxlength']) { $attributes['maxlength'] = (int) $this->element['maxlength']; } if ($this->element['class']) { $attributes['class'] = (string) $this->element['class']; } if ((string) $this->element['readonly'] == 'true') { $attributes['readonly'] = 'readonly'; } if ((string) $this->element['disabled'] == 'true') { $attributes['disabled'] = 'disabled'; } if ($this->element['onchange']) { $attributes['onchange'] = (string) $this->element['onchange']; } // Handle the special case for "now". if (strtoupper($this->value) == 'NOW') { $this->value = strftime($format); } // Get some system objects. $config = Factory::getConfig(); $user = Factory::getUser(); // If a known filter is given use it. switch (strtoupper((string) $this->element['filter'])) { case 'SERVER_UTC': // Convert a date to UTC based on the server timezone. if ((int) $this->value) { // Get a date object based on the correct timezone. $date = Factory::getDate($this->value, 'UTC'); $date->setTimezone(new DateTimeZone($config->get('offset'))); // Transform the date string. $this->value = $date->format('Y-m-d H:i:s', true, false); } break; case 'USER_UTC': // Convert a date to UTC based on the user timezone. if ((int) $this->value) { // Get a date object based on the correct timezone. $date = Factory::getDate($this->value, 'UTC'); $date->setTimezone(new DateTimeZone($user->getParam('timezone', $config->get('offset')))); // Transform the date string. $this->value = $date->format('Y-m-d H:i:s', true, false); } break; } return Html::_('calendar', $this->value, $this->name, $this->id, $format, $attributes); }
/** * Method to render the view. * * @return string The rendered view. * * @since 1.0 * @throws \RuntimeException */ public function render() { if (Factory::$application->input->get('success', false)) { Factory::$application->enqueueMessage("Sweet! You've setup your database successfully. Check out the <a href=\"news\">Sample Page</a>", 'success'); } $this->renderer->set('success', Factory::$application->input->get('success', false)); $this->renderer->set('logo', DEFAULT_THEME . '/images/logo.png'); $this->renderer->set('config', Factory::getConfig()); return parent::render(); }
/** * Constructor * * @param array $options Optional parameters. * * @since 11.1 * @throws RuntimeException */ public function __construct($options = array()) { if (!self::isSupported()) { throw new RuntimeException('Memcache Extension is not available', 404); } parent::__construct($options); $config = Factory::getConfig(); // This will be an array of loveliness // @todo: multiple servers $this->_servers = array(array('host' => $config->get('memcache_server_host', 'localhost'), 'port' => $config->get('memcache_server_port', 11211))); }
/** * Constructor * * @param array $options options * * @since 11.1 */ public function __construct($options) { $conf = Factory::getConfig(); $this->_options = array('cachebase' => $conf->get('cache_path', JPATH_CACHE), 'lifetime' => (int) $conf->get('cachetime'), 'language' => $conf->get('language', 'en-GB'), 'storage' => $conf->get('cache_handler', ''), 'defaultgroup' => 'default', 'locking' => true, 'locktime' => 15, 'checkTime' => true, 'caching' => $conf->get('caching') >= 1 ? true : false); // Overwrite default options with given options foreach ($options as $option => $value) { if (isset($options[$option]) && $options[$option] !== '') { $this->_options[$option] = $options[$option]; } } if (empty($this->_options['storage'])) { $this->_options['caching'] = false; } }
/** * Method to get the time zone field option groups. * * @return array The field option objects as a nested array in groups. * * @since 11.1 */ protected function getGroups() { $groups = array(); $keyField = $this->element['key_field'] ? (string) $this->element['key_field'] : 'id'; $keyValue = $this->form->getValue($keyField); // If the timezone is not set use the server setting. if (strlen($this->value) == 0 && empty($keyValue)) { $this->value = Factory::getConfig()->get('offset'); } // Get the list of time zones from the server. $zones = DateTimeZone::listIdentifiers(); // Build the group lists. foreach ($zones as $zone) { // Time zones not in a group we will ignore. if (strpos($zone, '/') === false) { continue; } // Get the group/locale from the timezone. list($group, $locale) = explode('/', $zone, 2); // Only use known groups. if (in_array($group, self::$zones)) { // Initialize the group if necessary. if (!isset($groups[$group])) { $groups[$group] = array(); } // Only add options where a locale exists. if (!empty($locale)) { $groups[$group][$zone] = Html::_('select.option', $zone, str_replace('_', ' ', $locale), 'value', 'text', false); } } } // Sort the group lists. ksort($groups); foreach ($groups as $zone => &$location) { sort($location); } // Merge any additional groups in the XML definition. $groups = array_merge(parent::getGroups(), $groups); return $groups; }
/** * Update the database configuration * * @return boolean * * @since 1.0 * @throws \RuntimeException */ public function updateDatabase() { $input = Factory::$application->input; $oldConfig = Factory::getConfig(); $file = JPATH_CONFIGURATION . '/config.json'; // Verify the configuration exists and is readable. if (!is_readable($file)) { throw new \RuntimeException('Configuration file does not exist or is unreadable.'); } $config = json_decode(file_get_contents($file)); $config->database->driver = $input->get('driver', $oldConfig->get('database.driver')); $config->database->user = $input->get('user', $oldConfig->get('database.user')); $config->database->password = $input->get('password', $oldConfig->get('database.password')); $config->database->name = $input->get('name', $oldConfig->get('database.name')); $config->database->host = $input->get('host', $oldConfig->get('database.host')); $config->database->prefix = $input->get('prefix', $oldConfig->get('database.prefix')); file_put_contents($file, json_encode($config)); Factory::$application->loadConfiguration(); if ($input->get('install_sample_data')) { $this->installSampleData(); } return true; }
/** * Validation and filtering * * @return boolean True if satisfactory * * @since 11.1 */ public function check() { // Set user id to null istead of 0, if needed if ($this->id === 0) { $this->id = null; } // Validate user information if (trim($this->name) == '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_PLEASE_ENTER_YOUR_NAME')); return false; } if (trim($this->username) == '') { $this->setError(Text::_('JLIB_DATABASE_ERROR_PLEASE_ENTER_A_USER_NAME')); return false; } if (preg_match("#[<>\"'%;()&]#i", $this->username) || strlen(utf8_decode($this->username)) < 2) { $this->setError(Text::sprintf('JLIB_DATABASE_ERROR_VALID_AZ09', 2)); return false; } if (trim($this->email) == "" || !Helper::isEmailAddress($this->email)) { $this->setError(Text::_('JLIB_DATABASE_ERROR_VALID_MAIL')); return false; } // Set the registration timestamp if (empty($this->registerDate) || $this->registerDate == $this->_db->getNullDate()) { $this->registerDate = Factory::getDate()->toSql(); } // Set the lastvisitDate timestamp if (empty($this->lastvisitDate)) { $this->lastvisitDate = $this->_db->getNullDate(); } // Check for existing username $query = $this->_db->getQuery(true); $query->select($this->_db->quoteName('id')); $query->from($this->_db->quoteName('#__users')); $query->where($this->_db->quoteName('username') . ' = ' . $this->_db->quote($this->username)); $query->where($this->_db->quoteName('id') . ' != ' . (int) $this->id); $this->_db->setQuery($query); $xid = (int) $this->_db->loadResult(); if ($xid && $xid != (int) $this->id) { $this->setError(Text::_('JLIB_DATABASE_ERROR_USERNAME_INUSE')); return false; } // Check for existing email $query->clear(); $query->select($this->_db->quoteName('id')); $query->from($this->_db->quoteName('#__users')); $query->where($this->_db->quoteName('email') . ' = ' . $this->_db->quote($this->email)); $query->where($this->_db->quoteName('id') . ' != ' . (int) $this->id); $this->_db->setQuery($query); $xid = (int) $this->_db->loadResult(); if ($xid && $xid != (int) $this->id) { $this->setError(Text::_('JLIB_DATABASE_ERROR_EMAIL_INUSE')); return false; } // Check for root_user != username $config = Factory::getConfig(); $rootUser = $config->get('root_user'); if (!is_numeric($rootUser)) { $query->clear(); $query->select($this->_db->quoteName('id')); $query->from($this->_db->quoteName('#__users')); $query->where($this->_db->quoteName('username') . ' = ' . $this->_db->quote($rootUser)); $this->_db->setQuery($query); $xid = (int) $this->_db->loadResult(); if ($rootUser == $this->username && (!$xid || $xid && $xid != (int) $this->id) || $xid && $xid == (int) $this->id && $rootUser != $this->username) { $this->setError(Text::_('JLIB_DATABASE_ERROR_USERNAME_CANNOT_CHANGE')); return false; } } return true; }
/** * Returns a cache storage handler object, only creating it * if it doesn't already exist. * * @param string $handler The cache storage handler to instantiate * @param array $options Array of handler options * * @return JCacheStorage A JCacheStorage instance * * @since 11.1 * @throws UnexpectedValueException * @throws RuntimeException */ public static function getInstance($handler = null, $options = array()) { static $now = null; self::addIncludePath(JPATH_PLATFORM . '/joomla/cache/storage'); if (!isset($handler)) { $conf = Factory::getConfig(); $handler = $conf->get('cache_handler'); if (empty($handler)) { throw new UnexpectedValueException('Cache Storage Handler not set.'); } } if (is_null($now)) { $now = time(); } $options['now'] = $now; // We can't cache this since options may change... $handler = strtolower(preg_replace('/[^A-Z0-9_\\.-]/i', '', $handler)); $class = '\\Joomla\\Cache\\Storage'; if (!empty($handler)) { $class .= '\\' . ucfirst($handler); } if (!class_exists($class)) { // Search for the class file in the JCacheStorage include paths. if ($path = Path::find(self::addIncludePath(), strtolower($handler) . '.php')) { include_once $path; } else { throw new RuntimeException(sprintf('Unable to load Cache Storage: %s', $handler)); } } return new $class($options); }
/** * Returns formated date according to a given format and time zone. * * @param string $input String in a format accepted by date(), defaults to "now". * @param string $format The date format specification string (see {@link PHP_MANUAL#date}) * @param mixed $tz Time zone to be used for the date. Special cases: boolean true for user * setting, boolean false for server setting. * @param boolean $gregorian True to use Gregorian calenar * * @return string A date translated by the given format and time zone. * * @see strftime * @since 11.1 */ public static function date($input = 'now', $format = null, $tz = true, $gregorian = false) { // Get some system objects. $config = Factory::getConfig(); $user = Factory::getUser(); // UTC date converted to user time zone. if ($tz === true) { // Get a date object based on UTC. $date = Factory::getDate($input, 'UTC'); // Set the correct time zone based on the user configuration. $date->setTimeZone(new DateTimeZone($user->getParam('timezone', $config->get('offset')))); } elseif ($tz === false) { // Get a date object based on UTC. $date = Factory::getDate($input, 'UTC'); // Set the correct time zone based on the server configuration. $date->setTimeZone(new DateTimeZone($config->get('offset'))); } elseif ($tz === null) { $date = Factory::getDate($input); } else { // Get a date object based on UTC. $date = Factory::getDate($input, 'UTC'); // Set the correct time zone based on the server configuration. $date->setTimeZone(new DateTimeZone($tz)); } // If no format is given use the default locale based format. if (!$format) { $format = Text::_('DATE_FORMAT_LC1'); } elseif (Factory::getLanguage()->hasKey($format)) { $format = Text::_($format); } if ($gregorian) { return $date->format($format, true); } else { return $date->calendar($format, true); } }
/** * Keep session alive, for example, while editing or creating an article. * * @return void * * @since 11.1 */ public static function keepalive() { // Only load once if (isset(self::$loaded[__METHOD__])) { return; } // Include MooTools framework self::framework(); $config = Factory::getConfig(); $lifetime = $config->get('lifetime') * 60000; $refreshTime = $lifetime <= 60000 ? 30000 : $lifetime - 60000; // Refresh time is 1 minute less than the liftime assined in the configuration.php file. // The longest refresh period is one hour to prevent integer overflow. if ($refreshTime > 3600000 || $refreshTime <= 0) { $refreshTime = 3600000; } $document = Factory::getDocument(); $script = ''; $script .= 'function keepAlive() {'; $script .= ' var myAjax = new Request({method: "get", url: "index.php"}).send();'; $script .= '}'; $script .= ' window.addEvent("domready", function()'; $script .= '{ keepAlive.periodical(' . $refreshTime . '); }'; $script .= ');'; $document->addScriptDeclaration($script); self::$loaded[__METHOD__] = true; return; }
/** * Test to see if the cache storage is available. * * @return boolean True on success, false otherwise. * * @since 12.1 */ public static function isSupported() { if ((extension_loaded('memcached') && class_exists('Memcached')) != true) { return false; } $config = Factory::getConfig(); $host = $config->get('memcache_server_host', 'localhost'); $port = $config->get('memcache_server_port', 11211); $memcached = new \Memcached(); $memcachedtest = @$memcached->addServer($host, $port); if (!$memcachedtest) { return false; } else { return true; } }
/** * Object constructor to set table and key fields. In most cases this will * be overridden by child classes to explicitly set the table and key fields * for a particular database table. * * @param string $table Name of the table to model. * @param mixed $key Name of the primary key field in the table or array of field names that compose the primary key. * @param Driver $db Driver object. * * @since 11.1 */ public function __construct($table, $key, Driver $db) { // Set internal variables. $this->_tbl = $table; // Set the key to be an array. if (is_string($key)) { $key = array($key); } elseif (is_object($key)) { $key = (array) $key; } $this->_tbl_keys = $key; if (count($key) == 1) { $this->_autoincrement = true; } else { $this->_autoincrement = false; } // Set the singular table key for backwards compatibility. $this->_tbl_key = $this->getKeyName(); $this->_db = $db; // Initialise the table properties. $fields = $this->getFields(); if ($fields) { foreach ($fields as $name => $v) { // Add the field if it is not already present. if (!property_exists($this, $name)) { $this->{$name} = null; } } } // If we are tracking assets, make sure an access field exists and initially set the default. if (property_exists($this, 'asset_id')) { $this->_trackAssets = true; } // If the access property exists, set the default. if (property_exists($this, 'access')) { $this->access = (int) Factory::getConfig()->get('access'); } }
/** * Returns the base URI for the request. * * @param boolean $pathonly If false, prepend the scheme, host and port information. Default is false. * * @return string The base URI string * * @since 11.1 */ public static function base($pathonly = false) { // Get the base request path. if (empty(self::$base)) { $config = Factory::getConfig(); $live_site = $config->get('live_site'); if (trim($live_site) != '') { $uri = self::getInstance($live_site); self::$base['prefix'] = $uri->toString(array('scheme', 'host', 'port')); self::$base['path'] = rtrim($uri->toString(array('path')), '/\\'); if (defined('JPATH_BASE') && defined('JPATH_ADMINISTRATOR')) { if (JPATH_BASE == JPATH_ADMINISTRATOR) { self::$base['path'] .= '/administrator'; } } } else { $uri = self::getInstance(); self::$base['prefix'] = $uri->toString(array('scheme', 'host', 'port')); if (strpos(php_sapi_name(), 'cgi') !== false && !ini_get('cgi.fix_pathinfo') && !empty($_SERVER['REQUEST_URI'])) { // PHP-CGI on Apache with "cgi.fix_pathinfo = 0" // We shouldn't have user-supplied PATH_INFO in PHP_SELF in this case // because PHP will not work with PATH_INFO at all. $script_name = $_SERVER['PHP_SELF']; } else { // Others $script_name = $_SERVER['SCRIPT_NAME']; } self::$base['path'] = rtrim(dirname($script_name), '/\\'); } } return $pathonly === false ? self::$base['prefix'] . self::$base['path'] . '/' : self::$base['path']; }
/** * Extract an archive file to a directory. * * @param string $archivename The name of the archive file * @param string $extractdir Directory to unpack into * * @return boolean True for success * * @since 11.1 * @throws InvalidArgumentException */ public static function extract($archivename, $extractdir) { $untar = false; $result = false; $ext = File::getExt(strtolower($archivename)); // Check if a tar is embedded...gzip/bzip2 can just be plain files! if (File::getExt(File::stripExt(strtolower($archivename))) == 'tar') { $untar = true; } switch ($ext) { case 'zip': $adapter = self::getAdapter('zip'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tar': $adapter = self::getAdapter('tar'); if ($adapter) { $result = $adapter->extract($archivename, $extractdir); } break; case 'tgz': // This format is a tarball gzip'd $untar = true; case 'gz': case 'gzip': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('gzip'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('gzip'); $gzresult = $adapter->extract($archivename, $tmpfname); if ($gzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; case 'tbz2': // This format is a tarball bzip2'd $untar = true; case 'bz2': case 'bzip2': // This may just be an individual file (e.g. sql script) $adapter = self::getAdapter('bzip2'); if ($adapter) { $config = Factory::getConfig(); $tmpfname = $config->get('tmp_path') . '/' . uniqid('bzip2'); $bzresult = $adapter->extract($archivename, $tmpfname); if ($bzresult instanceof Exception) { @unlink($tmpfname); return false; } if ($untar) { // Try to untar the file $tadapter = self::getAdapter('tar'); if ($tadapter) { $result = $tadapter->extract($tmpfname, $extractdir); } } else { $path = Path::clean($extractdir); Folder::create($path); $result = File::copy($tmpfname, $path . '/' . File::stripExt(basename(strtolower($archivename))), null, 1); } @unlink($tmpfname); } break; default: throw new InvalidArgumentException('Unknown Archive Type'); } if (!$result || $result instanceof Exception) { return false; } return true; }
/** * Set session cookie parameters * * @return void * * @since 11.1 */ protected function _setCookieParams() { $cookie = session_get_cookie_params(); if ($this->_force_ssl) { $cookie['secure'] = true; } $config = Factory::getConfig(); if ($config->get('cookie_domain', '') != '') { $cookie['domain'] = $config->get('cookie_domain'); } if ($config->get('cookie_path', '') != '') { $cookie['path'] = $config->get('cookie_path'); } session_set_cookie_params($cookie['lifetime'], $cookie['path'], $cookie['domain'], $cookie['secure'], true); }
/** * Method to check JUser object authorisation against an access control * object and optionally an access extension object * * @param string $action The name of the action to check for permission. * @param string $assetname The name of the asset on which to perform the action. * * @return boolean True if authorised * * @since 11.1 */ public function authorise($action, $assetname = null) { // Make sure we only check for core.admin once during the run. if ($this->isRoot === null) { $this->isRoot = false; // Check for the configuration file failsafe. $config = Factory::getConfig(); $rootUser = $config->get('root_user'); // The root_user variable can be a numeric user ID or a username. if (is_numeric($rootUser) && $this->id > 0 && $this->id == $rootUser) { $this->isRoot = true; } elseif ($this->username && $this->username == $rootUser) { $this->isRoot = true; } else { // Get all groups against which the user is mapped. $identities = $this->getAuthorisedGroups(); array_unshift($identities, $this->id * -1); if (Access::getAssetRules(1)->allow('core.admin', $identities)) { $this->isRoot = true; return true; } } } return $this->isRoot ? true : Access::check($this->id, $action, $assetname); }
/** * Method to determine if client login credentials are present * * @param string $client Client name, currently only 'ftp' is supported * * @return boolean True if login credentials are available * * @since 11.1 */ public static function hasCredentials($client) { $return = false; $client = strtolower($client); // Get (unmodified) credentials for this client switch ($client) { case 'ftp': $config = Factory::getConfig(); $options = array('enabled' => $config->get('ftp_enable'), 'user' => $config->get('ftp_user'), 'pass' => $config->get('ftp_pass')); break; default: $options = array('enabled' => false, 'user' => '', 'pass' => ''); break; } if ($options['enabled'] == false) { // The client is disabled in global config, so let's pretend we are OK $return = true; } elseif ($options['user'] != '' && $options['pass'] != '') { // Login credentials are available in global config $return = true; } else { // Check if login credentials are available in the session $session = Factory::getSession(); $user = $session->get($client . '.user', null, 'JClientHelper'); $pass = $session->get($client . '.pass', null, 'JClientHelper'); if ($user != '' && $pass != '') { $return = true; } } return $return; }
/** * Method to apply an input filter to a value based on field data. * * @param string $element The XML element object representation of the form field. * @param mixed $value The value to filter for the field. * * @return mixed The filtered value. * * @since 11.1 */ protected function filterField($element, $value) { // Make sure there is a valid SimpleXMLElement. if (!$element instanceof SimpleXMLElement) { return false; } // Get the field filter type. $filter = (string) $element['filter']; // Process the input value based on the filter. $return = null; switch (strtoupper($filter)) { // Access Control Rules. case 'RULES': $return = array(); foreach ((array) $value as $action => $ids) { // Build the rules array. $return[$action] = array(); foreach ($ids as $id => $p) { if ($p !== '') { $return[$action][$id] = $p == '1' || $p == 'true' ? true : false; } } } break; // Do nothing, thus leaving the return value as null. // Do nothing, thus leaving the return value as null. case 'UNSET': break; // No Filter. // No Filter. case 'RAW': $return = $value; break; // Filter the input as an array of integers. // Filter the input as an array of integers. case 'INT_ARRAY': // Make sure the input is an array. if (is_object($value)) { $value = get_object_vars($value); } $value = is_array($value) ? $value : array($value); ArrayHelper::toInteger($value); $return = $value; break; // Filter safe HTML. // Filter safe HTML. case 'SAFEHTML': $return = Input::getInstance(null, null, 1, 1)->clean($value, 'string'); break; // Convert a date to UTC based on the server timezone offset. // Convert a date to UTC based on the server timezone offset. case 'SERVER_UTC': if ((int) $value > 0) { // Get the server timezone setting. $offset = Factory::getConfig()->get('offset'); // Return an SQL formatted datetime string in UTC. $return = Factory::getDate($value, $offset)->toSql(); } else { $return = ''; } break; // Convert a date to UTC based on the user timezone offset. // Convert a date to UTC based on the user timezone offset. case 'USER_UTC': if ((int) $value > 0) { // Get the user timezone setting defaulting to the server timezone setting. $offset = Factory::getUser()->getParam('timezone', Factory::getConfig()->get('offset')); // Return a MySQL formatted datetime string in UTC. $return = Factory::getDate($value, $offset)->toSql(); } else { $return = ''; } break; // Ensures a protocol is present in the saved field. Only use when // the only permitted protocols requre '://'. See JFormRuleUrl for list of these. // Ensures a protocol is present in the saved field. Only use when // the only permitted protocols requre '://'. See JFormRuleUrl for list of these. case 'URL': if (empty($value)) { return; } $value = Input::getInstance()->clean($value, 'html'); $value = trim($value); // Check for a protocol $protocol = parse_url($value, PHP_URL_SCHEME); // If there is no protocol and the relative option is not specified, // we assume that it is an external URL and prepend http://. if ($element['type'] == 'url' && !$protocol && !$element['relative'] || !$element['type'] == 'url' && !$protocol) { $protocol = 'http'; // If it looks like an internal link, then add the root. if (substr($value, 0) == 'index.php') { $value = Uri::root() . $value; } // Otherwise we treat it is an external link. // Put the url back together. $value = $protocol . '://' . $value; } elseif (!$protocol && $element['relative']) { $host = Uri::getInstance('SERVER')->gethost(); // If it starts with the host string, just prepend the protocol. if (substr($value, 0) == $host) { $value = 'http://' . $value; } else { $value = Uri::root() . $value; } } $return = $value; break; case 'TEL': $value = trim($value); // Does it match the NANP pattern? if (preg_match('/^(?:\\+?1[-. ]?)?\\(?([2-9][0-8][0-9])\\)?[-. ]?([2-9][0-9]{2})[-. ]?([0-9]{4})$/', $value) == 1) { $number = (string) preg_replace('/[^\\d]/', '', $value); if (substr($number, 0, 1) == 1) { $number = substr($number, 1); } if (substr($number, 0, 2) == '+1') { $number = substr($number, 2); } $result = '1.' . $number; } elseif (preg_match('/^\\+(?:[0-9] ?){6,14}[0-9]$/', $value) == 1) { $countrycode = substr($value, 0, strpos($value, ' ')); $countrycode = (string) preg_replace('/[^\\d]/', '', $countrycode); $number = strstr($value, ' '); $number = (string) preg_replace('/[^\\d]/', '', $number); $result = $countrycode . '.' . $number; } elseif (preg_match('/^\\+[0-9]{1,3}\\.[0-9]{4,14}(?:x.+)?$/', $value) == 1) { if (strstr($value, 'x')) { $xpos = strpos($value, 'x'); $value = substr($value, 0, $xpos); } $result = str_replace('+', '', $value); } elseif (preg_match('/[0-9]{1,3}\\.[0-9]{4,14}$/', $value) == 1) { $result = $value; } else { $value = (string) preg_replace('/[^\\d]/', '', $value); if ($value != null && strlen($value) <= 15) { $length = strlen($value); // If it is fewer than 13 digits assume it is a local number if ($length <= 12) { $result = '.' . $value; } else { // If it has 13 or more digits let's make a country code. $cclen = $length - 12; $result = substr($value, 0, $cclen) . '.' . substr($value, $cclen); } } else { $result = ''; } } $return = $result; break; default: // Check for a callback filter. if (strpos($filter, '::') !== false && is_callable(explode('::', $filter))) { $return = call_user_func(explode('::', $filter), $value); } elseif (function_exists($filter)) { $return = call_user_func($filter, $value); } else { $return = Input::getInstance()->clean($value, $filter); } break; } return $return; }
/** * Test to see if the cache storage is available. * * @return boolean True on success, false otherwise. * * @since 12.1 */ public static function isSupported() { $conf = Factory::getConfig(); return is_writable($conf->get('cache_path', JPATH_CACHE)); }
/** * Returns a published state on a grid * * @param integer $value The state value. * @param integer $i The row index * @param string|array $prefix An optional task prefix or an array of options * @param boolean $enabled An optional setting for access control on the action. * @param string $checkbox An optional prefix for checkboxes. * @param string $publish_up An optional start publishing date. * @param string $publish_down An optional finish publishing date. * * @return string The Html code * * @see JHtmlJGrid::state * @since 11.1 */ public static function published($value, $i, $prefix = '', $enabled = true, $checkbox = 'cb', $publish_up = null, $publish_down = null) { if (is_array($prefix)) { $options = $prefix; $enabled = array_key_exists('enabled', $options) ? $options['enabled'] : $enabled; $checkbox = array_key_exists('checkbox', $options) ? $options['checkbox'] : $checkbox; $prefix = array_key_exists('prefix', $options) ? $options['prefix'] : ''; } $states = array(1 => array('unpublish', 'JPUBLISHED', 'JLIB_HTML_UNPUBLISH_ITEM', 'JPUBLISHED', false, 'publish', 'publish'), 0 => array('publish', 'JUNPUBLISHED', 'JLIB_HTML_PUBLISH_ITEM', 'JUNPUBLISHED', false, 'unpublish', 'unpublish'), 2 => array('unpublish', 'JARCHIVED', 'JLIB_HTML_UNPUBLISH_ITEM', 'JARCHIVED', false, 'archive', 'archive'), -2 => array('publish', 'JTRASHED', 'JLIB_HTML_PUBLISH_ITEM', 'JTRASHED', false, 'trash', 'trash')); // Special state for dates if ($publish_up || $publish_down) { $nullDate = Factory::getDBO()->getNullDate(); $nowDate = Factory::getDate()->toUnix(); $tz = new DateTimeZone(Factory::getUser()->getParam('timezone', Factory::getConfig()->get('offset'))); $publish_up = $publish_up != $nullDate ? Factory::getDate($publish_up, 'UTC')->setTimeZone($tz) : false; $publish_down = $publish_down != $nullDate ? Factory::getDate($publish_down, 'UTC')->setTimeZone($tz) : false; // Create tip text, only we have publish up or down settings $tips = array(); if ($publish_up) { $tips[] = Text::sprintf('JLIB_HTML_PUBLISHED_START', $publish_up->format(Date::$format, true)); } if ($publish_down) { $tips[] = Text::sprintf('JLIB_HTML_PUBLISHED_FINISHED', $publish_down->format(Date::$format, true)); } $tip = empty($tips) ? false : implode('<br/>', $tips); // Add tips and special titles foreach ($states as $key => $state) { // Create special titles for published items if ($key == 1) { $states[$key][2] = $states[$key][3] = 'JLIB_HTML_PUBLISHED_ITEM'; if ($publish_up > $nullDate && $nowDate < $publish_up->toUnix()) { $states[$key][2] = $states[$key][3] = 'JLIB_HTML_PUBLISHED_PENDING_ITEM'; $states[$key][5] = $states[$key][6] = 'pending'; } if ($publish_down > $nullDate && $nowDate > $publish_down->toUnix()) { $states[$key][2] = $states[$key][3] = 'JLIB_HTML_PUBLISHED_EXPIRED_ITEM'; $states[$key][5] = $states[$key][6] = 'expired'; } } // Add tips to titles if ($tip) { $states[$key][1] = Text::_($states[$key][1]); $states[$key][2] = Text::_($states[$key][2]) . '::' . $tip; $states[$key][3] = Text::_($states[$key][3]) . '::' . $tip; $states[$key][4] = true; } } return self::state($states, $value, $i, array('prefix' => $prefix, 'translate' => !$tip), $enabled, true, $checkbox); } return self::state($states, $value, $i, $prefix, $enabled, true, $checkbox); }