Remove trailing whitespace

This commit is contained in:
Kijin Sung 2023-01-17 20:57:44 +09:00
parent 3b0030e82b
commit a9f72a5cd2
81 changed files with 2455 additions and 2455 deletions

View file

@ -107,7 +107,7 @@ spl_autoload_register(function($class_name)
$filename2 = null; $filename2 = null;
$lang_plugin = null; $lang_plugin = null;
$lang_path = null; $lang_path = null;
// Try namespaced classes, legacy classes, and module classes. // Try namespaced classes, legacy classes, and module classes.
if (preg_match('!^Rhymix/(Framework|Addons|Modules|Plugins|Themes|Widgets)/((\w+)/(?:\w+/)*)?(\w+)$!', $class_name, $matches)) if (preg_match('!^Rhymix/(Framework|Addons|Modules|Plugins|Themes|Widgets)/((\w+)/(?:\w+/)*)?(\w+)$!', $class_name, $matches))
{ {
@ -136,7 +136,7 @@ spl_autoload_register(function($class_name)
$lang_path = RX_BASEDIR . 'modules/' . $module . '/lang'; $lang_path = RX_BASEDIR . 'modules/' . $module . '/lang';
} }
} }
// Load the PHP file. // Load the PHP file.
if ($filename1 && file_exists($filename1)) if ($filename1 && file_exists($filename1))
{ {
@ -146,7 +146,7 @@ spl_autoload_register(function($class_name)
{ {
include $filename2; include $filename2;
} }
// Load the lang file for the plugin. // Load the lang file for the plugin.
if ($lang_plugin) if ($lang_plugin)
{ {

View file

@ -12,25 +12,25 @@ class Cache
*/ */
protected static $_driver = null; protected static $_driver = null;
protected static $_driver_name = null; protected static $_driver_name = null;
/** /**
* The cache prefix. * The cache prefix.
*/ */
protected static $_prefix = null; protected static $_prefix = null;
/** /**
* The default TTL. * The default TTL.
*/ */
protected static $_ttl = 86400; protected static $_ttl = 86400;
/** /**
* Cache group versions. * Cache group versions.
*/ */
protected static $_group_versions = array(); protected static $_group_versions = array();
/** /**
* Initialize the cache system. * Initialize the cache system.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
@ -40,7 +40,7 @@ class Cache
{ {
$config = array($config); $config = array($config);
} }
if (isset($config['type'])) if (isset($config['type']))
{ {
$driver_name = $config['type']; $driver_name = $config['type'];
@ -61,7 +61,7 @@ class Cache
$driver_name = null; $driver_name = null;
$class_name = null; $class_name = null;
} }
if ($class_name !== null && $driver_name !== 'file' && class_exists($class_name) && $class_name::isSupported()) if ($class_name !== null && $driver_name !== 'file' && class_exists($class_name) && $class_name::isSupported())
{ {
self::$_driver = $class_name::getInstance($config); self::$_driver = $class_name::getInstance($config);
@ -72,7 +72,7 @@ class Cache
self::$_driver = Drivers\Cache\Dummy::getInstance(array()); self::$_driver = Drivers\Cache\Dummy::getInstance(array());
self::$_driver_name = 'dummy'; self::$_driver_name = 'dummy';
} }
if (self::$_driver->prefix) if (self::$_driver->prefix)
{ {
self::$_prefix = substr(sha1(\RX_BASEDIR), 0, 10) . ':' . \RX_VERSION . ':'; self::$_prefix = substr(sha1(\RX_BASEDIR), 0, 10) . ':' . \RX_VERSION . ':';
@ -81,13 +81,13 @@ class Cache
{ {
self::$_prefix = \RX_VERSION . ':'; self::$_prefix = \RX_VERSION . ':';
} }
return self::$_driver; return self::$_driver;
} }
/** /**
* Get the list of supported cache drivers. * Get the list of supported cache drivers.
* *
* @return array * @return array
*/ */
public static function getSupportedDrivers() public static function getSupportedDrivers()
@ -104,20 +104,20 @@ class Cache
} }
return $result; return $result;
} }
/** /**
* Get the name of the currently enabled cache driver. * Get the name of the currently enabled cache driver.
* *
* @return string|null * @return string|null
*/ */
public static function getDriverName() public static function getDriverName()
{ {
return self::$_driver_name; return self::$_driver_name;
} }
/** /**
* Get the currently enabled cache driver, or a named driver with the given settings. * Get the currently enabled cache driver, or a named driver with the given settings.
* *
* @param string $name (optional) * @param string $name (optional)
* @param array $config (optional) * @param array $config (optional)
* @return object|null * @return object|null
@ -141,30 +141,30 @@ class Cache
} }
} }
} }
/** /**
* Get the automatically generated cache prefix for this installation of Rhymix. * Get the automatically generated cache prefix for this installation of Rhymix.
* *
* @return object|null * @return object|null
*/ */
public static function getPrefix() public static function getPrefix()
{ {
return self::$_prefix; return self::$_prefix;
} }
/** /**
* Get the default TTL. * Get the default TTL.
* *
* @return int * @return int
*/ */
public static function getDefaultTTL() public static function getDefaultTTL()
{ {
return self::$_ttl; return self::$_ttl;
} }
/** /**
* Set the default TTL. * Set the default TTL.
* *
* @param int $ttl * @param int $ttl
* @return void * @return void
*/ */
@ -172,12 +172,12 @@ class Cache
{ {
self::$_ttl = $ttl; self::$_ttl = $ttl;
} }
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -192,14 +192,14 @@ class Cache
return null; return null;
} }
} }
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is not given, the default TTL is used. * $ttl is measured in seconds. If it is not given, the default TTL is used.
* $force is used to cache essential data when using the default driver. * $force is used to cache essential data when using the default driver.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl (optional) * @param int $ttl (optional)
@ -226,13 +226,13 @@ class Cache
return false; return false;
} }
} }
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -247,12 +247,12 @@ class Cache
return false; return false;
} }
} }
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -267,13 +267,13 @@ class Cache
return false; return false;
} }
} }
/** /**
* Increase the value of a key by $amount. * Increase the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value, or -1 on failure. * This method returns the new value, or -1 on failure.
* *
* @param string $key * @param string $key
* @param int $amount (optional) * @param int $amount (optional)
* @return int * @return int
@ -289,13 +289,13 @@ class Cache
return -1; return -1;
} }
} }
/** /**
* Decrease the value of a key by $amount. * Decrease the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value, or -1 on failure. * This method returns the new value, or -1 on failure.
* *
* @param string $key * @param string $key
* @param int $amount (optional) * @param int $amount (optional)
* @return int * @return int
@ -311,12 +311,12 @@ class Cache
return -1; return -1;
} }
} }
/** /**
* Clear a group of keys from the cache. * Clear a group of keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $group_name * @param string $group_name
* @return bool * @return bool
*/ */
@ -333,12 +333,12 @@ class Cache
return false; return false;
} }
} }
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function clearAll(): bool public static function clearAll(): bool
@ -352,10 +352,10 @@ class Cache
return false; return false;
} }
} }
/** /**
* Get the group version. * Get the group version.
* *
* @param string $group_name * @param string $group_name
* @return int * @return int
*/ */
@ -377,10 +377,10 @@ class Cache
} }
} }
} }
/** /**
* Get the actual key used by Rhymix. * Get the actual key used by Rhymix.
* *
* @param string $key * @param string $key
* @return string * @return string
*/ */
@ -390,7 +390,7 @@ class Cache
{ {
$key = $matches[1] . '#' . self::getGroupVersion($matches[1]) . ':' . $matches[2]; $key = $matches[1] . '#' . self::getGroupVersion($matches[1]) . ':' . $matches[2];
} }
return self::$_prefix . $key; return self::$_prefix . $key;
} }
} }

View file

@ -9,7 +9,7 @@ class Calendar
{ {
/** /**
* This method returns the English name of a month, e.g. 9 = 'September'. * This method returns the English name of a month, e.g. 9 = 'September'.
* *
* @param int $month_number * @param int $month_number
* @param bool $long_format (optional, default is true) * @param bool $long_format (optional, default is true)
* @return string * @return string
@ -21,16 +21,16 @@ class Calendar
{ {
return false; return false;
} }
return date($long_format ? 'F' : 'M', mktime(0, 0, 0, $month_number, 1)); return date($long_format ? 'F' : 'M', mktime(0, 0, 0, $month_number, 1));
} }
/** /**
* This method returns the day on which a month begins. * This method returns the day on which a month begins.
* *
* 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday. * 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday.
* If you do not specify a year, the current year is assumed. * If you do not specify a year, the current year is assumed.
* *
* @param int $month_number * @param int $month_number
* @param int $year (optional) * @param int $year (optional)
* @return int * @return int
@ -42,16 +42,16 @@ class Calendar
{ {
return false; return false;
} }
return (int)date('w', mktime(0, 0, 0, $month_number, 1, $year ?: date('Y'))); return (int)date('w', mktime(0, 0, 0, $month_number, 1, $year ?: date('Y')));
} }
/** /**
* This method returns the number of days in a month, e.g. February 2016 has 29 days. * This method returns the number of days in a month, e.g. February 2016 has 29 days.
* *
* If you do not specify a year, the current year is assumed. * If you do not specify a year, the current year is assumed.
* You must specify a year to get the number of days in February. * You must specify a year to get the number of days in February.
* *
* @param int $month_number * @param int $month_number
* @param int $year (optional) * @param int $year (optional)
* @return int * @return int
@ -63,19 +63,19 @@ class Calendar
{ {
return false; return false;
} }
return (int)date('t', mktime(0, 0, 0, $month_number, 1, $year ?: date('Y'))); return (int)date('t', mktime(0, 0, 0, $month_number, 1, $year ?: date('Y')));
} }
/** /**
* This method returns a complete calendar for a month. * This method returns a complete calendar for a month.
* *
* The return value is an array with six members, each representing a week. * The return value is an array with six members, each representing a week.
* Each week is an array with seven members, each representing a day. * Each week is an array with seven members, each representing a day.
* 6 weeks are returned. Empty cells are represented by nulls. * 6 weeks are returned. Empty cells are represented by nulls.
* *
* If you do not specify a year, the current year is assumed. * If you do not specify a year, the current year is assumed.
* *
* @param int $month_number * @param int $month_number
* @param int $year (optional) * @param int $year (optional)
* @param int $start_dow (optional) * @param int $start_dow (optional)
@ -96,13 +96,13 @@ class Calendar
{ {
$year = date('Y'); $year = date('Y');
} }
$start = self::getMonthStartDayOfWeek($month_number, $year); $start = self::getMonthStartDayOfWeek($month_number, $year);
$count = self::getMonthDays($month_number, $year); $count = self::getMonthDays($month_number, $year);
$initial_blank_cells = (7 + $start - $start_dow) % 7; $initial_blank_cells = (7 + $start - $start_dow) % 7;
$final_blank_cells = 42 - $count - $initial_blank_cells; $final_blank_cells = 42 - $count - $initial_blank_cells;
$temp = array(); $temp = array();
for ($i = 0; $i < $initial_blank_cells; $i++) for ($i = 0; $i < $initial_blank_cells; $i++)
{ {
$temp[] = null; $temp[] = null;
@ -115,7 +115,7 @@ class Calendar
{ {
$temp[] = null; $temp[] = null;
} }
$return = array(); $return = array();
for ($i = 0; $i < 6; $i++) for ($i = 0; $i < 6; $i++)
{ {
@ -126,7 +126,7 @@ class Calendar
} }
$return[] = $week; $return[] = $week;
} }
return $return; return $return;
} }
} }

View file

@ -11,7 +11,7 @@ class Config
* System configuration is stored here. * System configuration is stored here.
*/ */
protected static $_config = array(); protected static $_config = array();
/** /**
* Location of configuration files. * Location of configuration files.
*/ */
@ -20,10 +20,10 @@ class Config
public static $old_ftp_config_filename = 'files/config/ftp.config.php'; public static $old_ftp_config_filename = 'files/config/ftp.config.php';
public static $old_lang_config_filename = 'files/config/lang_selected.info'; public static $old_lang_config_filename = 'files/config/lang_selected.info';
public static $default_config_filename = 'common/defaults/config.php'; public static $default_config_filename = 'common/defaults/config.php';
/** /**
* Load system configuration. * Load system configuration.
* *
* @return void * @return void
*/ */
public static function init() public static function init()
@ -43,30 +43,30 @@ class Config
} }
return self::$_config; return self::$_config;
} }
/** /**
* Get all system configuration. * Get all system configuration.
* *
* @return array * @return array
*/ */
public static function getAll() public static function getAll()
{ {
return self::$_config; return self::$_config;
} }
/** /**
* Get default system configuration. * Get default system configuration.
* *
* @return array * @return array
*/ */
public static function getDefaults() public static function getDefaults()
{ {
return (include \RX_BASEDIR . self::$default_config_filename); return (include \RX_BASEDIR . self::$default_config_filename);
} }
/** /**
* Get a system configuration value. * Get a system configuration value.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -88,10 +88,10 @@ class Config
} }
return $data; return $data;
} }
/** /**
* Set a system configuration value. * Set a system configuration value.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @return void * @return void
@ -110,10 +110,10 @@ class Config
} }
$data = $value; $data = $value;
} }
/** /**
* Set all system configuration. * Set all system configuration.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
@ -121,10 +121,10 @@ class Config
{ {
self::$_config = $config; self::$_config = $config;
} }
/** /**
* Save the current system configuration. * Save the current system configuration.
* *
* @param array $config (optional) * @param array $config (optional)
* @return bool * @return bool
*/ */
@ -134,7 +134,7 @@ class Config
{ {
self::setAll($config); self::setAll($config);
} }
// Backup the main config file. // Backup the main config file.
$config_filename = \RX_BASEDIR . self::$config_filename; $config_filename = \RX_BASEDIR . self::$config_filename;
if (Storage::exists($config_filename)) if (Storage::exists($config_filename))
@ -147,7 +147,7 @@ class Config
return false; return false;
} }
} }
// Save the main config file. // Save the main config file.
$buff = '<?php' . "\n" . '// Rhymix System Configuration' . "\n" . 'return ' . self::serialize(self::$_config) . ';' . "\n"; $buff = '<?php' . "\n" . '// Rhymix System Configuration' . "\n" . 'return ' . self::serialize(self::$_config) . ';' . "\n";
$result = Storage::write($config_filename, $buff) ? true : false; $result = Storage::write($config_filename, $buff) ? true : false;
@ -156,10 +156,10 @@ class Config
{ {
return false; return false;
} }
// Remove the backup file. // Remove the backup file.
Storage::delete($backup_filename); Storage::delete($backup_filename);
// Save XE-compatible config files. // Save XE-compatible config files.
$warning = '// THIS FILE IS NOT USED IN RHYMIX.' . "\n" . '// TO MODIFY SYSTEM CONFIGURATION, EDIT config.php INSTEAD.'; $warning = '// THIS FILE IS NOT USED IN RHYMIX.' . "\n" . '// TO MODIFY SYSTEM CONFIGURATION, EDIT config.php INSTEAD.';
$buff = '<?php' . "\n" . $warning . "\n"; $buff = '<?php' . "\n" . $warning . "\n";
@ -167,10 +167,10 @@ class Config
Storage::write(\RX_BASEDIR . self::$old_ftp_config_filename, $buff); Storage::write(\RX_BASEDIR . self::$old_ftp_config_filename, $buff);
return true; return true;
} }
/** /**
* Serialize a value for insertion into a PHP-based configuration file. * Serialize a value for insertion into a PHP-based configuration file.
* *
* @param mixed $value * @param mixed $value
* @return string * @return string
*/ */

File diff suppressed because it is too large Load diff

View file

@ -11,10 +11,10 @@ class DateTime
* Time zone objects and settings are cached here. * Time zone objects and settings are cached here.
*/ */
protected static $_timezones = array(); protected static $_timezones = array();
/** /**
* Format a Unix timestamp using the internal timezone. * Format a Unix timestamp using the internal timezone.
* *
* @param string $format Format used in PHP date() function * @param string $format Format used in PHP date() function
* @param int $timestamp Unix timestamp (optional, default is now) * @param int $timestamp Unix timestamp (optional, default is now)
* @return string * @return string
@ -25,14 +25,14 @@ class DateTime
{ {
return self::getRelativeTimestamp($timestamp ?: time()); return self::getRelativeTimestamp($timestamp ?: time());
} }
$offset = Config::get('locale.internal_timezone') ?: date('Z', $timestamp); $offset = Config::get('locale.internal_timezone') ?: date('Z', $timestamp);
return gmdate($format, ($timestamp ?: time()) + $offset); return gmdate($format, ($timestamp ?: time()) + $offset);
} }
/** /**
* Format a Unix timestamp for the current user's timezone. * Format a Unix timestamp for the current user's timezone.
* *
* @param string $format Format used in PHP date() function * @param string $format Format used in PHP date() function
* @param int $timestamp Unix timestamp (optional, default is now) * @param int $timestamp Unix timestamp (optional, default is now)
* @return string * @return string
@ -43,7 +43,7 @@ class DateTime
{ {
return self::getRelativeTimestamp($timestamp ?: time()); return self::getRelativeTimestamp($timestamp ?: time());
} }
$timezone = self::getTimezoneForCurrentUser(); $timezone = self::getTimezoneForCurrentUser();
if (!isset(self::$_timezones[$timezone])) if (!isset(self::$_timezones[$timezone]))
{ {
@ -54,10 +54,10 @@ class DateTime
$datetime->setTimezone(self::$_timezones[$timezone]); $datetime->setTimezone(self::$_timezones[$timezone]);
return $datetime->format($format); return $datetime->format($format);
} }
/** /**
* Get the current user's timezone. * Get the current user's timezone.
* *
* @return string * @return string
*/ */
public static function getTimezoneForCurrentUser() public static function getTimezoneForCurrentUser()
@ -79,10 +79,10 @@ class DateTime
return @date_default_timezone_get(); return @date_default_timezone_get();
} }
} }
/** /**
* Get the list of time zones supported on this server. * Get the list of time zones supported on this server.
* *
* @return array * @return array
*/ */
public static function getTimezoneList() public static function getTimezoneList()
@ -103,10 +103,10 @@ class DateTime
$result['Etc/UTC'] = 'GMT/UTC (+00:00)'; $result['Etc/UTC'] = 'GMT/UTC (+00:00)';
return $result; return $result;
} }
/** /**
* Get the absolute (UTC) offset of a timezone. * Get the absolute (UTC) offset of a timezone.
* *
* @param string $timezone Timezone identifier, e.g. Asia/Seoul * @param string $timezone Timezone identifier, e.g. Asia/Seoul
* @param int $timestamp Unix timestamp (optional, default is now) * @param int $timestamp Unix timestamp (optional, default is now)
* @return int * @return int
@ -122,10 +122,10 @@ class DateTime
$datetime->setTimezone(self::$_timezones[$timezone]); $datetime->setTimezone(self::$_timezones[$timezone]);
return $datetime->getOffset(); return $datetime->getOffset();
} }
/** /**
* Get the relative offset between a timezone and Rhymix's internal timezone. * Get the relative offset between a timezone and Rhymix's internal timezone.
* *
* @param string $timezone Timezone identifier, e.g. Asia/Seoul * @param string $timezone Timezone identifier, e.g. Asia/Seoul
* @param int $timestamp Unix timestamp (optional, default is now) * @param int $timestamp Unix timestamp (optional, default is now)
* @return int * @return int
@ -134,10 +134,10 @@ class DateTime
{ {
return self::getTimezoneOffset($timezone, $timestamp) - Config::get('locale.internal_timezone'); return self::getTimezoneOffset($timezone, $timestamp) - Config::get('locale.internal_timezone');
} }
/** /**
* Get the absolute (UTC) offset of a timezone written in XE legacy format ('+0900'). * Get the absolute (UTC) offset of a timezone written in XE legacy format ('+0900').
* *
* @param string $timezone * @param string $timezone
* @return int * @return int
*/ */
@ -148,16 +148,16 @@ class DateTime
list($hours, $minutes) = str_split($timezone, 2); list($hours, $minutes) = str_split($timezone, 2);
return (((int)$hours * 60) + (int)$minutes) * $multiplier; return (((int)$hours * 60) + (int)$minutes) * $multiplier;
} }
/** /**
* Get a PHP time zone by UTC offset. * Get a PHP time zone by UTC offset.
* *
* Time zones with both (a) fractional offsets and (b) daylight saving time * Time zones with both (a) fractional offsets and (b) daylight saving time
* (such as Iran's +03:30/+04:30) cannot be converted in this way. * (such as Iran's +03:30/+04:30) cannot be converted in this way.
* However, if Rhymix is installed for the first time in such a time zone, * However, if Rhymix is installed for the first time in such a time zone,
* the internal time zone will be automatically set to UTC, * the internal time zone will be automatically set to UTC,
* so this should never be a problem in practice. * so this should never be a problem in practice.
* *
* @param int $offset * @param int $offset
* @return bool * @return bool
*/ */
@ -178,10 +178,10 @@ class DateTime
default: return 'Etc/GMT' . ($offset > 0 ? '-' : '+') . intval(abs($offset / 3600)); default: return 'Etc/GMT' . ($offset > 0 ? '-' : '+') . intval(abs($offset / 3600));
} }
} }
/** /**
* Get a relative timestamp (3 hours ago, etc.) * Get a relative timestamp (3 hours ago, etc.)
* *
* @param int $timestamp * @param int $timestamp
* @return string * @return string
*/ */
@ -189,7 +189,7 @@ class DateTime
{ {
$diff = \RX_TIME - $timestamp; $diff = \RX_TIME - $timestamp;
$langs = lang('common.time_gap'); $langs = lang('common.time_gap');
if ($diff < 3) if ($diff < 3)
{ {
return $langs['now']; return $langs['now'];

View file

@ -25,90 +25,90 @@ class Debug
protected static $_slow_remote_requests = array(); protected static $_slow_remote_requests = array();
protected static $_session_time = 0; protected static $_session_time = 0;
protected static $_query_time = 0; protected static $_query_time = 0;
/** /**
* Enable log collection. * Enable log collection.
* *
* @return void * @return void
*/ */
public static function enable() public static function enable()
{ {
self::$_enabled = true; self::$_enabled = true;
} }
/** /**
* Disable log collection. * Disable log collection.
* *
* @return void * @return void
*/ */
public static function disable() public static function disable()
{ {
self::$_enabled = false; self::$_enabled = false;
} }
/** /**
* Get all entries. * Get all entries.
* *
* @return array * @return array
*/ */
public static function getEntries() public static function getEntries()
{ {
return self::$_entries; return self::$_entries;
} }
/** /**
* Clear all entries. * Clear all entries.
* *
* @return void * @return void
*/ */
public static function clearEntries() public static function clearEntries()
{ {
self::$_entries = array(); self::$_entries = array();
} }
/** /**
* Get all errors. * Get all errors.
* *
* @return array * @return array
*/ */
public static function getErrors() public static function getErrors()
{ {
return self::$_errors; return self::$_errors;
} }
/** /**
* Clear all errors. * Clear all errors.
* *
* @return void * @return void
*/ */
public static function clearErrors() public static function clearErrors()
{ {
self::$_errors = array(); self::$_errors = array();
} }
/** /**
* Get all queries. * Get all queries.
* *
* @return array * @return array
*/ */
public static function getQueries() public static function getQueries()
{ {
return self::$_queries; return self::$_queries;
} }
/** /**
* Get all slow queries. * Get all slow queries.
* *
* @return array * @return array
*/ */
public static function getSlowQueries() public static function getSlowQueries()
{ {
return self::$_slow_queries; return self::$_slow_queries;
} }
/** /**
* Clear all queries. * Clear all queries.
* *
* @return void * @return void
*/ */
public static function clearQueries() public static function clearQueries()
@ -116,30 +116,30 @@ class Debug
self::$_queries = array(); self::$_queries = array();
self::$_slow_queries = array(); self::$_slow_queries = array();
} }
/** /**
* Get all triggers. * Get all triggers.
* *
* @return array * @return array
*/ */
public static function getTriggers() public static function getTriggers()
{ {
return self::$_triggers; return self::$_triggers;
} }
/** /**
* Get all slow triggers. * Get all slow triggers.
* *
* @return array * @return array
*/ */
public static function getSlowTriggers() public static function getSlowTriggers()
{ {
return self::$_slow_triggers; return self::$_slow_triggers;
} }
/** /**
* Clear all triggers. * Clear all triggers.
* *
* @return void * @return void
*/ */
public static function clearTriggers() public static function clearTriggers()
@ -147,30 +147,30 @@ class Debug
self::$_triggers = array(); self::$_triggers = array();
self::$_slow_triggers = array(); self::$_slow_triggers = array();
} }
/** /**
* Get all widgets. * Get all widgets.
* *
* @return array * @return array
*/ */
public static function getWidgets() public static function getWidgets()
{ {
return self::$_widgets; return self::$_widgets;
} }
/** /**
* Get all slow widgets. * Get all slow widgets.
* *
* @return array * @return array
*/ */
public static function getSlowWidgets() public static function getSlowWidgets()
{ {
return self::$_slow_widgets; return self::$_slow_widgets;
} }
/** /**
* Clear all widgets. * Clear all widgets.
* *
* @return void * @return void
*/ */
public static function clearWidgets() public static function clearWidgets()
@ -178,30 +178,30 @@ class Debug
self::$_widgets = array(); self::$_widgets = array();
self::$_slow_widgets = array(); self::$_slow_widgets = array();
} }
/** /**
* Get all remote requests. * Get all remote requests.
* *
* @return array * @return array
*/ */
public static function getRemoteRequests() public static function getRemoteRequests()
{ {
return self::$_remote_requests; return self::$_remote_requests;
} }
/** /**
* Get all slow remote requests. * Get all slow remote requests.
* *
* @return array * @return array
*/ */
public static function getSlowRemoteRequests() public static function getSlowRemoteRequests()
{ {
return self::$_slow_remote_requests; return self::$_slow_remote_requests;
} }
/** /**
* Clear all remote requests. * Clear all remote requests.
* *
* @return void * @return void
*/ */
public static function clearRemoteRequests() public static function clearRemoteRequests()
@ -209,10 +209,10 @@ class Debug
self::$_remote_requests = array(); self::$_remote_requests = array();
self::$_slow_remote_requests = array(); self::$_slow_remote_requests = array();
} }
/** /**
* Clear all records. * Clear all records.
* *
* @return void * @return void
*/ */
public static function clearAll() public static function clearAll()
@ -230,10 +230,10 @@ class Debug
self::$_session_time = 0; self::$_session_time = 0;
self::$_query_time = 0; self::$_query_time = 0;
} }
/** /**
* Add a filename alias. * Add a filename alias.
* *
* @param string $display_filename * @param string $display_filename
* @param string $real_filename * @param string $real_filename
* @return void * @return void
@ -242,10 +242,10 @@ class Debug
{ {
self::$_aliases[$real_filename] = $display_filename; self::$_aliases[$real_filename] = $display_filename;
} }
/** /**
* Add session start time. * Add session start time.
* *
* @param float $session_start_time * @param float $session_start_time
* @return void * @return void
*/ */
@ -253,10 +253,10 @@ class Debug
{ {
self::$_session_time += $session_start_time; self::$_session_time += $session_start_time;
} }
/** /**
* Add an arbitrary entry to the log. * Add an arbitrary entry to the log.
* *
* @param string $message * @param string $message
* @return void * @return void
*/ */
@ -267,14 +267,14 @@ class Debug
{ {
return; return;
} }
// Get the backtrace. // Get the backtrace.
$backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
if (count($backtrace) > 1 && $backtrace[1]['function'] === 'debugPrint' && empty($backtrace[1]['class'])) if (count($backtrace) > 1 && $backtrace[1]['function'] === 'debugPrint' && empty($backtrace[1]['class']))
{ {
array_shift($backtrace); array_shift($backtrace);
} }
// Create a log entry. // Create a log entry.
$entry = (object)array( $entry = (object)array(
'message' => unserialize(serialize($message)), 'message' => unserialize(serialize($message)),
@ -285,7 +285,7 @@ class Debug
'type' => 'Debug', 'type' => 'Debug',
); );
self::$_entries[] = $entry; self::$_entries[] = $entry;
// Add the entry to the error log. // Add the entry to the error log.
if (isset(self::$_config['write_error_log']) && self::$_config['write_error_log'] === 'all') if (isset(self::$_config['write_error_log']) && self::$_config['write_error_log'] === 'all')
{ {
@ -294,10 +294,10 @@ class Debug
error_log($log_entry); error_log($log_entry);
} }
} }
/** /**
* Add a PHP error to the log. * Add a PHP error to the log.
* *
* @param int $errno * @param int $errno
* @param string $errstr * @param string $errstr
* @param string $errfile * @param string $errfile
@ -312,13 +312,13 @@ class Debug
{ {
return; return;
} }
// Do not handle error types that we were told to ignore. // Do not handle error types that we were told to ignore.
if (!($errno & error_reporting())) if (!($errno & error_reporting()))
{ {
return; return;
} }
// Rewrite the error message with relative paths. // Rewrite the error message with relative paths.
$message = str_replace(array( $message = str_replace(array(
' called in ' . \RX_BASEDIR, ' called in ' . \RX_BASEDIR,
@ -327,10 +327,10 @@ class Debug
' called in ', ' called in ',
' defined in ', ' defined in ',
), $errstr); ), $errstr);
// Get the backtrace. // Get the backtrace.
$backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
// Prepare the error entry. // Prepare the error entry.
self::$_errors[] = $errinfo = (object)array( self::$_errors[] = $errinfo = (object)array(
'message' => $message, 'message' => $message,
@ -340,7 +340,7 @@ class Debug
'time' => microtime(true), 'time' => microtime(true),
'type' => self::getErrorType($errno), 'type' => self::getErrorType($errno),
); );
// Add the entry to the error log. // Add the entry to the error log.
if (isset(self::$_config['write_error_log']) && self::$_config['write_error_log'] === 'all') if (isset(self::$_config['write_error_log']) && self::$_config['write_error_log'] === 'all')
{ {
@ -348,10 +348,10 @@ class Debug
error_log($log_entry . \PHP_EOL . self::formatBacktrace($backtrace)); error_log($log_entry . \PHP_EOL . self::formatBacktrace($backtrace));
} }
} }
/** /**
* Add a query to the log. * Add a query to the log.
* *
* @return void * @return void
*/ */
public static function addQuery($query) public static function addQuery($query)
@ -361,7 +361,7 @@ class Debug
{ {
return; return;
} }
// Prepare the log entry. // Prepare the log entry.
$query_object = (object)array( $query_object = (object)array(
'query_id' => $query['query_id'], 'query_id' => $query['query_id'],
@ -377,10 +377,10 @@ class Debug
'time' => microtime(true), 'time' => microtime(true),
'type' => 'Query', 'type' => 'Query',
); );
self::$_queries[] = $query_object; self::$_queries[] = $query_object;
self::$_query_time += $query_object->query_time; self::$_query_time += $query_object->query_time;
// Add the entry to the error log if the result wasn't successful. // Add the entry to the error log if the result wasn't successful.
if ($query['result'] === 'error') if ($query['result'] === 'error')
{ {
@ -392,26 +392,26 @@ class Debug
'time' => $query_object->time, 'time' => $query_object->time,
'type' => 'Query Error', 'type' => 'Query Error',
); );
self::$_errors[] = $error_object; self::$_errors[] = $error_object;
if (self::$_config['write_error_log'] === 'all') if (self::$_config['write_error_log'] === 'all')
{ {
$log_entry = strtr(sprintf('Query Error: %s in %s on line %d', $error_object->message, $error_object->file, intval($error_object->line)), "\0\r\n\t\v\e\f", ' '); $log_entry = strtr(sprintf('Query Error: %s in %s on line %d', $error_object->message, $error_object->file, intval($error_object->line)), "\0\r\n\t\v\e\f", ' ');
error_log($log_entry . \PHP_EOL . self::formatBacktrace($error_object->backtrace)); error_log($log_entry . \PHP_EOL . self::formatBacktrace($error_object->backtrace));
} }
} }
// Add the entry to the slow query log. // Add the entry to the slow query log.
if ($query_object->query_time && $query_object->query_time >= (self::$_config['log_slow_queries'] ?? 1)) if ($query_object->query_time && $query_object->query_time >= (self::$_config['log_slow_queries'] ?? 1))
{ {
self::$_slow_queries[] = $query_object; self::$_slow_queries[] = $query_object;
} }
} }
/** /**
* Add a trigger to the log. * Add a trigger to the log.
* *
* @return bool * @return bool
*/ */
public static function addTrigger($trigger) public static function addTrigger($trigger)
@ -421,7 +421,7 @@ class Debug
{ {
return; return;
} }
// Prepare the log entry. // Prepare the log entry.
$trigger_object = (object)array( $trigger_object = (object)array(
'trigger_name' => $trigger['name'], 'trigger_name' => $trigger['name'],
@ -435,17 +435,17 @@ class Debug
'time' => microtime(true), 'time' => microtime(true),
'type' => 'Trigger', 'type' => 'Trigger',
); );
self::$_triggers[] = $trigger_object; self::$_triggers[] = $trigger_object;
if ($trigger_object->trigger_time && $trigger_object->trigger_time >= (self::$_config['log_slow_triggers'] ?? 1)) if ($trigger_object->trigger_time && $trigger_object->trigger_time >= (self::$_config['log_slow_triggers'] ?? 1))
{ {
self::$_slow_triggers[] = $trigger_object; self::$_slow_triggers[] = $trigger_object;
} }
} }
/** /**
* Add a widget to the log. * Add a widget to the log.
* *
* @return bool * @return bool
*/ */
public static function addWidget($widget) public static function addWidget($widget)
@ -455,7 +455,7 @@ class Debug
{ {
return; return;
} }
// Prepare the log entry. // Prepare the log entry.
$widget_object = (object)array( $widget_object = (object)array(
'widget_name' => $widget['name'], 'widget_name' => $widget['name'],
@ -467,17 +467,17 @@ class Debug
'time' => microtime(true), 'time' => microtime(true),
'type' => 'Widget', 'type' => 'Widget',
); );
self::$_widgets[] = $widget_object; self::$_widgets[] = $widget_object;
if ($widget_object->widget_time && $widget_object->widget_time >= (self::$_config['log_slow_widgets'] ?? 1)) if ($widget_object->widget_time && $widget_object->widget_time >= (self::$_config['log_slow_widgets'] ?? 1))
{ {
self::$_slow_widgets[] = $widget_object; self::$_slow_widgets[] = $widget_object;
} }
} }
/** /**
* Add a remote request to the log. * Add a remote request to the log.
* *
* @return bool * @return bool
*/ */
public static function addRemoteRequest($request) public static function addRemoteRequest($request)
@ -487,7 +487,7 @@ class Debug
{ {
return; return;
} }
// Prepare the log entry. // Prepare the log entry.
$request_object = (object)array( $request_object = (object)array(
'url' => $request['url'], 'url' => $request['url'],
@ -501,17 +501,17 @@ class Debug
'time' => microtime(true), 'time' => microtime(true),
'type' => 'Remote Request', 'type' => 'Remote Request',
); );
self::$_remote_requests[] = $request_object; self::$_remote_requests[] = $request_object;
if ($request_object->elapsed_time && $request_object->elapsed_time >= (self::$_config['log_slow_remote_requests'] ?? 1)) if ($request_object->elapsed_time && $request_object->elapsed_time >= (self::$_config['log_slow_remote_requests'] ?? 1))
{ {
self::$_slow_remote_requests[] = $request_object; self::$_slow_remote_requests[] = $request_object;
} }
} }
/** /**
* The default handler for catching exceptions. * The default handler for catching exceptions.
* *
* @param Exception $e * @param Exception $e
* @return void * @return void
*/ */
@ -519,7 +519,7 @@ class Debug
{ {
// Find out the file where the error really occurred. // Find out the file where the error really occurred.
$errfile = self::translateFilename($e->getFile()); $errfile = self::translateFilename($e->getFile());
// If the exception was thrown in a Rhymix Framework class, find out where that class was called. // If the exception was thrown in a Rhymix Framework class, find out where that class was called.
$backtrace = $e->getTrace(); $backtrace = $e->getTrace();
$caller_errfile = $errfile; $caller_errfile = $errfile;
@ -537,9 +537,9 @@ class Debug
$caller_errline = $trace['line']; $caller_errline = $trace['line'];
} }
} }
// Add the exception to the error log. // Add the exception to the error log.
if ($caller_errfile && $caller_errfile !== $errfile) if ($caller_errfile && $caller_errfile !== $errfile)
{ {
$log_entry = str_replace("\0", '', sprintf('%s #%d "%s" in %s on line %d (via %s on line %d)', $log_entry = str_replace("\0", '', sprintf('%s #%d "%s" in %s on line %d (via %s on line %d)',
@ -554,15 +554,15 @@ class Debug
{ {
error_log('PHP Exception: ' . $log_entry . \PHP_EOL . self::formatBacktrace($e->getTrace())); error_log('PHP Exception: ' . $log_entry . \PHP_EOL . self::formatBacktrace($e->getTrace()));
} }
// Display the error screen. // Display the error screen.
self::displayErrorScreen($log_entry); self::displayErrorScreen($log_entry);
exit; exit;
} }
/** /**
* The default handler for catching fatal errors. * The default handler for catching fatal errors.
* *
* @return void * @return void
*/ */
public static function shutdownHandler() public static function shutdownHandler()
@ -573,10 +573,10 @@ class Debug
{ {
return; return;
} }
// Find out the file where the error really occurred. // Find out the file where the error really occurred.
$errinfo['file'] = self::translateFilename($errinfo['file']); $errinfo['file'] = self::translateFilename($errinfo['file']);
// Add the entry to the error log. // Add the entry to the error log.
$message = sprintf('%s in %s on line %d', $errinfo['message'], $errinfo['file'], intval($errinfo['line'])); $message = sprintf('%s in %s on line %d', $errinfo['message'], $errinfo['file'], intval($errinfo['line']));
$log_entry = str_replace("\0", '', 'PHP ' . self::getErrorType($errinfo['type']) . ': ' . $message); $log_entry = str_replace("\0", '', 'PHP ' . self::getErrorType($errinfo['type']) . ': ' . $message);
@ -584,11 +584,11 @@ class Debug
{ {
error_log($log_entry); error_log($log_entry);
} }
// Display the error screen. // Display the error screen.
self::displayErrorScreen($log_entry); self::displayErrorScreen($log_entry);
} }
/** /**
* Format a backtrace for error logging. * Format a backtrace for error logging.
*/ */
@ -607,10 +607,10 @@ class Debug
} }
return implode(\PHP_EOL, $result); return implode(\PHP_EOL, $result);
} }
/** /**
* Translate filenames. * Translate filenames.
* *
* @param string $filename * @param string $filename
* @return string * @return string
*/ */
@ -626,10 +626,10 @@ class Debug
} }
return $filename; return $filename;
} }
/** /**
* Register all error handlers. * Register all error handlers.
* *
* @return void * @return void
*/ */
public static function registerErrorHandlers($error_types) public static function registerErrorHandlers($error_types)
@ -639,10 +639,10 @@ class Debug
set_exception_handler('\\Rhymix\\Framework\\Debug::exceptionHandler'); set_exception_handler('\\Rhymix\\Framework\\Debug::exceptionHandler');
register_shutdown_function('\\Rhymix\\Framework\\Debug::shutdownHandler'); register_shutdown_function('\\Rhymix\\Framework\\Debug::shutdownHandler');
} }
/** /**
* Display a fatal error screen. * Display a fatal error screen.
* *
* @param string $message * @param string $message
* @return void * @return void
*/ */
@ -653,20 +653,20 @@ class Debug
{ {
return; return;
} }
// Disable output buffering. // Disable output buffering.
while (ob_get_level()) while (ob_get_level())
{ {
ob_end_clean(); ob_end_clean();
} }
// Localize the error title. // Localize the error title.
$title = lang('msg_server_error'); $title = lang('msg_server_error');
if ($title === 'msg_server_error') if ($title === 'msg_server_error')
{ {
$message = 'Server Error'; $message = 'Server Error';
} }
// Localize the error message. // Localize the error message.
$display_error_message = ini_get('display_errors') || !\Context::isInstalled() || Session::isAdmin() || self::isEnabledForCurrentUser(); $display_error_message = ini_get('display_errors') || !\Context::isInstalled() || Session::isAdmin() || self::isEnabledForCurrentUser();
$message = $display_error_message ? $message : lang('msg_server_error_see_log'); $message = $display_error_message ? $message : lang('msg_server_error_see_log');
@ -674,7 +674,7 @@ class Debug
{ {
$message = 'Your server is configured to hide error messages. Please see your server\'s error log for details.'; $message = 'Your server is configured to hide error messages. Please see your server\'s error log for details.';
} }
// Display a generic error page. // Display a generic error page.
try try
{ {
@ -685,10 +685,10 @@ class Debug
self::displayError($message); self::displayError($message);
} }
} }
/** /**
* Display a default error. * Display a default error.
* *
* @param string $message * @param string $message
* @return void * @return void
*/ */
@ -706,10 +706,10 @@ class Debug
echo json_encode(array('error' => -1, 'message' => escape($message, false)), \JSON_UNESCAPED_UNICODE); echo json_encode(array('error' => -1, 'message' => escape($message, false)), \JSON_UNESCAPED_UNICODE);
} }
} }
/** /**
* Check if debugging is enabled for the current user. * Check if debugging is enabled for the current user.
* *
* @return bool * @return bool
*/ */
public static function isEnabledForCurrentUser() public static function isEnabledForCurrentUser()
@ -722,12 +722,12 @@ class Debug
{ {
return self::$_enabled = false; return self::$_enabled = false;
} }
switch (self::$_config['display_to']) switch (self::$_config['display_to'])
{ {
case 'everyone': case 'everyone':
return self::$_enabled = true; return self::$_enabled = true;
case 'ip': case 'ip':
if (Filters\IpFilter::inRanges(\RX_CLIENT_IP, self::$_config['allow'])) if (Filters\IpFilter::inRanges(\RX_CLIENT_IP, self::$_config['allow']))
{ {
@ -742,7 +742,7 @@ class Debug
return self::$_enabled = true; return self::$_enabled = true;
} }
return self::$_enabled = false; return self::$_enabled = false;
case 'admin': case 'admin':
default: default:
$logged_info = \Context::get('logged_info'); $logged_info = \Context::get('logged_info');
@ -760,10 +760,10 @@ class Debug
} }
} }
} }
/** /**
* Get all debug information as an object. * Get all debug information as an object.
* *
* @return object * @return object
*/ */
public static function getDebugData() public static function getDebugData()
@ -802,7 +802,7 @@ class Debug
'slow_widgets' => self::$_slow_widgets, 'slow_widgets' => self::$_slow_widgets,
'slow_remote_requests' => self::$_slow_remote_requests, 'slow_remote_requests' => self::$_slow_remote_requests,
); );
// Clean up the querystring. // Clean up the querystring.
if (isset($data->queries)) if (isset($data->queries))
{ {
@ -811,7 +811,7 @@ class Debug
$query->query_string = trim(utf8_normalize_spaces($query->query_string, true)); $query->query_string = trim(utf8_normalize_spaces($query->query_string, true));
} }
} }
// Clean up the backtrace. // Clean up the backtrace.
foreach (array('entries', 'errors', 'queries', 'slow_queries', 'remote_requests', 'slow_remote_requests') as $key) foreach (array('entries', 'errors', 'queries', 'slow_queries', 'remote_requests', 'slow_remote_requests') as $key)
{ {
@ -838,13 +838,13 @@ class Debug
} }
} }
} }
return $data; return $data;
} }
/** /**
* Convert a PHP error number to the corresponding error name. * Convert a PHP error number to the corresponding error name.
* *
* @param int $errno * @param int $errno
* @return string * @return string
*/ */

View file

@ -7,5 +7,5 @@ namespace Rhymix\Framework;
*/ */
class Exception extends \Exception class Exception extends \Exception
{ {
} }

View file

@ -12,16 +12,16 @@ class Formatter
*/ */
const TEXT_NEWLINE_AS_P = 1; const TEXT_NEWLINE_AS_P = 1;
const TEXT_DOUBLE_NEWLINE_AS_P = 2; const TEXT_DOUBLE_NEWLINE_AS_P = 2;
/** /**
* Options for Markdown to HTML conversion. * Options for Markdown to HTML conversion.
*/ */
const MD_NEWLINE_AS_BR = 16; const MD_NEWLINE_AS_BR = 16;
const MD_ENABLE_EXTRA = 128; const MD_ENABLE_EXTRA = 128;
/** /**
* Convert plain text to HTML. * Convert plain text to HTML.
* *
* @param string $text * @param string $text
* @param int $options (optional) * @param int $options (optional)
* @return string * @return string
@ -39,7 +39,7 @@ class Formatter
} }
return $result; return $result;
} }
// This option uses <br> to separate lines and <p> to separate paragraphs. // This option uses <br> to separate lines and <p> to separate paragraphs.
if ($options & self::TEXT_DOUBLE_NEWLINE_AS_P) if ($options & self::TEXT_DOUBLE_NEWLINE_AS_P)
{ {
@ -52,14 +52,14 @@ class Formatter
} }
return $result; return $result;
} }
// The default is to use <br> always. // The default is to use <br> always.
return nl2br(escape(trim($text))) . "<br />\n"; return nl2br(escape(trim($text))) . "<br />\n";
} }
/** /**
* Convert HTML to plain text. * Convert HTML to plain text.
* *
* @param string $html * @param string $html
* @return string * @return string
*/ */
@ -69,7 +69,7 @@ class Formatter
$html = preg_replace('!<br[^>]*>\s*!i', "\n", $html); $html = preg_replace('!<br[^>]*>\s*!i', "\n", $html);
$html = preg_replace('!<p\b[^>]*>\s*!i', '', $html); $html = preg_replace('!<p\b[^>]*>\s*!i', '', $html);
$html = preg_replace('!</p[^>]*>\s*!i', "\n\n", $html); $html = preg_replace('!</p[^>]*>\s*!i', "\n\n", $html);
// Encode links and images to preserve essential information. // Encode links and images to preserve essential information.
$html = preg_replace_callback('!<a\b[^>]*href="([^>"]+)"[^>]*>([^<]*)</a>!i', function($matches) { $html = preg_replace_callback('!<a\b[^>]*href="([^>"]+)"[^>]*>([^<]*)</a>!i', function($matches) {
return trim($matches[2] . ' &lt;' . $matches[1] . '&gt;'); return trim($matches[2] . ' &lt;' . $matches[1] . '&gt;');
@ -79,20 +79,20 @@ class Formatter
$title = $title ?: (preg_match('!alt="([^>"]+)"!i', $matches[0], $m) ? $m[1] : 'IMAGE'); $title = $title ?: (preg_match('!alt="([^>"]+)"!i', $matches[0], $m) ? $m[1] : 'IMAGE');
return trim('[' . $title . '] &lt;' . $matches[1] . '&gt;'); return trim('[' . $title . '] &lt;' . $matches[1] . '&gt;');
}, $html); }, $html);
// Strip all other HTML. // Strip all other HTML.
$text = html_entity_decode(strip_tags($html)); $text = html_entity_decode(strip_tags($html));
unset($html); unset($html);
// Normalize whitespace and return. // Normalize whitespace and return.
$text = str_replace("\r\n", "\n", $text); $text = str_replace("\r\n", "\n", $text);
$text = preg_replace('/\n(?:\s*\n)+/', "\n\n", $text); $text = preg_replace('/\n(?:\s*\n)+/', "\n\n", $text);
return trim($text) . "\n"; return trim($text) . "\n";
} }
/** /**
* Convert Markdown to HTML. * Convert Markdown to HTML.
* *
* @param string $markdown * @param string $markdown
* @param int $options (optional) * @param int $options (optional)
* @return string * @return string
@ -110,19 +110,19 @@ class Formatter
$classes = false; $classes = false;
$parser = new \Michelf\Markdown; $parser = new \Michelf\Markdown;
} }
if ($options & self::MD_NEWLINE_AS_BR) if ($options & self::MD_NEWLINE_AS_BR)
{ {
$parser->hard_wrap = true; $parser->hard_wrap = true;
} }
$html = $parser->transform($markdown); $html = $parser->transform($markdown);
return Filters\HTMLFilter::clean($html, $classes); return Filters\HTMLFilter::clean($html, $classes);
} }
/** /**
* Convert HTML to Markdown. * Convert HTML to Markdown.
* *
* @param string $html * @param string $html
* @return string * @return string
*/ */
@ -133,10 +133,10 @@ class Formatter
$converter->getConfig()->setOption('strip_tags', true); $converter->getConfig()->setOption('strip_tags', true);
return trim($converter->convert($html)) . "\n"; return trim($converter->convert($html)) . "\n";
} }
/** /**
* Convert BBCode to HTML. * Convert BBCode to HTML.
* *
* @param string $bbcode * @param string $bbcode
* @return string * @return string
*/ */
@ -144,21 +144,21 @@ class Formatter
{ {
$parser = new \JBBCode\Parser; $parser = new \JBBCode\Parser;
$parser->addCodeDefinitionSet(new \JBBCode\DefaultCodeDefinitionSet()); $parser->addCodeDefinitionSet(new \JBBCode\DefaultCodeDefinitionSet());
$builder = new \JBBCode\CodeDefinitionBuilder('quote', '<blockquote>{param}</blockquote>'); $builder = new \JBBCode\CodeDefinitionBuilder('quote', '<blockquote>{param}</blockquote>');
$parser->addCodeDefinition($builder->build()); $parser->addCodeDefinition($builder->build());
$builder = new \JBBCode\CodeDefinitionBuilder('code', '<pre><code>{param}</code></pre>'); $builder = new \JBBCode\CodeDefinitionBuilder('code', '<pre><code>{param}</code></pre>');
$builder->setParseContent(false); $builder->setParseContent(false);
$parser->addCodeDefinition($builder->build()); $parser->addCodeDefinition($builder->build());
$parser->parse($bbcode); $parser->parse($bbcode);
$html = $parser->getAsHtml(); $html = $parser->getAsHtml();
return Filters\HTMLFilter::clean($html); return Filters\HTMLFilter::clean($html);
} }
/** /**
* Apply smart quotes and other stylistic enhancements to HTML. * Apply smart quotes and other stylistic enhancements to HTML.
* *
* @param string $html * @param string $html
* @return string * @return string
*/ */
@ -166,10 +166,10 @@ class Formatter
{ {
return \Michelf\SmartyPants::defaultTransform($html, 'qbBdDiew'); return \Michelf\SmartyPants::defaultTransform($html, 'qbBdDiew');
} }
/** /**
* Compile LESS into CSS. * Compile LESS into CSS.
* *
* @param string|array $source_filename * @param string|array $source_filename
* @param string $target_filename * @param string $target_filename
* @param array $variables (optional) * @param array $variables (optional)
@ -181,7 +181,7 @@ class Formatter
// Get the cleaned and concatenated content. // Get the cleaned and concatenated content.
$imported_list = []; $imported_list = [];
$content = self::concatCSS($source_filename, $target_filename, true, $imported_list); $content = self::concatCSS($source_filename, $target_filename, true, $imported_list);
// Compile! // Compile!
try try
{ {
@ -192,7 +192,7 @@ class Formatter
{ {
$less_compiler->setVariables($variables); $less_compiler->setVariables($variables);
} }
$content = $less_compiler->compile($content) . "\n"; $content = $less_compiler->compile($content) . "\n";
$content = strpos($content, '@charset') === false ? ('@charset "UTF-8";' . "\n" . $content) : $content; $content = strpos($content, '@charset') === false ? ('@charset "UTF-8";' . "\n" . $content) : $content;
$result = true; $result = true;
@ -204,20 +204,20 @@ class Formatter
$content = sprintf("/*\n Error while compiling %s\n\n %s\n*/\n", $filename, $message); $content = sprintf("/*\n Error while compiling %s\n\n %s\n*/\n", $filename, $message);
$result = false; $result = false;
} }
// Save the result to the target file. // Save the result to the target file.
Storage::write($target_filename, $content); Storage::write($target_filename, $content);
// Save the list of imported files. // Save the list of imported files.
Storage::writePHPData(preg_replace('/\.css$/', '.imports.php', $target_filename), $imported_list, null, false); Storage::writePHPData(preg_replace('/\.css$/', '.imports.php', $target_filename), $imported_list, null, false);
// Also return the compiled CSS content. // Also return the compiled CSS content.
return $result; return $result;
} }
/** /**
* Compile SCSS into CSS. * Compile SCSS into CSS.
* *
* @param string|array $source_filename * @param string|array $source_filename
* @param string $target_filename * @param string $target_filename
* @param array $variables (optional) * @param array $variables (optional)
@ -229,7 +229,7 @@ class Formatter
// Get the cleaned and concatenated content. // Get the cleaned and concatenated content.
$imported_list = []; $imported_list = [];
$content = self::concatCSS($source_filename, $target_filename, true, $imported_list); $content = self::concatCSS($source_filename, $target_filename, true, $imported_list);
// Compile! // Compile!
try try
{ {
@ -240,7 +240,7 @@ class Formatter
{ {
$scss_compiler->addVariables(array_map('\ScssPhp\ScssPhp\ValueConverter::parseValue', $variables)); $scss_compiler->addVariables(array_map('\ScssPhp\ScssPhp\ValueConverter::parseValue', $variables));
} }
$content = $scss_compiler->compileString($content)->getCss() . "\n"; $content = $scss_compiler->compileString($content)->getCss() . "\n";
$content = strpos($content, '@charset') === false ? ('@charset "UTF-8";' . "\n" . $content) : $content; $content = strpos($content, '@charset') === false ? ('@charset "UTF-8";' . "\n" . $content) : $content;
$result = true; $result = true;
@ -252,20 +252,20 @@ class Formatter
$content = sprintf("/*\n Error while compiling %s\n\n %s\n*/\n", $filename, $message); $content = sprintf("/*\n Error while compiling %s\n\n %s\n*/\n", $filename, $message);
$result = false; $result = false;
} }
// Save the result to the target file. // Save the result to the target file.
Storage::write($target_filename, $content); Storage::write($target_filename, $content);
// Save the list of imported files. // Save the list of imported files.
Storage::writePHPData(preg_replace('/\.css$/', '.imports.php', $target_filename), $imported_list, null, false); Storage::writePHPData(preg_replace('/\.css$/', '.imports.php', $target_filename), $imported_list, null, false);
// Also return the compiled CSS content. // Also return the compiled CSS content.
return $result; return $result;
} }
/** /**
* Minify CSS. * Minify CSS.
* *
* @param string|array $source_filename * @param string|array $source_filename
* @param string $target_filename * @param string $target_filename
* @return bool * @return bool
@ -290,10 +290,10 @@ class Formatter
Storage::write($target_filename, $content); Storage::write($target_filename, $content);
return strlen($content) ? true : false; return strlen($content) ? true : false;
} }
/** /**
* Minify JS. * Minify JS.
* *
* @param string|array $source_filename * @param string|array $source_filename
* @param string $target_filename * @param string $target_filename
* @return bool * @return bool
@ -316,10 +316,10 @@ class Formatter
Storage::write($target_filename, $content); Storage::write($target_filename, $content);
return strlen($content) ? true : false; return strlen($content) ? true : false;
} }
/** /**
* CSS concatenation subroutine for compileLESS() and compileSCSS(). * CSS concatenation subroutine for compileLESS() and compileSCSS().
* *
* @param string|array $source_filename * @param string|array $source_filename
* @param string $target_filename * @param string $target_filename
* @param bool $add_comment * @param bool $add_comment
@ -331,12 +331,12 @@ class Formatter
$charsets = []; $charsets = [];
$imported_urls = []; $imported_urls = [];
$result = ''; $result = '';
if (!is_array($source_filename)) if (!is_array($source_filename))
{ {
$source_filename = array($source_filename); $source_filename = array($source_filename);
} }
foreach ($source_filename as $filename) foreach ($source_filename as $filename)
{ {
// Get the media query. // Get the media query.
@ -348,10 +348,10 @@ class Formatter
{ {
$media = null; $media = null;
} }
// Clean the content. // Clean the content.
$content = utf8_clean(file_get_contents($filename)); $content = utf8_clean(file_get_contents($filename));
// Convert all paths in LESS and SCSS imports, too. // Convert all paths in LESS and SCSS imports, too.
$dirname = dirname($filename); $dirname = dirname($filename);
$import_type = ends_with('.scss', $filename) ? 'scss' : 'normal'; $import_type = ends_with('.scss', $filename) ? 'scss' : 'normal';
@ -421,7 +421,7 @@ class Formatter
} }
return trim($import_content); return trim($import_content);
}, $content); }, $content);
// Convert all paths to be relative to the new filename. // Convert all paths to be relative to the new filename.
$path_converter = new \MatthiasMullie\PathConverter\Converter($filename, $target_filename); $path_converter = new \MatthiasMullie\PathConverter\Converter($filename, $target_filename);
$content = preg_replace_callback('/\burl\\(([^)]+)\\)/iU', function($matches) use ($path_converter) { $content = preg_replace_callback('/\burl\\(([^)]+)\\)/iU', function($matches) use ($path_converter) {
@ -436,19 +436,19 @@ class Formatter
} }
}, $content); }, $content);
unset($path_converter); unset($path_converter);
// Extract all @charset declarations. // Extract all @charset declarations.
$content = preg_replace_callback('/@charset\s+(["\'a-z0-9_-]+);[\r\n]*/i', function($matches) use (&$charsets) { $content = preg_replace_callback('/@charset\s+(["\'a-z0-9_-]+);[\r\n]*/i', function($matches) use (&$charsets) {
$charsets[] = trim($matches[1], '"\''); $charsets[] = trim($matches[1], '"\'');
return ''; return '';
}, $content); }, $content);
// Wrap the content in a media query if there is one. // Wrap the content in a media query if there is one.
if ($media !== null) if ($media !== null)
{ {
$content = "@media $media {\n\n" . trim($content) . "\n\n}"; $content = "@media $media {\n\n" . trim($content) . "\n\n}";
} }
// Append to the result string. // Append to the result string.
$original_filename = starts_with(\RX_BASEDIR, $filename) ? substr($filename, strlen(\RX_BASEDIR)) : $filename; $original_filename = starts_with(\RX_BASEDIR, $filename) ? substr($filename, strlen(\RX_BASEDIR)) : $filename;
if ($add_comment) if ($add_comment)
@ -460,7 +460,7 @@ class Formatter
$result .= trim($content) . "\n\n"; $result .= trim($content) . "\n\n";
} }
} }
// Place all @charset and @import statements at the beginning. // Place all @charset and @import statements at the beginning.
if (count($imported_urls)) if (count($imported_urls))
{ {
@ -474,13 +474,13 @@ class Formatter
$charset = '@charset "' . escape_dqstr(array_first($charsets)) . '";'; $charset = '@charset "' . escape_dqstr(array_first($charsets)) . '";';
$result = $charset . "\n" . $result; $result = $charset . "\n" . $result;
} }
return $result; return $result;
} }
/** /**
* JS concatenation subroutine. * JS concatenation subroutine.
* *
* @param string|array $source_filename * @param string|array $source_filename
* @param string $target_filename * @param string $target_filename
* @return string * @return string
@ -488,12 +488,12 @@ class Formatter
public static function concatJS($source_filename, $target_filename) public static function concatJS($source_filename, $target_filename)
{ {
$result = ''; $result = '';
if (!is_array($source_filename)) if (!is_array($source_filename))
{ {
$source_filename = array($source_filename); $source_filename = array($source_filename);
} }
foreach ($source_filename as $filename) foreach ($source_filename as $filename)
{ {
// Handle the array format, previously used for the targetIE attribute. // Handle the array format, previously used for the targetIE attribute.
@ -501,21 +501,21 @@ class Formatter
{ {
$filename = reset($filename); $filename = reset($filename);
} }
// Clean the content. // Clean the content.
$content = utf8_clean(file_get_contents($filename)); $content = utf8_clean(file_get_contents($filename));
// Append to the result string. // Append to the result string.
$original_filename = starts_with(\RX_BASEDIR, $filename) ? substr($filename, strlen(\RX_BASEDIR)) : $filename; $original_filename = starts_with(\RX_BASEDIR, $filename) ? substr($filename, strlen(\RX_BASEDIR)) : $filename;
$result .= '/* Original file: ' . $original_filename . ' */' . "\n\n" . trim($content) . ";\n\n"; $result .= '/* Original file: ' . $original_filename . ' */' . "\n\n" . trim($content) . ";\n\n";
} }
return $result; return $result;
} }
/** /**
* Convert IE conditional comments to JS conditions. * Convert IE conditional comments to JS conditions.
* *
* @deprecated * @deprecated
* @param string $condition * @param string $condition
* @return string * @return string

View file

@ -9,7 +9,7 @@ class Image
{ {
/** /**
* Check if a file is an image * Check if a file is an image
* *
* @param string $filename * @param string $filename
* @return bool * @return bool
*/ */
@ -17,10 +17,10 @@ class Image
{ {
return array_shift(explode('/', MIME::getContentType($filename))) === 'image'; return array_shift(explode('/', MIME::getContentType($filename))) === 'image';
} }
/** /**
* Check if a file is an animated GIF. * Check if a file is an animated GIF.
* *
* @param string $filename * @param string $filename
* @return bool * @return bool
*/ */
@ -46,10 +46,10 @@ class Image
fclose($fp); fclose($fp);
return $frames > 1; return $frames > 1;
} }
/** /**
* Get image information * Get image information
* *
* @param string $filename * @param string $filename
* @return array|false * @return array|false
*/ */

View file

@ -9,7 +9,7 @@ class Korea
{ {
/** /**
* Format a phone number. * Format a phone number.
* *
* @param string $num * @param string $num
* @return string * @return string
*/ */
@ -17,7 +17,7 @@ class Korea
{ {
// Remove all non-numbers. // Remove all non-numbers.
$num = preg_replace('/[^0-9]/', '', $num); $num = preg_replace('/[^0-9]/', '', $num);
// Remove the country code. // Remove the country code.
if (strncmp($num, '82', 2) === 0) if (strncmp($num, '82', 2) === 0)
{ {
@ -27,7 +27,7 @@ class Korea
$num = '0' . $num; $num = '0' . $num;
} }
} }
// Apply different format based on the number of digits. // Apply different format based on the number of digits.
switch (strlen($num)) switch (strlen($num))
{ {
@ -62,10 +62,10 @@ class Korea
} }
} }
} }
/** /**
* Check if a Korean phone number contains a valid area code and the correct number of digits. * Check if a Korean phone number contains a valid area code and the correct number of digits.
* *
* @param string $num * @param string $num
* @return bool * @return bool
*/ */
@ -90,10 +90,10 @@ class Korea
} }
return false; return false;
} }
/** /**
* Check if a Korean phone number is a mobile phone number. * Check if a Korean phone number is a mobile phone number.
* *
* @param string $num * @param string $num
* @return bool * @return bool
*/ */
@ -103,14 +103,14 @@ class Korea
$len = strlen($num); $len = strlen($num);
return preg_match('/^01[016789][2-9][0-9]{6,7}$/', $num) ? true : false; return preg_match('/^01[016789][2-9][0-9]{6,7}$/', $num) ? true : false;
} }
/** /**
* Check if the given string is a valid resident registration number (주민등록번호) * Check if the given string is a valid resident registration number (주민등록번호)
* or foreigner registration number (외국인등록번호). * or foreigner registration number (외국인등록번호).
* *
* This method only checks the format. * This method only checks the format.
* It does not check that the number is actually in use. * It does not check that the number is actually in use.
* *
* @param string $code * @param string $code
* @return bool * @return bool
*/ */
@ -121,16 +121,16 @@ class Korea
{ {
return false; return false;
} }
// Remove hyphen. // Remove hyphen.
$code = str_replace('-', '', $code); $code = str_replace('-', '', $code);
// Return false if the date of birth is in the future. // Return false if the date of birth is in the future.
if (in_array((int)($code[6]), array(3, 4, 7, 8)) && intval(substr($code, 0, 6), 10) > date('ymd')) if (in_array((int)($code[6]), array(3, 4, 7, 8)) && intval(substr($code, 0, 6), 10) > date('ymd'))
{ {
return false; return false;
} }
// Calculate the checksum. // Calculate the checksum.
$sum = 0; $sum = 0;
for ($i = 0; $i < 12; $i++) for ($i = 0; $i < 12; $i++)
@ -154,13 +154,13 @@ class Korea
} }
} }
} }
/** /**
* Check if the given string is a valid corporation registration number (법인등록번호). * Check if the given string is a valid corporation registration number (법인등록번호).
* *
* This method only checks the format. * This method only checks the format.
* It does not check that the number is actually in use. * It does not check that the number is actually in use.
* *
* @param string $code * @param string $code
* @return bool * @return bool
*/ */
@ -171,10 +171,10 @@ class Korea
{ {
return false; return false;
} }
// Remove hyphen. // Remove hyphen.
$code = str_replace('-', '', $code); $code = str_replace('-', '', $code);
// Calculate the checksum. // Calculate the checksum.
$sum = 0; $sum = 0;
for ($i = 0; $i < 12; $i++) for ($i = 0; $i < 12; $i++)
@ -182,7 +182,7 @@ class Korea
$sum += $code[$i] * (($i % 2) + 1); $sum += $code[$i] * (($i % 2) + 1);
} }
$checksum = (10 - ($sum % 10)) % 10; $checksum = (10 - ($sum % 10)) % 10;
// Check the 7th and 13th digits. // Check the 7th and 13th digits.
if ($code[6] !== '0') if ($code[6] !== '0')
{ {
@ -190,13 +190,13 @@ class Korea
} }
return $checksum === (int)($code[12]); return $checksum === (int)($code[12]);
} }
/** /**
* Check if the given string is a valid business registration number (사업자등록번호). * Check if the given string is a valid business registration number (사업자등록번호).
* *
* This method only checks the format. * This method only checks the format.
* It does not check that the number is actually in use. * It does not check that the number is actually in use.
* *
* @param string $code * @param string $code
* @return bool * @return bool
*/ */
@ -207,10 +207,10 @@ class Korea
{ {
return false; return false;
} }
// Remove hyphen. // Remove hyphen.
$code = str_replace('-', '', $code); $code = str_replace('-', '', $code);
// Calculate the checksum. // Calculate the checksum.
$sum = 0; $sum = 0;
$sum += $code[0] + ($code[1] * 3) + ($code[2] * 7); $sum += $code[0] + ($code[1] * 3) + ($code[2] * 7);
@ -218,17 +218,17 @@ class Korea
$sum += $code[6] + ($code[7] * 3) + ($code[8] * 5); $sum += $code[6] + ($code[7] * 3) + ($code[8] * 5);
$sum += floor(($code[8] * 5) / 10); $sum += floor(($code[8] * 5) / 10);
$checksum = (10 - ($sum % 10)) % 10; $checksum = (10 - ($sum % 10)) % 10;
// Check the last digit. // Check the last digit.
return $checksum === (int)($code[9]); return $checksum === (int)($code[9]);
} }
/** /**
* Check if the given IP address is Korean. * Check if the given IP address is Korean.
* *
* This method may return incorrect results if the IP allocation databases * This method may return incorrect results if the IP allocation databases
* (korea.ipv4.php, korea.ipv6.php) are out of date. * (korea.ipv4.php, korea.ipv6.php) are out of date.
* *
* @param string $ip * @param string $ip
* @return bool * @return bool
*/ */
@ -236,22 +236,22 @@ class Korea
{ {
// Extract the IPv4 address from an "IPv4-mapped IPv6" address. // Extract the IPv4 address from an "IPv4-mapped IPv6" address.
if (preg_match('/::ffff:(?:0+:)?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $ip, $matches)) $ip = $matches[1]; if (preg_match('/::ffff:(?:0+:)?([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)$/', $ip, $matches)) $ip = $matches[1];
// Return false if the IP address is not in the right format. // Return false if the IP address is not in the right format.
if (!filter_var($ip, \FILTER_VALIDATE_IP)) return false; if (!filter_var($ip, \FILTER_VALIDATE_IP)) return false;
// Check IPv4. // Check IPv4.
if (filter_var($ip, \FILTER_VALIDATE_IP, array('flags' => \FILTER_FLAG_IPV4))) if (filter_var($ip, \FILTER_VALIDATE_IP, array('flags' => \FILTER_FLAG_IPV4)))
{ {
// Convert to integer. // Convert to integer.
$ipnum = sprintf('%u', ip2long($ip)); $ipnum = sprintf('%u', ip2long($ip));
// Treat local addresses as Korean. // Treat local addresses as Korean.
if ($ipnum >= 167772160 && $ipnum <= 184549375) return true; // 10.0.0.0/8 if ($ipnum >= 167772160 && $ipnum <= 184549375) return true; // 10.0.0.0/8
if ($ipnum >= 2130706432 && $ipnum <= 2147483647) return true; // 127.0.0.0/8 if ($ipnum >= 2130706432 && $ipnum <= 2147483647) return true; // 127.0.0.0/8
if ($ipnum >= 3232235520 && $ipnum <= 3232301055) return true; // 192.168.0.0/16 if ($ipnum >= 3232235520 && $ipnum <= 3232301055) return true; // 192.168.0.0/16
if ($ipnum >= 2886729728 && $ipnum <= 2887778303) return true; // 172.16.0.0/20 if ($ipnum >= 2886729728 && $ipnum <= 2887778303) return true; // 172.16.0.0/20
// Check the IPv4 allocation database. // Check the IPv4 allocation database.
$ranges = (include \RX_BASEDIR . 'common/defaults/korea.ipv4.php'); $ranges = (include \RX_BASEDIR . 'common/defaults/korea.ipv4.php');
foreach ($ranges as $range) foreach ($ranges as $range)
@ -260,17 +260,17 @@ class Korea
} }
return false; return false;
} }
// Check IPv6. // Check IPv6.
elseif (function_exists('inet_pton')) elseif (function_exists('inet_pton'))
{ {
// Convert to hexadecimal format. // Convert to hexadecimal format.
$ipbin = strtolower(bin2hex(inet_pton($ip))); $ipbin = strtolower(bin2hex(inet_pton($ip)));
// Treat local addresses as Korean. // Treat local addresses as Korean.
if ($ipbin == '00000000000000000000000000000001') return true; // ::1 if ($ipbin == '00000000000000000000000000000001') return true; // ::1
if (preg_match('/^f(?:[cd]|e80{13})/', $ipbin)) return true; // fc00::/8, fd00::/8, fe80::/64 if (preg_match('/^f(?:[cd]|e80{13})/', $ipbin)) return true; // fc00::/8, fd00::/8, fe80::/64
// Check the IPv6 allocation database. // Check the IPv6 allocation database.
$ranges = (include \RX_BASEDIR . 'common/defaults/korea.ipv6.php'); $ranges = (include \RX_BASEDIR . 'common/defaults/korea.ipv6.php');
foreach ($ranges as $range) foreach ($ranges as $range)
@ -279,16 +279,16 @@ class Korea
} }
return false; return false;
} }
return false; return false;
} }
/** /**
* Check if the given email address is hosted by a Korean portal site. * Check if the given email address is hosted by a Korean portal site.
* *
* This can be used to tell which recipients may subscribe to the KISA RBL (kisarbl.or.kr). * This can be used to tell which recipients may subscribe to the KISA RBL (kisarbl.or.kr).
* If the domain is not found, this method returns false. * If the domain is not found, this method returns false.
* *
* @param string $domain * @param string $domain
* @param bool $clear_cache (optional) * @param bool $clear_cache (optional)
* @return bool * @return bool
@ -300,7 +300,7 @@ class Korea
{ {
self::$_domain_cache = array(); self::$_domain_cache = array();
} }
// Get the domain from the email address. // Get the domain from the email address.
if ($pos = strpos($email_address, '@')) if ($pos = strpos($email_address, '@'))
{ {
@ -311,13 +311,13 @@ class Korea
$domain = $email_address; $domain = $email_address;
} }
$domain = rtrim(strtolower($domain), '.'); $domain = rtrim(strtolower($domain), '.');
// Return cached result if available. // Return cached result if available.
if (array_key_exists($domain, self::$_domain_cache)) if (array_key_exists($domain, self::$_domain_cache))
{ {
return self::$_domain_cache[$domain]; return self::$_domain_cache[$domain];
} }
// Shortcut for known domains. // Shortcut for known domains.
if (in_array($domain, self::$known_korean)) if (in_array($domain, self::$known_korean))
{ {
@ -327,10 +327,10 @@ class Korea
{ {
return self::$_domain_cache[$domain] = false; return self::$_domain_cache[$domain] = false;
} }
// For unknown domains, check the MX record. // For unknown domains, check the MX record.
$mx = self::_getDNSRecords($domain, \DNS_MX); $mx = self::_getDNSRecords($domain, \DNS_MX);
$i = 0; $i = 0;
foreach ($mx as $mx) foreach ($mx as $mx)
{ {
@ -358,13 +358,13 @@ class Korea
break; break;
} }
} }
return self::$_domain_cache[$domain] = false; return self::$_domain_cache[$domain] = false;
} }
/** /**
* Get the DNS records of a domain. * Get the DNS records of a domain.
* *
* @param string $domain * @param string $domain
* @param int $type * @param int $type
* @return array * @return array
@ -376,7 +376,7 @@ class Korea
{ {
return array(); return array();
} }
$result = array(); $result = array();
foreach ($records as $record) foreach ($records as $record)
{ {
@ -397,16 +397,16 @@ class Korea
$result[] = $record['txt']; $result[] = $record['txt'];
} }
} }
ksort($result); ksort($result);
return $result; return $result;
} }
/** /**
* Prevent multiple lookups for the same domain. * Prevent multiple lookups for the same domain.
*/ */
protected static $_domain_cache = array(); protected static $_domain_cache = array();
/** /**
* Domains known to be Korean and subscribed to the KISA RBL. * Domains known to be Korean and subscribed to the KISA RBL.
*/ */
@ -432,7 +432,7 @@ class Korea
'empal.com', 'empal.com',
'hanafos.com', 'hanafos.com',
); );
/** /**
* Domains known to be foreign. * Domains known to be foreign.
*/ */

View file

@ -11,7 +11,7 @@ class Lang
* Instances are stored here. * Instances are stored here.
*/ */
protected static $_instances = array(); protected static $_instances = array();
/** /**
* Configuration. * Configuration.
*/ */
@ -19,10 +19,10 @@ class Lang
protected $_loaded_directories = array(); protected $_loaded_directories = array();
protected $_loaded_plugins = array(); protected $_loaded_plugins = array();
protected $_search_priority = array(); protected $_search_priority = array();
/** /**
* This method returns the cached instance of a language. * This method returns the cached instance of a language.
* *
* @param string $language * @param string $language
* @return object * @return object
*/ */
@ -38,10 +38,10 @@ class Lang
} }
return self::$_instances[$language]; return self::$_instances[$language];
} }
/** /**
* The constructor should not be called from outside. * The constructor should not be called from outside.
* *
* @param string $language * @param string $language
*/ */
protected function __construct($language) protected function __construct($language)
@ -49,20 +49,20 @@ class Lang
$this->_language = preg_replace('/[^a-z0-9_-]/i', '', $language); $this->_language = preg_replace('/[^a-z0-9_-]/i', '', $language);
$this->_loaded_plugins['_custom_'] = new \stdClass(); $this->_loaded_plugins['_custom_'] = new \stdClass();
} }
/** /**
* Return language type. * Return language type.
* *
* @return string * @return string
*/ */
public function langType() public function langType()
{ {
return $this->_language; return $this->_language;
} }
/** /**
* Load translations from a plugin (module, addon). * Load translations from a plugin (module, addon).
* *
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
@ -72,7 +72,7 @@ class Lang
{ {
return true; return true;
} }
if ($name === 'common') if ($name === 'common')
{ {
$this->loadDirectory(\RX_BASEDIR . 'common/lang', 'common'); $this->loadDirectory(\RX_BASEDIR . 'common/lang', 'common');
@ -90,10 +90,10 @@ class Lang
$this->loadDirectory(\RX_BASEDIR . "addons/$name/lang", $name); $this->loadDirectory(\RX_BASEDIR . "addons/$name/lang", $name);
} }
} }
/** /**
* Load translations from a directory. * Load translations from a directory.
* *
* @param string $dir * @param string $dir
* @param string $plugin_name * @param string $plugin_name
* @return bool * @return bool
@ -107,12 +107,12 @@ class Lang
{ {
return true; return true;
} }
// Initialize variables. // Initialize variables.
$filename = null; $filename = null;
$lang = new \stdClass; $lang = new \stdClass;
$result = true; $result = true;
// Find a suitable language file in the given directory. // Find a suitable language file in the given directory.
if (file_exists($dir . '/' . $this->_language . '.php')) if (file_exists($dir . '/' . $this->_language . '.php'))
{ {
@ -130,7 +130,7 @@ class Lang
{ {
$filename = $dir . '/' . ($this->_language === 'ja' ? 'jp' : $this->_language) . '.lang.php'; $filename = $dir . '/' . ($this->_language === 'ja' ? 'jp' : $this->_language) . '.lang.php';
} }
// Load the language file. // Load the language file.
if ($filename) if ($filename)
{ {
@ -142,23 +142,23 @@ class Lang
{ {
$result = false; $result = false;
} }
// Mark this directory and plugin as loaded. // Mark this directory and plugin as loaded.
$this->_loaded_directories[$dir] = true; $this->_loaded_directories[$dir] = true;
$this->_loaded_plugins[$plugin_name] = $lang; $this->_loaded_plugins[$plugin_name] = $lang;
// Load the same directory in the default language, too. // Load the same directory in the default language, too.
if ($this->_language !== 'en') if ($this->_language !== 'en')
{ {
self::getInstance('en')->loadDirectory($dir, $plugin_name); self::getInstance('en')->loadDirectory($dir, $plugin_name);
} }
return $result; return $result;
} }
/** /**
* Get the list of supported languages. * Get the list of supported languages.
* *
* @return array * @return array
*/ */
public static function getSupportedList() public static function getSupportedList()
@ -170,10 +170,10 @@ class Lang
} }
return $list; return $list;
} }
/** /**
* Generic getter. * Generic getter.
* *
* @param string $key * @param string $key
* @return string * @return string
*/ */
@ -185,20 +185,20 @@ class Lang
{ {
$args = $args[0]; $args = $args[0];
} }
// Get the translation. // Get the translation.
$translation = $this->__get($key); $translation = $this->__get($key);
// If there are no arguments, return the translation. // If there are no arguments, return the translation.
if (!count($args)) return $translation; if (!count($args)) return $translation;
// If there are arguments, interpolate them into the translation and return the result. // If there are arguments, interpolate them into the translation and return the result.
return vsprintf($translation, $args); return vsprintf($translation, $args);
} }
/** /**
* Generic setter. * Generic setter.
* *
* @param string $key * @param string $key
* @param string $value * @param string $value
* @return void * @return void
@ -207,10 +207,10 @@ class Lang
{ {
$this->__set($key, $value); $this->__set($key, $value);
} }
/** /**
* Fallback method for getting the default translation. * Fallback method for getting the default translation.
* *
* @param string $key * @param string $key
* @return string * @return string
*/ */
@ -225,10 +225,10 @@ class Lang
return self::getInstance('en')->__get($key); return self::getInstance('en')->__get($key);
} }
} }
/** /**
* Magic method for translations without arguments. * Magic method for translations without arguments.
* *
* @param string $key * @param string $key
* @return string * @return string
*/ */
@ -247,7 +247,7 @@ class Lang
{ {
return $this->getFromDefaultLang($key); return $this->getFromDefaultLang($key);
} }
// Find the given key. // Find the given key.
$lang = $this->_loaded_plugins[$plugin_name]; $lang = $this->_loaded_plugins[$plugin_name];
foreach ($keys as $subkey) foreach ($keys as $subkey)
@ -267,14 +267,14 @@ class Lang
} }
return is_array($lang) ? new \ArrayObject($lang, 3) : $lang; return is_array($lang) ? new \ArrayObject($lang, 3) : $lang;
} }
// Search custom translations first. // Search custom translations first.
if (isset($this->_loaded_plugins['_custom_']->{$key})) if (isset($this->_loaded_plugins['_custom_']->{$key}))
{ {
$lang = $this->_loaded_plugins['_custom_']->{$key}; $lang = $this->_loaded_plugins['_custom_']->{$key};
return is_array($lang) ? new \ArrayObject($lang, 3) : $lang; return is_array($lang) ? new \ArrayObject($lang, 3) : $lang;
} }
// Search other plugins. // Search other plugins.
foreach ($this->_search_priority as $plugin_name) foreach ($this->_search_priority as $plugin_name)
{ {
@ -284,14 +284,14 @@ class Lang
return is_array($lang) ? new \ArrayObject($lang, 3) : $lang; return is_array($lang) ? new \ArrayObject($lang, 3) : $lang;
} }
} }
// If no translation is found, return the default language. // If no translation is found, return the default language.
return $this->getFromDefaultLang($key); return $this->getFromDefaultLang($key);
} }
/** /**
* Magic method for setting a new custom translation. * Magic method for setting a new custom translation.
* *
* @param string $key * @param string $key
* @param string $value * @param string $value
* @return void * @return void
@ -311,7 +311,7 @@ class Lang
{ {
return false; return false;
} }
// Set the given key. // Set the given key.
$count = count($keys); $count = count($keys);
$lang = $this->_loaded_plugins[$plugin_name]; $lang = $this->_loaded_plugins[$plugin_name];
@ -363,14 +363,14 @@ class Lang
} }
} }
} }
// Set a regular key. // Set a regular key.
$this->_loaded_plugins['_custom_']->{$key} = $value; $this->_loaded_plugins['_custom_']->{$key} = $value;
} }
/** /**
* Magic method for checking whether a translation exists. * Magic method for checking whether a translation exists.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -385,10 +385,10 @@ class Lang
} }
return false; return false;
} }
/** /**
* Magic method for unsetting a translation. * Magic method for unsetting a translation.
* *
* @param string $key * @param string $key
* @return void * @return void
*/ */
@ -396,10 +396,10 @@ class Lang
{ {
$this->set($key, null); $this->set($key, null);
} }
/** /**
* Magic method for translations with arguments. * Magic method for translations with arguments.
* *
* @param string $key * @param string $key
* @param mixed $args * @param mixed $args
* @return string|null * @return string|null

View file

@ -9,9 +9,9 @@ class MIME
{ {
/** /**
* Get the MIME type of a file, detected by its content. * Get the MIME type of a file, detected by its content.
* *
* This method returns the MIME type of a file, or false on error. * This method returns the MIME type of a file, or false on error.
* *
* @param string $filename * @param string $filename
* @return array|false * @return array|false
*/ */
@ -38,10 +38,10 @@ class MIME
return false; return false;
} }
} }
/** /**
* Get the MIME type for the given extension. * Get the MIME type for the given extension.
* *
* @param string $extension * @param string $extension
* @return string * @return string
*/ */
@ -50,10 +50,10 @@ class MIME
$extension = strtolower($extension); $extension = strtolower($extension);
return array_key_exists($extension, self::$_types) ? self::$_types[$extension][0] : self::$_default; return array_key_exists($extension, self::$_types) ? self::$_types[$extension][0] : self::$_default;
} }
/** /**
* Get the MIME type for the given filename. * Get the MIME type for the given filename.
* *
* @param string $filename * @param string $filename
* @return string * @return string
*/ */
@ -64,10 +64,10 @@ class MIME
$extension = strtolower(substr($extension, 1)); $extension = strtolower(substr($extension, 1));
return array_key_exists($extension, self::$_types) ? self::$_types[$extension][0] : self::$_default; return array_key_exists($extension, self::$_types) ? self::$_types[$extension][0] : self::$_default;
} }
/** /**
* Get the most common extension for the given MIME type. * Get the most common extension for the given MIME type.
* *
* @param string $type * @param string $type
* @return string|false * @return string|false
*/ */
@ -82,17 +82,17 @@ class MIME
} }
return false; return false;
} }
/** /**
* The default MIME type for unknown extensions. * The default MIME type for unknown extensions.
*/ */
protected static $_default = 'application/octet-stream'; protected static $_default = 'application/octet-stream';
/** /**
* The list of known MIME types. * The list of known MIME types.
*/ */
protected static $_types = array( protected static $_types = array(
// Text-based document formats. // Text-based document formats.
'html' => ['text/html'], 'html' => ['text/html'],
'htm' => ['text/html'], 'htm' => ['text/html'],
@ -107,7 +107,7 @@ class MIME
'xsl' => ['text/xml'], 'xsl' => ['text/xml'],
'css' => ['text/css'], 'css' => ['text/css'],
'csv' => ['text/csv'], 'csv' => ['text/csv'],
// Binary document formats. // Binary document formats.
'doc' => ['application/msword'], 'doc' => ['application/msword'],
'dot' => ['application/msword'], 'dot' => ['application/msword'],
@ -124,7 +124,7 @@ class MIME
'odb' => ['application/vnd.oasis.opendocument.database'], 'odb' => ['application/vnd.oasis.opendocument.database'],
'pdf' => ['application/pdf'], 'pdf' => ['application/pdf'],
'dvi' => ['application/x-dvi'], 'dvi' => ['application/x-dvi'],
// Images. // Images.
'bmp' => ['image/bmp'], 'bmp' => ['image/bmp'],
'gif' => ['image/gif'], 'gif' => ['image/gif'],
@ -138,7 +138,7 @@ class MIME
'tiff' => ['image/tiff'], 'tiff' => ['image/tiff'],
'tif' => ['image/tiff'], 'tif' => ['image/tiff'],
'ico' => ['image/x-icon'], 'ico' => ['image/x-icon'],
// Audio. // Audio.
'mid' => ['audio/midi'], 'mid' => ['audio/midi'],
'midi' => ['audio/midi'], 'midi' => ['audio/midi'],
@ -153,7 +153,7 @@ class MIME
'aiff' => ['audio/x-aiff'], 'aiff' => ['audio/x-aiff'],
'ra' => ['audio/x-realaudio'], 'ra' => ['audio/x-realaudio'],
'm4a' => ['audio/x-m4a'], 'm4a' => ['audio/x-m4a'],
// Video. // Video.
'avi' => ['video/x-msvideo'], 'avi' => ['video/x-msvideo'],
'flv' => ['video/x-flv'], 'flv' => ['video/x-flv'],
@ -173,7 +173,7 @@ class MIME
'wma' => ['video/x-ms-asf'], 'wma' => ['video/x-ms-asf'],
'asf' => ['video/x-ms-asf'], 'asf' => ['video/x-ms-asf'],
'm4v' => ['video/x-m4v'], 'm4v' => ['video/x-m4v'],
// Other multimedia file formats. // Other multimedia file formats.
'psd' => ['application/x-photoshop'], 'psd' => ['application/x-photoshop'],
'swf' => ['application/x-shockwave-flash'], 'swf' => ['application/x-shockwave-flash'],
@ -182,11 +182,11 @@ class MIME
'ps' => ['application/postscript'], 'ps' => ['application/postscript'],
'mif' => ['application/vnd.mif'], 'mif' => ['application/vnd.mif'],
'xul' => ['application/vnd.mozilla.xul+xml'], 'xul' => ['application/vnd.mozilla.xul+xml'],
// Source code formats. // Source code formats.
'phps' => ['application/x-httpd-php-source'], 'phps' => ['application/x-httpd-php-source'],
'js' => ['application/x-javascript'], 'js' => ['application/x-javascript'],
// Archives. // Archives.
'bz2' => ['application/x-bzip'], 'bz2' => ['application/x-bzip'],
'gz' => ['application/x-gzip'], 'gz' => ['application/x-gzip'],
@ -195,13 +195,13 @@ class MIME
'gtar' => ['application/x-gtar'], 'gtar' => ['application/x-gtar'],
'rar' => ['application/x-rar-compressed'], 'rar' => ['application/x-rar-compressed'],
'zip' => ['application/x-zip'], 'zip' => ['application/x-zip'],
// Executables and packages. // Executables and packages.
'apk' => ['application/vnd.android.package-archive'], 'apk' => ['application/vnd.android.package-archive'],
'pkg' => ['application/x-newton-compatible-pkg'], 'pkg' => ['application/x-newton-compatible-pkg'],
'exe' => ['application/vnd.microsoft.portable-executable'], 'exe' => ['application/vnd.microsoft.portable-executable'],
'msi' => ['application/x-msdownload'], 'msi' => ['application/x-msdownload'],
// RFC822 email message. // RFC822 email message.
'eml' => ['message/rfc822'], 'eml' => ['message/rfc822'],
); );

View file

@ -17,16 +17,16 @@ class Mail
protected $attachments = array(); protected $attachments = array();
public $errors = array(); public $errors = array();
protected $sent = false; protected $sent = false;
/** /**
* Static properties. * Static properties.
*/ */
public static $default_driver = null; public static $default_driver = null;
public static $custom_drivers = array(); public static $custom_drivers = array();
/** /**
* Set the default driver. * Set the default driver.
* *
* @param object $driver * @param object $driver
* @return void * @return void
*/ */
@ -34,10 +34,10 @@ class Mail
{ {
self::$default_driver = $driver; self::$default_driver = $driver;
} }
/** /**
* Get the default driver. * Get the default driver.
* *
* @return object * @return object
*/ */
public static function getDefaultDriver() public static function getDefaultDriver()
@ -58,7 +58,7 @@ class Mail
} }
return self::$default_driver; return self::$default_driver;
} }
/** /**
* Add a custom mail driver. * Add a custom mail driver.
*/ */
@ -66,10 +66,10 @@ class Mail
{ {
self::$custom_drivers[] = $driver; self::$custom_drivers[] = $driver;
} }
/** /**
* Get the list of supported mail drivers. * Get the list of supported mail drivers.
* *
* @return array * @return array
*/ */
public static function getSupportedDrivers() public static function getSupportedDrivers()
@ -106,7 +106,7 @@ class Mail
ksort($result); ksort($result);
return $result; return $result;
} }
/** /**
* The constructor. * The constructor.
*/ */
@ -115,7 +115,7 @@ class Mail
$this->message = new \Swift_Message; $this->message = new \Swift_Message;
$this->driver = self::getDefaultDriver(); $this->driver = self::getDefaultDriver();
} }
/** /**
* Set the sender (From:). * Set the sender (From:).
* *
@ -136,7 +136,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Get the sender (From:). * Get the sender (From:).
* *
@ -147,7 +147,7 @@ class Mail
$list = $this->message->getFrom(); $list = $this->message->getFrom();
return $list ? array_first($this->formatAddresses($list)) : null; return $list ? array_first($this->formatAddresses($list)) : null;
} }
/** /**
* Add a recipient (To:). * Add a recipient (To:).
* *
@ -168,7 +168,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Add a recipient (CC:). * Add a recipient (CC:).
* *
@ -189,7 +189,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Add a recipient (BCC:). * Add a recipient (BCC:).
* *
@ -210,7 +210,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Get the list of recipients. * Get the list of recipients.
* *
@ -219,7 +219,7 @@ class Mail
public function getRecipients() public function getRecipients()
{ {
$result = array(); $result = array();
foreach ($this->formatAddresses($this->message->getTo()) as $address) foreach ($this->formatAddresses($this->message->getTo()) as $address)
{ {
$result[] = $address; $result[] = $address;
@ -232,10 +232,10 @@ class Mail
{ {
$result[] = $address; $result[] = $address;
} }
return array_unique($result); return array_unique($result);
} }
/** /**
* Set the Reply-To: address. * Set the Reply-To: address.
* *
@ -255,7 +255,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Set the Return-Path: address. * Set the Return-Path: address.
* *
@ -275,7 +275,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Set the Message ID. * Set the Message ID.
* *
@ -296,7 +296,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Set the In-Reply-To: header. * Set the In-Reply-To: header.
* *
@ -317,7 +317,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Set the References: header. * Set the References: header.
* *
@ -338,7 +338,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Set the subject. * Set the subject.
* *
@ -358,7 +358,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Get the subject. * Get the subject.
* *
@ -368,7 +368,7 @@ class Mail
{ {
return $this->message->getSubject(); return $this->message->getSubject();
} }
/** /**
* Set the subject (alias to setSubject). * Set the subject (alias to setSubject).
* *
@ -379,7 +379,7 @@ class Mail
{ {
return $this->setSubject($subject); return $this->setSubject($subject);
} }
/** /**
* Get the subject (alias to getSubject). * Get the subject (alias to getSubject).
* *
@ -389,7 +389,7 @@ class Mail
{ {
return $this->getSubject(); return $this->getSubject();
} }
/** /**
* Set the body content. * Set the body content.
* *
@ -403,25 +403,25 @@ class Mail
{ {
$this->setContentType($content_type); $this->setContentType($content_type);
} }
if (strpos($this->content_type, 'html') !== false) if (strpos($this->content_type, 'html') !== false)
{ {
$content = Filters\HTMLFilter::fixRelativeUrls($content); $content = Filters\HTMLFilter::fixRelativeUrls($content);
} }
$this->message->setBody($content, $this->content_type); $this->message->setBody($content, $this->content_type);
} }
/** /**
* Get the body content. * Get the body content.
* *
* @return string * @return string
*/ */
public function getBody() public function getBody()
{ {
return $this->message->getBody(); return $this->message->getBody();
} }
/** /**
* Set the body content (alias to setBody). * Set the body content (alias to setBody).
* *
@ -433,20 +433,20 @@ class Mail
{ {
return $this->setBody($content, $content_type); return $this->setBody($content, $content_type);
} }
/** /**
* Get the body content (alias to getBody). * Get the body content (alias to getBody).
* *
* @return string * @return string
*/ */
public function getContent() public function getContent()
{ {
return $this->getBody(); return $this->getBody();
} }
/** /**
* Set the content type. * Set the content type.
* *
* @param string $mode The type * @param string $mode The type
* @return void * @return void
*/ */
@ -454,17 +454,17 @@ class Mail
{ {
$this->content_type = (strpos($type, 'html') !== false) ? 'text/html' : ((strpos($type, '/') !== false) ? $type : 'text/plain'); $this->content_type = (strpos($type, 'html') !== false) ? 'text/html' : ((strpos($type, '/') !== false) ? $type : 'text/plain');
} }
/** /**
* Get the content type. * Get the content type.
* *
* @return string * @return string
*/ */
public function getContentType() public function getContentType()
{ {
return $this->content_type; return $this->content_type;
} }
/** /**
* Attach a file. * Attach a file.
* *
@ -482,11 +482,11 @@ class Mail
{ {
return false; return false;
} }
$attachment = \Swift_Attachment::fromPath($local_filename); $attachment = \Swift_Attachment::fromPath($local_filename);
$attachment->setFilename($display_filename); $attachment->setFilename($display_filename);
$result = $this->message->attach($attachment); $result = $this->message->attach($attachment);
if ($result) if ($result)
{ {
$this->attachments[] = (object)array( $this->attachments[] = (object)array(
@ -502,7 +502,7 @@ class Mail
return false; return false;
} }
} }
/** /**
* Embed a file. * Embed a file.
* *
@ -516,14 +516,14 @@ class Mail
{ {
return false; return false;
} }
$embedded = \Swift_EmbeddedFile::fromPath($local_filename); $embedded = \Swift_EmbeddedFile::fromPath($local_filename);
if ($cid !== null) if ($cid !== null)
{ {
$embedded->setId(preg_replace('/^cid:/i', '', $cid)); $embedded->setId(preg_replace('/^cid:/i', '', $cid));
} }
$result = $this->message->embed($embedded); $result = $this->message->embed($embedded);
if ($result) if ($result)
{ {
$this->attachments[] = (object)array( $this->attachments[] = (object)array(
@ -539,20 +539,20 @@ class Mail
return false; return false;
} }
} }
/** /**
* Get the list of attachments to this message. * Get the list of attachments to this message.
* *
* @return array * @return array
*/ */
public function getAttachments() public function getAttachments()
{ {
return $this->attachments; return $this->attachments;
} }
/** /**
* Send the email. * Send the email.
* *
* @return bool * @return bool
*/ */
public function send() public function send()
@ -563,20 +563,20 @@ class Mail
{ {
$this->caller = $backtrace[0]['file'] . ($backtrace[0]['line'] ? (' line ' . $backtrace[0]['line']) : ''); $this->caller = $backtrace[0]['file'] . ($backtrace[0]['line'] ? (' line ' . $backtrace[0]['line']) : '');
} }
// Reset Message-ID in case send() is called multiple times. // Reset Message-ID in case send() is called multiple times.
$random = substr(hash('sha256', mt_rand() . microtime() . getmypid()), 0, 32); $random = substr(hash('sha256', mt_rand() . microtime() . getmypid()), 0, 32);
$sender = $this->message->getFrom(); reset($sender); $sender = $this->message->getFrom(); reset($sender);
$id = $random . '@' . (preg_match('/^(.+)@([^@]+)$/', key($sender), $matches) ? $matches[2] : 'swift.generated'); $id = $random . '@' . (preg_match('/^(.+)@([^@]+)$/', key($sender), $matches) ? $matches[2] : 'swift.generated');
$this->message->getHeaders()->get('Message-ID')->setId($id); $this->message->getHeaders()->get('Message-ID')->setId($id);
$output = \ModuleHandler::triggerCall('mail.send', 'before', $this); $output = \ModuleHandler::triggerCall('mail.send', 'before', $this);
if(!$output->toBool()) if(!$output->toBool())
{ {
$this->errors[] = $output->getMessage(); $this->errors[] = $output->getMessage();
return false; return false;
} }
try try
{ {
$this->sent = $this->driver->send($this) ? true : false; $this->sent = $this->driver->send($this) ? true : false;
@ -586,46 +586,46 @@ class Mail
$this->errors[] = $e->getMessage(); $this->errors[] = $e->getMessage();
$this->sent = false; $this->sent = false;
} }
$output = \ModuleHandler::triggerCall('mail.send', 'after', $this); $output = \ModuleHandler::triggerCall('mail.send', 'after', $this);
if(!$output->toBool()) if(!$output->toBool())
{ {
$this->errors[] = $output->getMessage(); $this->errors[] = $output->getMessage();
} }
return $this->sent; return $this->sent;
} }
/** /**
* Check if the message was sent. * Check if the message was sent.
* *
* @return bool * @return bool
*/ */
public function isSent() public function isSent()
{ {
return $this->sent; return $this->sent;
} }
/** /**
* Get caller information. * Get caller information.
* *
* @return string * @return string
*/ */
public function getCaller() public function getCaller()
{ {
return $this->caller; return $this->caller;
} }
/** /**
* Get errors. * Get errors.
* *
* @return array * @return array
*/ */
public function getErrors() public function getErrors()
{ {
return $this->errors; return $this->errors;
} }
/** /**
* Convert image paths to absolute URLs. * Convert image paths to absolute URLs.
* *
@ -637,22 +637,22 @@ class Mail
{ {
return Filters\HTMLFilter::fixRelativeUrls($matches[0]); return Filters\HTMLFilter::fixRelativeUrls($matches[0]);
} }
/** /**
* Format an array of addresses for display. * Format an array of addresses for display.
* *
* @param array $addresses * @param array $addresses
* @return array * @return array
*/ */
protected function formatAddresses($addresses) protected function formatAddresses($addresses)
{ {
$result = array(); $result = array();
if (!$addresses) if (!$addresses)
{ {
return array(); return array();
} }
foreach($addresses as $email => $name) foreach($addresses as $email => $name)
{ {
if(strval($name) === '') if(strval($name) === '')
@ -664,7 +664,7 @@ class Mail
$result[] = $name . ' <' . $email . '>'; $result[] = $name . ' <' . $email . '>';
} }
} }
return $result; return $result;
} }
} }

View file

@ -12,10 +12,10 @@ class Pagination
*/ */
const COUNT_STYLE_NORMAL = 1; const COUNT_STYLE_NORMAL = 1;
const COUNT_STYLE_CONTINUOUS = 2; const COUNT_STYLE_CONTINUOUS = 2;
/** /**
* Calculate the number of pages. * Calculate the number of pages.
* *
* @param int $total_items * @param int $total_items
* @param int $items_per_page * @param int $items_per_page
* @param int $minimum (optional) * @param int $minimum (optional)
@ -32,10 +32,10 @@ class Pagination
return (int)max($minimum, ceil($total_items / $items_per_page)); return (int)max($minimum, ceil($total_items / $items_per_page));
} }
} }
/** /**
* Create HTML for pagination. * Create HTML for pagination.
* *
* @param string $base_url ($PAGE will be replaced with the page number) * @param string $base_url ($PAGE will be replaced with the page number)
* @param int $current_page * @param int $current_page
* @param int $total_pages * @param int $total_pages
@ -47,7 +47,7 @@ class Pagination
$current_page = (int)$current_page; $current_page = (int)$current_page;
$total_pages = (int)$total_pages; $total_pages = (int)$total_pages;
$count = (int)$count; $count = (int)$count;
// Determine the range of pages to show. // Determine the range of pages to show.
if ($count_style === self::COUNT_STYLE_NORMAL) if ($count_style === self::COUNT_STYLE_NORMAL)
{ {
@ -72,10 +72,10 @@ class Pagination
$first_shown = max(1, $last_shown - $count + 1); $first_shown = max(1, $last_shown - $count + 1);
} }
} }
// Open the <div> tag. // Open the <div> tag.
$return = array('<div class="pagination">'); $return = array('<div class="pagination">');
// Compose the link to the first page. // Compose the link to the first page.
if ($first_shown > 1) if ($first_shown > 1)
{ {
@ -87,11 +87,11 @@ class Pagination
{ {
$target_url = $base_url . 1; $target_url = $base_url . 1;
} }
$return[] = self::_composeLink($target_url, '<span class="arrow">&laquo;</span> <span class="page_number first_page">1</span>'); $return[] = self::_composeLink($target_url, '<span class="arrow">&laquo;</span> <span class="page_number first_page">1</span>');
$return[] = '<span class="ellipsis">...</span>'; $return[] = '<span class="ellipsis">...</span>';
} }
// Compose links for each page. // Compose links for each page.
for ($page = $first_shown; $page <= $last_shown; $page++) for ($page = $first_shown; $page <= $last_shown; $page++)
{ {
@ -103,7 +103,7 @@ class Pagination
{ {
$opening_span = '<span class="page_number">'; $opening_span = '<span class="page_number">';
} }
if (strpos($base_url, '$PAGE') !== false) if (strpos($base_url, '$PAGE') !== false)
{ {
$target_url = str_replace('$PAGE', $page, $base_url); $target_url = str_replace('$PAGE', $page, $base_url);
@ -112,10 +112,10 @@ class Pagination
{ {
$target_url = $base_url . $page; $target_url = $base_url . $page;
} }
$return[] = self::_composeLink($target_url, $opening_span . $page . '</span>'); $return[] = self::_composeLink($target_url, $opening_span . $page . '</span>');
} }
// Compose the link to the last page. // Compose the link to the last page.
if ($last_shown < $total_pages) if ($last_shown < $total_pages)
{ {
@ -127,21 +127,21 @@ class Pagination
{ {
$target_url = $base_url . $total_pages; $target_url = $base_url . $total_pages;
} }
$return[] = '<span class="ellipsis">...</span>'; $return[] = '<span class="ellipsis">...</span>';
$return[] = self::_composeLink($target_url, '<span class="page_number last_page">' . $total_pages . '</span> <span class="arrow">&raquo;</span>'); $return[] = self::_composeLink($target_url, '<span class="page_number last_page">' . $total_pages . '</span> <span class="arrow">&raquo;</span>');
} }
// Close the <div> tag. // Close the <div> tag.
$return[] = '</div>'; $return[] = '</div>';
// Return the completed HTML. // Return the completed HTML.
return implode(' ', $return); return implode(' ', $return);
} }
/** /**
* Link creation subroutine. * Link creation subroutine.
* *
* @param string $target_url * @param string $target_url
* @param string $content * @param string $content
* @return string * @return string

View file

@ -31,10 +31,10 @@ class Password
'kimsqrb' => '/\$[1-4]\$[0-9]{14}$/', 'kimsqrb' => '/\$[1-4]\$[0-9]{14}$/',
'crypt' => '/^([0-9a-zA-Z\.\/]{13}$|_[0-9a-zA-Z\.\/]{19}$|\$[156]\$)/', 'crypt' => '/^([0-9a-zA-Z\.\/]{13}$|_[0-9a-zA-Z\.\/]{19}$|\$[156]\$)/',
); );
/** /**
* Add a custom algorithm. * Add a custom algorithm.
* *
* @param string $name * @param string $name
* @param string $signature * @param string $signature
* @param callable $callback * @param callable $callback
@ -45,10 +45,10 @@ class Password
self::$_algorithm_signatures[$name] = $signature; self::$_algorithm_signatures[$name] = $signature;
self::$_algorithm_callbacks[$name] = $callback; self::$_algorithm_callbacks[$name] = $callback;
} }
/** /**
* Check if the given sequence of algorithms is valid. * Check if the given sequence of algorithms is valid.
* *
* @param array|string $algos * @param array|string $algos
* @return bool * @return bool
*/ */
@ -70,10 +70,10 @@ class Password
} }
return true; return true;
} }
/** /**
* Get the list of hashing algorithms supported by this server. * Get the list of hashing algorithms supported by this server.
* *
* @return array * @return array
*/ */
public static function getSupportedAlgorithms() public static function getSupportedAlgorithms()
@ -96,7 +96,7 @@ class Password
/** /**
* Get the best hashing algorithm supported by this server. * Get the best hashing algorithm supported by this server.
* *
* @return string * @return string
*/ */
public static function getBestSupportedAlgorithm() public static function getBestSupportedAlgorithm()
@ -107,7 +107,7 @@ class Password
/** /**
* Get the current default hashing algorithm. * Get the current default hashing algorithm.
* *
* @return string * @return string
*/ */
public static function getDefaultAlgorithm() public static function getDefaultAlgorithm()
@ -130,7 +130,7 @@ class Password
/** /**
* Get the currently configured work factor for bcrypt and other adjustable algorithms. * Get the currently configured work factor for bcrypt and other adjustable algorithms.
* *
* @return int * @return int
*/ */
public static function getWorkFactor() public static function getWorkFactor()
@ -148,13 +148,13 @@ class Password
{ {
$work_factor = 10; $work_factor = 10;
} }
return $work_factor; return $work_factor;
} }
/** /**
* Generate a reasonably strong random password. * Generate a reasonably strong random password.
* *
* @param int $length * @param int $length
* @return string * @return string
*/ */
@ -176,14 +176,14 @@ class Password
} }
} }
} }
/** /**
* Hash a password. * Hash a password.
* *
* To use multiple algorithms in series, provide them as an array. * To use multiple algorithms in series, provide them as an array.
* Salted algorithms such as bcrypt, pbkdf2, or portable must be used last. * Salted algorithms such as bcrypt, pbkdf2, or portable must be used last.
* On error, false will be returned. * On error, false will be returned.
* *
* @param string $password * @param string $password
* @param string|array $algos (optional) * @param string|array $algos (optional)
* @param string $salt (optional) * @param string $salt (optional)
@ -196,11 +196,11 @@ class Password
{ {
$algos = self::getDefaultAlgorithm(); $algos = self::getDefaultAlgorithm();
} }
// Initialize the chain of hashes. // Initialize the chain of hashes.
$algos = array_map('strtolower', array_map('trim', is_array($algos) ? $algos : explode(',', $algos))); $algos = array_map('strtolower', array_map('trim', is_array($algos) ? $algos : explode(',', $algos)));
$hashchain = preg_replace('/\\s+/', ' ', trim($password)); $hashchain = preg_replace('/\\s+/', ' ', trim($password));
// Apply the given algorithms one by one. // Apply the given algorithms one by one.
foreach ($algos as $algo) foreach ($algos as $algo)
{ {
@ -211,7 +211,7 @@ class Password
$hashchain = self::bcrypt($hashchain, $salt, self::getWorkFactor()); $hashchain = self::bcrypt($hashchain, $salt, self::getWorkFactor());
if ($hashchain[0] === '*') return false; if ($hashchain[0] === '*') return false;
return $hashchain; return $hashchain;
// PBKDF2 (must be used last) // PBKDF2 (must be used last)
case 'pbkdf2': case 'pbkdf2':
if ($salt === null) if ($salt === null)
@ -231,7 +231,7 @@ class Password
} }
$iterations_padding = ($salt === null || !isset($parts[1])) ? 7 : strlen($parts[1]); $iterations_padding = ($salt === null || !isset($parts[1])) ? 7 : strlen($parts[1]);
return self::pbkdf2($hashchain, $salt, $hash_algorithm, $iterations, $key_length, $iterations_padding); return self::pbkdf2($hashchain, $salt, $hash_algorithm, $iterations, $key_length, $iterations_padding);
// phpass portable algorithm (must be used last) // phpass portable algorithm (must be used last)
case 'portable': case 'portable':
$phpass = new \Hautelook\Phpass\PasswordHash(self::getWorkFactor(), true); $phpass = new \Hautelook\Phpass\PasswordHash(self::getWorkFactor(), true);
@ -245,47 +245,47 @@ class Password
$match = $phpass->CheckPassword($hashchain, $salt); $match = $phpass->CheckPassword($hashchain, $salt);
return $match ? $salt : false; return $match ? $salt : false;
} }
// Drupal's SHA-512 based algorithm (must be used last) // Drupal's SHA-512 based algorithm (must be used last)
case 'drupal': case 'drupal':
$hashchain = \VendorPass::drupal($password, $salt); $hashchain = \VendorPass::drupal($password, $salt);
return $hashchain; return $hashchain;
// Joomla's MD5 based algorithm (must be used last) // Joomla's MD5 based algorithm (must be used last)
case 'joomla': case 'joomla':
$hashchain = \VendorPass::joomla($password, $salt); $hashchain = \VendorPass::joomla($password, $salt);
return $hashchain; return $hashchain;
// KimsQ Rb algorithms (must be used last) // KimsQ Rb algorithms (must be used last)
case 'kimsqrb': case 'kimsqrb':
$hashchain = \VendorPass::kimsqrb($password, $salt); $hashchain = \VendorPass::kimsqrb($password, $salt);
return $hashchain; return $hashchain;
// crypt() function (must be used last) // crypt() function (must be used last)
case 'crypt': case 'crypt':
if ($salt === null) $salt = Security::getRandom(2, 'alnum'); if ($salt === null) $salt = Security::getRandom(2, 'alnum');
$hashchain = crypt($hashchain, $salt); $hashchain = crypt($hashchain, $salt);
return $hashchain; return $hashchain;
// MS SQL's PWDENCRYPT() function (must be used last) // MS SQL's PWDENCRYPT() function (must be used last)
case 'mssql_pwdencrypt': case 'mssql_pwdencrypt':
$hashchain = \VendorPass::mssql_pwdencrypt($hashchain, $salt); $hashchain = \VendorPass::mssql_pwdencrypt($hashchain, $salt);
return $hashchain; return $hashchain;
// MySQL's old PASSWORD() function. // MySQL's old PASSWORD() function.
case 'mysql_old_password': case 'mysql_old_password':
$hashchain = \VendorPass::mysql_old_password($hashchain); $hashchain = \VendorPass::mysql_old_password($hashchain);
break; break;
// MySQL's new PASSWORD() function. // MySQL's new PASSWORD() function.
case 'mysql_new_password': case 'mysql_new_password':
$hashchain = \VendorPass::mysql_new_password($hashchain); $hashchain = \VendorPass::mysql_new_password($hashchain);
break; break;
// A dummy algorithm that does nothing. // A dummy algorithm that does nothing.
case 'null': case 'null':
break; break;
// All other algorithms will be passed to hash() or treated as a function name. // All other algorithms will be passed to hash() or treated as a function name.
default: default:
if (isset(self::$_algorithm_callbacks[$algo])) if (isset(self::$_algorithm_callbacks[$algo]))
@ -307,16 +307,16 @@ class Password
} }
} }
} }
return $hashchain; return $hashchain;
} }
/** /**
* Check a password against a hash. * Check a password against a hash.
* *
* This method returns true if the password is correct, and false otherwise. * This method returns true if the password is correct, and false otherwise.
* If the algorithm is not specified, it will be guessed from the format of the hash. * If the algorithm is not specified, it will be guessed from the format of the hash.
* *
* @param string $password * @param string $password
* @param string $hash * @param string $hash
* @param array|string $algos * @param array|string $algos
@ -341,12 +341,12 @@ class Password
return Security::compareStrings($hash, self::hashPassword($password, $algos, $hash)); return Security::compareStrings($hash, self::hashPassword($password, $algos, $hash));
} }
} }
/** /**
* Guess which algorithm(s) were used to generate the given hash. * Guess which algorithm(s) were used to generate the given hash.
* *
* If there are multiple possibilities, all of them will be returned in an array. * If there are multiple possibilities, all of them will be returned in an array.
* *
* @param string $hash * @param string $hash
* @return array * @return array
*/ */
@ -359,10 +359,10 @@ class Password
} }
return $candidates; return $candidates;
} }
/** /**
* Check the work factor of a hash. * Check the work factor of a hash.
* *
* @param string $hash * @param string $hash
* @return int * @return int
*/ */
@ -381,10 +381,10 @@ class Password
return 0; return 0;
} }
} }
/** /**
* Generate the bcrypt hash of a string. * Generate the bcrypt hash of a string.
* *
* @param string $password * @param string $password
* @param string $salt (optional) * @param string $salt (optional)
* @param int $work_factor (optional) * @param int $work_factor (optional)
@ -396,13 +396,13 @@ class Password
{ {
$salt = '$2y$' . sprintf('%02d', $work_factor) . '$' . Security::getRandom(22, 'alnum'); $salt = '$2y$' . sprintf('%02d', $work_factor) . '$' . Security::getRandom(22, 'alnum');
} }
return crypt($password, $salt); return crypt($password, $salt);
} }
/** /**
* Generate the PBKDF2 hash of a string. * Generate the PBKDF2 hash of a string.
* *
* @param string $password * @param string $password
* @param string $salt (optional) * @param string $salt (optional)
* @param string $algorithm (optional) * @param string $algorithm (optional)
@ -417,7 +417,7 @@ class Password
{ {
$salt = Security::getRandom(12, 'alnum'); $salt = Security::getRandom(12, 'alnum');
} }
if (function_exists('hash_pbkdf2')) if (function_exists('hash_pbkdf2'))
{ {
$hash = hash_pbkdf2($algorithm, $password, $salt, $iterations, $length, true); $hash = hash_pbkdf2($algorithm, $password, $salt, $iterations, $length, true);
@ -438,24 +438,24 @@ class Password
} }
$hash = substr($output, 0, $length); $hash = substr($output, 0, $length);
} }
return $algorithm . ':' . str_pad($iterations, $iterations_padding, '0', STR_PAD_LEFT) . ':' . $salt . ':' . base64_encode($hash); return $algorithm . ':' . str_pad($iterations, $iterations_padding, '0', STR_PAD_LEFT) . ':' . $salt . ':' . base64_encode($hash);
} }
/** /**
* Count the amount of entropy that a password contains. * Count the amount of entropy that a password contains.
* *
* @param string $password * @param string $password
* @return int * @return int
*/ */
public static function countEntropyBits($password) public static function countEntropyBits($password)
{ {
// An empty string has no entropy. // An empty string has no entropy.
if ($password === '') return 0; if ($password === '') return 0;
// Common character sets and the number of possible mutations. // Common character sets and the number of possible mutations.
static $entropy_per_char = array( static $entropy_per_char = array(
'/^[0-9]+$/' => 10, '/^[0-9]+$/' => 10,
'/^[a-z]+$/' => 26, '/^[a-z]+$/' => 26,
@ -468,7 +468,7 @@ class Password
'/^[\\x20-\\x7e]+$/' => 95, '/^[\\x20-\\x7e]+$/' => 95,
'/^[\\x00-\\x7f]+$/' => 128, '/^[\\x00-\\x7f]+$/' => 128,
); );
foreach ($entropy_per_char as $regex => $entropy) foreach ($entropy_per_char as $regex => $entropy)
{ {
if (preg_match($regex, $password)) if (preg_match($regex, $password))
@ -476,7 +476,7 @@ class Password
return log(pow($entropy, strlen($password)), 2); return log(pow($entropy, strlen($password)), 2);
} }
} }
return strlen($password) * 8; return strlen($password) * 8;
} }
} }

View file

@ -26,10 +26,10 @@ class Push
* Static properties. * Static properties.
*/ */
protected static $_drivers = array(); protected static $_drivers = array();
/** /**
* Add a custom Push driver. * Add a custom Push driver.
* *
* @param string $name * @param string $name
* @param object $driver * @param object $driver
* @return void * @return void
@ -38,10 +38,10 @@ class Push
{ {
self::$_drivers[$name] = $driver; self::$_drivers[$name] = $driver;
} }
/** /**
* Get the default driver. * Get the default driver.
* *
* @param string $name * @param string $name
* @return object|null * @return object|null
*/ */
@ -51,7 +51,7 @@ class Push
{ {
return self::$_drivers[$name]; return self::$_drivers[$name];
} }
$driver_class = '\Rhymix\Framework\Drivers\Push\\' . $name; $driver_class = '\Rhymix\Framework\Drivers\Push\\' . $name;
if (class_exists($driver_class)) if (class_exists($driver_class))
{ {
@ -63,10 +63,10 @@ class Push
return null; return null;
} }
} }
/** /**
* Get the list of supported Push drivers. * Get the list of supported Push drivers.
* *
* @return array * @return array
*/ */
public static function getSupportedDrivers(): array public static function getSupportedDrivers(): array
@ -99,15 +99,15 @@ class Push
ksort($result); ksort($result);
return $result; return $result;
} }
/** /**
* The constructor. * The constructor.
*/ */
public function __construct() public function __construct()
{ {
} }
/** /**
* Set the sender's member_srl. * Set the sender's member_srl.
* *
@ -119,7 +119,7 @@ class Push
$this->from = $member_srl; $this->from = $member_srl;
return true; return true;
} }
/** /**
* Get the sender's phone number. * Get the sender's phone number.
* *
@ -129,7 +129,7 @@ class Push
{ {
return intval($this->from); return intval($this->from);
} }
/** /**
* Add a recipient. * Add a recipient.
* *
@ -141,7 +141,7 @@ class Push
$this->to[] = $member_srl; $this->to[] = $member_srl;
return true; return true;
} }
/** /**
* Get the list of recipients without country codes. * Get the list of recipients without country codes.
* *
@ -151,7 +151,7 @@ class Push
{ {
return $this->to; return $this->to;
} }
/** /**
* Set the subject. * Set the subject.
* *
@ -163,7 +163,7 @@ class Push
$this->subject = utf8_trim(utf8_clean($subject)); $this->subject = utf8_trim(utf8_clean($subject));
return true; return true;
} }
/** /**
* Get the subject. * Get the subject.
* *
@ -173,7 +173,7 @@ class Push
{ {
return $this->subject; return $this->subject;
} }
/** /**
* Set the content. * Set the content.
* *
@ -186,17 +186,17 @@ class Push
$this->content = strtr($this->content, array("\r\n" => "\n")); $this->content = strtr($this->content, array("\r\n" => "\n"));
return true; return true;
} }
/** /**
* Get the content. * Get the content.
* *
* @return string * @return string
*/ */
public function getContent(): string public function getContent(): string
{ {
return $this->content; return $this->content;
} }
/** /**
* Set an click-action to associate with this push notification. * Set an click-action to associate with this push notification.
* *
@ -211,14 +211,14 @@ class Push
/** /**
* Get the click-action associated with this push notification. * Get the click-action associated with this push notification.
* *
* @return string * @return string
*/ */
public function getClickAction(): string public function getClickAction(): string
{ {
return $this->metadata['click_action']; return $this->metadata['click_action'];
} }
/** /**
* Set a sound to associate with this push notification. * Set a sound to associate with this push notification.
* *
@ -230,7 +230,7 @@ class Push
$this->metadata['sound'] = utf8_trim(utf8_clean($sound)); $this->metadata['sound'] = utf8_trim(utf8_clean($sound));
return true; return true;
} }
/** /**
* Set a badge to associate with this push notification. * Set a badge to associate with this push notification.
* *
@ -266,7 +266,7 @@ class Push
$this->metadata['tag'] = utf8_trim(utf8_clean($tag)); $this->metadata['tag'] = utf8_trim(utf8_clean($tag));
return true; return true;
} }
/** /**
* Set a color to associate with this push notification. * Set a color to associate with this push notification.
* *
@ -278,7 +278,7 @@ class Push
$this->metadata['color'] = utf8_trim(utf8_clean($color)); $this->metadata['color'] = utf8_trim(utf8_clean($color));
return true; return true;
} }
/** /**
* Set an android-channel-id to associate with this push notification. * Set an android-channel-id to associate with this push notification.
* *
@ -290,10 +290,10 @@ class Push
$this->metadata['android_channel_id'] = utf8_trim(utf8_clean($android_channel_id)); $this->metadata['android_channel_id'] = utf8_trim(utf8_clean($android_channel_id));
return true; return true;
} }
/** /**
* Get notification array * Get notification array
* *
* @return array * @return array
*/ */
public function getMetadata(): array public function getMetadata(): array
@ -314,17 +314,17 @@ class Push
$this->data = $data; $this->data = $data;
return true; return true;
} }
/** /**
* Get the data associated with this push notification. * Get the data associated with this push notification.
* *
* @return array * @return array
*/ */
public function getData(): array public function getData(): array
{ {
return $this->data; return $this->data;
} }
/** /**
* Set a URL to associate with this push notification. * Set a URL to associate with this push notification.
* *
@ -336,20 +336,20 @@ class Push
$this->data['url'] = $url; $this->data['url'] = $url;
return true; return true;
} }
/** /**
* Get the URL associated with this push notification. * Get the URL associated with this push notification.
* *
* @return string * @return string
*/ */
public function getURL(): string public function getURL(): string
{ {
return $this->data['url']; return $this->data['url'];
} }
/** /**
* Send the message. * Send the message.
* *
* @return bool * @return bool
*/ */
public function send(): bool public function send(): bool
@ -360,19 +360,19 @@ class Push
{ {
$this->caller = $backtrace[0]['file'] . ($backtrace[0]['line'] ? (' line ' . $backtrace[0]['line']) : ''); $this->caller = $backtrace[0]['file'] . ($backtrace[0]['line'] ? (' line ' . $backtrace[0]['line']) : '');
} }
$output = \ModuleHandler::triggerCall('push.send', 'before', $this); $output = \ModuleHandler::triggerCall('push.send', 'before', $this);
if(!$output->toBool()) if(!$output->toBool())
{ {
$this->errors[] = $output->getMessage(); $this->errors[] = $output->getMessage();
return false; return false;
} }
try try
{ {
$tokens = $this->_getDeviceTokens(); $tokens = $this->_getDeviceTokens();
$output = null; $output = null;
// Android FCM // Android FCM
if(count($tokens->fcm)) if(count($tokens->fcm))
{ {
@ -398,28 +398,28 @@ class Push
$this->_deleteInvalidTokens($output->invalid); $this->_deleteInvalidTokens($output->invalid);
$this->_updateDeviceTokens($output->needUpdate); $this->_updateDeviceTokens($output->needUpdate);
} }
} }
catch(\Exception $e) catch(\Exception $e)
{ {
$this->errors[] = class_basename($e) . ': ' . $e->getMessage(); $this->errors[] = class_basename($e) . ': ' . $e->getMessage();
$this->sent = false; $this->sent = false;
} }
$output = \ModuleHandler::triggerCall('push.send', 'after', $this); $output = \ModuleHandler::triggerCall('push.send', 'after', $this);
if(!$output->toBool()) if(!$output->toBool())
{ {
$this->errors[] = $output->getMessage(); $this->errors[] = $output->getMessage();
} }
return $this->sent > 0 ? true : false; return $this->sent > 0 ? true : false;
} }
/** /**
* Get the device token * Get the device token
* *
* @return \stdClass * @return \stdClass
* *
*/ */
protected function _getDeviceTokens(): \stdClass protected function _getDeviceTokens(): \stdClass
{ {
@ -461,7 +461,7 @@ class Push
/** /**
* Delete the device toekn * Delete the device toekn
* *
* @param array * @param array
* @return void * @return void
*/ */
@ -478,7 +478,7 @@ class Push
/** /**
* Update the device toekn * Update the device toekn
* *
* @param array * @param array
* @return void * @return void
*/ */
@ -492,70 +492,70 @@ class Push
executeQueryArray('member.updateMemberDevice', $args); executeQueryArray('member.updateMemberDevice', $args);
} }
} }
/** /**
* Check if the message was sent. * Check if the message was sent.
* *
* @return bool * @return bool
*/ */
public function isSent(): bool public function isSent(): bool
{ {
return $this->sent > 0 ? true : false; return $this->sent > 0 ? true : false;
} }
/** /**
* Get caller information. * Get caller information.
* *
* @return string * @return string
*/ */
public function getCaller(): string public function getCaller(): string
{ {
return $this->caller; return $this->caller;
} }
/** /**
* Get errors. * Get errors.
* *
* @return array * @return array
*/ */
public function getErrors(): array public function getErrors(): array
{ {
return $this->errors; return $this->errors;
} }
/** /**
* Get success tokens. * Get success tokens.
* *
* @return array * @return array
*/ */
public function getSuccessTokens(): array public function getSuccessTokens(): array
{ {
return $this->success_tokens; return $this->success_tokens;
} }
/** /**
* Get deleted tokens. * Get deleted tokens.
* *
* @return array * @return array
*/ */
public function getDeletedTokens(): array public function getDeletedTokens(): array
{ {
return $this->deleted_tokens; return $this->deleted_tokens;
} }
/** /**
* Get updated tokens. * Get updated tokens.
* *
* @return array * @return array
*/ */
public function getUpdatedTokens(): array public function getUpdatedTokens(): array
{ {
return $this->updated_tokens; return $this->updated_tokens;
} }
/** /**
* Add an error message. * Add an error message.
* *
* @param string $message * @param string $message
* @return void * @return void
*/ */

View file

@ -65,7 +65,7 @@ class Router
'priority' => 0, 'priority' => 0,
), ),
); );
/** /**
* List of legacy URLs that should not be treated as prefixes. * List of legacy URLs that should not be treated as prefixes.
*/ */
@ -73,14 +73,14 @@ class Router
'rss' => true, 'rss' => true,
'atom' => true, 'atom' => true,
); );
/** /**
* List of legacy modules whose URLs should not be shortened. * List of legacy modules whose URLs should not be shortened.
*/ */
protected static $_except_modules = array( protected static $_except_modules = array(
'socialxe' => true, 'socialxe' => true,
); );
/** /**
* Internal cache for module and route information. * Internal cache for module and route information.
*/ */
@ -89,14 +89,14 @@ class Router
protected static $_global_forwarded_cache = array(); protected static $_global_forwarded_cache = array();
protected static $_internal_forwarded_cache = array(); protected static $_internal_forwarded_cache = array();
protected static $_route_cache = array(); protected static $_route_cache = array();
/** /**
* Return the currently configured rewrite level. * Return the currently configured rewrite level.
* *
* 0 = None * 0 = None
* 1 = XE-compatible rewrite rules only * 1 = XE-compatible rewrite rules only
* 2 = Full rewrite support * 2 = Full rewrite support
* *
* @return int * @return int
*/ */
public static function getRewriteLevel(): int public static function getRewriteLevel(): int
@ -108,10 +108,10 @@ class Router
} }
return intval($level); return intval($level);
} }
/** /**
* Extract request arguments from the current URL. * Extract request arguments from the current URL.
* *
* @param string $method * @param string $method
* @param string $url * @param string $url
* @param int $rewrite_level * @param int $rewrite_level
@ -128,7 +128,7 @@ class Router
$result->act = ''; $result->act = '';
$result->forwarded = false; $result->forwarded = false;
$result->args = array(); $result->args = array();
// Separate additional arguments from the URL. // Separate additional arguments from the URL.
$args = array(); $args = array();
$argstart = strpos($url, '?'); $argstart = strpos($url, '?');
@ -138,7 +138,7 @@ class Router
$url = substr($url, 0, $argstart); $url = substr($url, 0, $argstart);
$result->args = $args; $result->args = $args;
} }
// Decode the URL into plain UTF-8. // Decode the URL into plain UTF-8.
$url = $result->url = urldecode($url); $url = $result->url = urldecode($url);
if ($url === '') if ($url === '')
@ -150,7 +150,7 @@ class Router
$result->status = 404; $result->status = 404;
return $result; return $result;
} }
// Try to detect the prefix. This might be $mid. // Try to detect the prefix. This might be $mid.
if ($rewrite_level >= 2 && preg_match('#^([a-zA-Z0-9_-]+)(?:/(.*))?$#s', $url, $matches) && !isset(self::$_except_prefixes[$matches[1]])) if ($rewrite_level >= 2 && preg_match('#^([a-zA-Z0-9_-]+)(?:/(.*))?$#s', $url, $matches) && !isset(self::$_except_prefixes[$matches[1]]))
{ {
@ -158,7 +158,7 @@ class Router
$prefix = $matches[1]; $prefix = $matches[1];
$internal_url = $matches[2] ?? ''; $internal_url = $matches[2] ?? '';
$prefix_type = 'mid'; $prefix_type = 'mid';
// Find the module associated with this prefix. // Find the module associated with this prefix.
$module_name = ''; $module_name = '';
$action_info = self::_getActionInfoByPrefix($prefix, $module_name); $action_info = self::_getActionInfoByPrefix($prefix, $module_name);
@ -171,7 +171,7 @@ class Router
$prefix_type = 'module'; $prefix_type = 'module';
} }
} }
// If a module is found, try its routes. // If a module is found, try its routes.
if ($action_info) if ($action_info)
{ {
@ -184,7 +184,7 @@ class Router
$result->args = $allargs; $result->args = $allargs;
return $result; return $result;
} }
// Try the list of routes defined by the module. // Try the list of routes defined by the module.
foreach ($action_info->route->{$method} as $regexp => $action) foreach ($action_info->route->{$method} as $regexp => $action)
{ {
@ -199,7 +199,7 @@ class Router
return $result; return $result;
} }
} }
// Check other modules. // Check other modules.
if ($prefix_type === 'mid') if ($prefix_type === 'mid')
{ {
@ -219,7 +219,7 @@ class Router
} }
} }
} }
// Try the generic mid/act pattern. // Try the generic mid/act pattern.
if (preg_match('#^[a-zA-Z0-9_]+$#', $internal_url)) if (preg_match('#^[a-zA-Z0-9_]+$#', $internal_url))
{ {
@ -231,7 +231,7 @@ class Router
$result->args = $allargs; $result->args = $allargs;
return $result; return $result;
} }
// If the module defines a 404 error handler, call it. // If the module defines a 404 error handler, call it.
if ($internal_url && isset($action_info->error_handlers[404])) if ($internal_url && isset($action_info->error_handlers[404]))
{ {
@ -245,7 +245,7 @@ class Router
} }
} }
} }
// Try registered global routes. // Try registered global routes.
if ($rewrite_level >= 2) if ($rewrite_level >= 2)
{ {
@ -264,7 +264,7 @@ class Router
} }
} }
} }
// Try XE-compatible global routes. // Try XE-compatible global routes.
foreach (self::$_global_routes as $route_info) foreach (self::$_global_routes as $route_info)
{ {
@ -280,7 +280,7 @@ class Router
return $result; return $result;
} }
} }
// If no pattern matches, return either an empty route or a 404 error. // If no pattern matches, return either an empty route or a 404 error.
$result->module = isset($args['module']) ? $args['module'] : ''; $result->module = isset($args['module']) ? $args['module'] : '';
$result->mid = isset($args['mid']) ? $args['mid'] : ''; $result->mid = isset($args['mid']) ? $args['mid'] : '';
@ -297,10 +297,10 @@ class Router
return $result; return $result;
} }
} }
/** /**
* Create a URL for the given set of arguments. * Create a URL for the given set of arguments.
* *
* @param array $args * @param array $args
* @param int $rewrite_level * @param int $rewrite_level
* @return string * @return string
@ -312,23 +312,23 @@ class Router
{ {
return 'index.php?' . http_build_query($args); return 'index.php?' . http_build_query($args);
} }
// Cache the number of arguments and their keys. // Cache the number of arguments and their keys.
$count = count($args); $count = count($args);
$keys = array_keys($args); $keys = array_keys($args);
// If there are no arguments, return the URL of the main page. // If there are no arguments, return the URL of the main page.
if ($count == 0) if ($count == 0)
{ {
return ''; return '';
} }
// If there is only one argument, try either $mid or $document_srl. // If there is only one argument, try either $mid or $document_srl.
if ($rewrite_level >= 1 && $count == 1 && ($keys[0] === 'mid' || $keys[0] === 'document_srl')) if ($rewrite_level >= 1 && $count == 1 && ($keys[0] === 'mid' || $keys[0] === 'document_srl'))
{ {
return urlencode($args[$keys[0]]); return urlencode($args[$keys[0]]);
} }
// If the list of keys is already cached, return the corresponding route. // If the list of keys is already cached, return the corresponding route.
$keys_sorted = $keys; sort($keys_sorted); $keys_sorted = $keys; sort($keys_sorted);
$keys_string = implode('.', $keys_sorted) . ':' . ($args['mid'] ?? '') . ':' . ($args['act'] ?? ''); $keys_string = implode('.', $keys_sorted) . ':' . ($args['mid'] ?? '') . ':' . ($args['act'] ?? '');
@ -336,10 +336,10 @@ class Router
{ {
return self::_insertRouteVars(self::$_route_cache[$rewrite_level][$keys_string], $args); return self::_insertRouteVars(self::$_route_cache[$rewrite_level][$keys_string], $args);
} }
// Remove $mid and $act from arguments and work with the remainder. // Remove $mid and $act from arguments and work with the remainder.
$args2 = $args; unset($args2['module'], $args2['mid'], $args2['act']); $args2 = $args; unset($args2['module'], $args2['mid'], $args2['act']);
// If $mid exists, try routes defined in the module. // If $mid exists, try routes defined in the module.
if ($rewrite_level >= 2 && (isset($args['mid']) || isset($args['module']))) if ($rewrite_level >= 2 && (isset($args['mid']) || isset($args['module'])))
{ {
@ -354,10 +354,10 @@ class Router
$action_info = self::_getActionInfoByModule($args['module']); $action_info = self::_getActionInfoByModule($args['module']);
$prefix_type = 'module'; $prefix_type = 'module';
} }
// If there is no $act, use the default action. // If there is no $act, use the default action.
$act = isset($args['act']) ? $args['act'] : $action_info->default_index_act; $act = isset($args['act']) ? $args['act'] : $action_info->default_index_act;
// Check if $act has any routes defined. // Check if $act has any routes defined.
$action = $action_info->action->{$act} ?? null; $action = $action_info->action->{$act} ?? null;
if ($action && $action->route) if ($action && $action->route)
@ -375,7 +375,7 @@ class Router
return $args[$prefix_type]; return $args[$prefix_type];
} }
} }
// Check other modules for $act. // Check other modules for $act.
if ($prefix_type === 'mid') if ($prefix_type === 'mid')
{ {
@ -391,7 +391,7 @@ class Router
} }
} }
} }
// Try the generic mid/act pattern. // Try the generic mid/act pattern.
if (($prefix_type !== 'module' || !isset(self::$_except_modules[$args[$prefix_type]])) && isset($args['act'])) if (($prefix_type !== 'module' || !isset(self::$_except_modules[$args[$prefix_type]])) && isset($args['act']))
{ {
@ -400,7 +400,7 @@ class Router
return $args[$prefix_type] . ($internal_url ? ('/' . $internal_url) : ''); return $args[$prefix_type] . ($internal_url ? ('/' . $internal_url) : '');
} }
} }
// Try registered global routes. // Try registered global routes.
if ($rewrite_level >= 2 && isset($args['act'])) if ($rewrite_level >= 2 && isset($args['act']))
{ {
@ -415,7 +415,7 @@ class Router
} }
} }
} }
// Try XE-compatible global routes. // Try XE-compatible global routes.
if ($rewrite_level >= 1) if ($rewrite_level >= 1)
{ {
@ -429,15 +429,15 @@ class Router
} }
} }
} }
// If no route matches, just create a query string. // If no route matches, just create a query string.
self::$_route_cache[$rewrite_level][$keys_string] = 'index.php'; self::$_route_cache[$rewrite_level][$keys_string] = 'index.php';
return 'index.php?' . http_build_query($args); return 'index.php?' . http_build_query($args);
} }
/** /**
* Load and cache module action info. * Load and cache module action info.
* *
* @param string $prefix * @param string $prefix
* @return object * @return object
*/ */
@ -448,7 +448,7 @@ class Router
$module_name = self::$_action_cache_prefix[$prefix]; $module_name = self::$_action_cache_prefix[$prefix];
return self::_getActionInfoByModule(self::$_action_cache_prefix[$prefix]) ?: false; return self::_getActionInfoByModule(self::$_action_cache_prefix[$prefix]) ?: false;
} }
$module_info = \ModuleModel::getModuleInfoByMid($prefix); $module_info = \ModuleModel::getModuleInfoByMid($prefix);
if ($module_info && $module_info->module) if ($module_info && $module_info->module)
{ {
@ -460,10 +460,10 @@ class Router
return self::$_action_cache_prefix[$prefix] = false; return self::$_action_cache_prefix[$prefix] = false;
} }
} }
/** /**
* Load and cache module action info. * Load and cache module action info.
* *
* @param string $prefix * @param string $prefix
* @return object * @return object
*/ */
@ -473,14 +473,14 @@ class Router
{ {
return self::$_action_cache_module[$module]; return self::$_action_cache_module[$module];
} }
$action_info = \ModuleModel::getModuleActionXml($module); $action_info = \ModuleModel::getModuleActionXml($module);
return self::$_action_cache_module[$module] = $action_info ?: false; return self::$_action_cache_module[$module] = $action_info ?: false;
} }
/** /**
* Get the list of routes that are registered for action-forward. * Get the list of routes that are registered for action-forward.
* *
* @param string $type * @param string $type
* @return array * @return array
*/ */
@ -494,14 +494,14 @@ class Router
{ {
return self::$_global_forwarded_cache; return self::$_global_forwarded_cache;
} }
self::$_global_forwarded_cache['GET'] = array(); self::$_global_forwarded_cache['GET'] = array();
self::$_global_forwarded_cache['POST'] = array(); self::$_global_forwarded_cache['POST'] = array();
self::$_global_forwarded_cache['reverse'] = array(); self::$_global_forwarded_cache['reverse'] = array();
self::$_internal_forwarded_cache['GET'] = array(); self::$_internal_forwarded_cache['GET'] = array();
self::$_internal_forwarded_cache['POST'] = array(); self::$_internal_forwarded_cache['POST'] = array();
self::$_internal_forwarded_cache['reverse'] = array(); self::$_internal_forwarded_cache['reverse'] = array();
$action_forward = \ModuleModel::getActionForward(); $action_forward = \ModuleModel::getActionForward();
foreach ($action_forward as $action_name => $action_info) foreach ($action_forward as $action_name => $action_info)
{ {
@ -530,10 +530,10 @@ class Router
} }
return $type === 'internal' ? self::$_internal_forwarded_cache : self::$_global_forwarded_cache; return $type === 'internal' ? self::$_internal_forwarded_cache : self::$_global_forwarded_cache;
} }
/** /**
* Find the best matching route for an array of variables. * Find the best matching route for an array of variables.
* *
* @param array $routes * @param array $routes
* @param array $vars * @param array $vars
* @return string|false * @return string|false
@ -551,7 +551,7 @@ class Router
} }
return $only_route; return $only_route;
} }
// If the action has multiple routes, select the one that matches the most arguments. // If the action has multiple routes, select the one that matches the most arguments.
else else
{ {
@ -574,10 +574,10 @@ class Router
return $best_route; return $best_route;
} }
} }
/** /**
* Insert variables into a route. * Insert variables into a route.
* *
* @param string $route * @param string $route
* @param array $vars * @param array $vars
* @return string * @return string
@ -597,7 +597,7 @@ class Router
return ''; return '';
} }
}, $route); }, $route);
// Add a query string for the remaining arguments. // Add a query string for the remaining arguments.
return $route . (count($vars) ? ('?' . http_build_query($vars)) : ''); return $route . (count($vars) ? ('?' . http_build_query($vars)) : '');
} }

View file

@ -24,16 +24,16 @@ class SMS
protected $allow_split_lms = true; protected $allow_split_lms = true;
protected $errors = array(); protected $errors = array();
protected $sent = false; protected $sent = false;
/** /**
* Static properties. * Static properties.
*/ */
public static $default_driver = null; public static $default_driver = null;
public static $custom_drivers = array(); public static $custom_drivers = array();
/** /**
* Set the default driver. * Set the default driver.
* *
* @param object $driver * @param object $driver
* @return void * @return void
*/ */
@ -41,10 +41,10 @@ class SMS
{ {
self::$default_driver = $driver; self::$default_driver = $driver;
} }
/** /**
* Get the default driver. * Get the default driver.
* *
* @return object * @return object
*/ */
public static function getDefaultDriver() public static function getDefaultDriver()
@ -65,7 +65,7 @@ class SMS
} }
return self::$default_driver; return self::$default_driver;
} }
/** /**
* Add a custom mail driver. * Add a custom mail driver.
*/ */
@ -73,10 +73,10 @@ class SMS
{ {
self::$custom_drivers[] = $driver; self::$custom_drivers[] = $driver;
} }
/** /**
* Get the list of supported mail drivers. * Get the list of supported mail drivers.
* *
* @return array * @return array
*/ */
public static function getSupportedDrivers() public static function getSupportedDrivers()
@ -114,7 +114,7 @@ class SMS
ksort($result); ksort($result);
return $result; return $result;
} }
/** /**
* The constructor. * The constructor.
*/ */
@ -125,7 +125,7 @@ class SMS
$this->allow_split_sms = (config('sms.allow_split.sms') !== false); $this->allow_split_sms = (config('sms.allow_split.sms') !== false);
$this->allow_split_lms = (config('sms.allow_split.lms') !== false); $this->allow_split_lms = (config('sms.allow_split.lms') !== false);
} }
/** /**
* Set the sender's phone number. * Set the sender's phone number.
* *
@ -137,7 +137,7 @@ class SMS
$this->from = preg_replace('/[^0-9]/', '', $number); $this->from = preg_replace('/[^0-9]/', '', $number);
return true; return true;
} }
/** /**
* Get the sender's phone number. * Get the sender's phone number.
* *
@ -147,7 +147,7 @@ class SMS
{ {
return $this->from; return $this->from;
} }
/** /**
* Add a recipient. * Add a recipient.
* *
@ -163,7 +163,7 @@ class SMS
); );
return true; return true;
} }
/** /**
* Get the list of recipients without country codes. * Get the list of recipients without country codes.
* *
@ -175,7 +175,7 @@ class SMS
return $recipient->number; return $recipient->number;
}, $this->to); }, $this->to);
} }
/** /**
* Get the list of recipients with country codes. * Get the list of recipients with country codes.
* *
@ -185,7 +185,7 @@ class SMS
{ {
return $this->to; return $this->to;
} }
/** /**
* Get the list of recipients grouped by country code. * Get the list of recipients grouped by country code.
* *
@ -200,7 +200,7 @@ class SMS
} }
return $result; return $result;
} }
/** /**
* Set the subject. * Set the subject.
* *
@ -212,7 +212,7 @@ class SMS
$this->subject = utf8_trim(utf8_clean($subject)); $this->subject = utf8_trim(utf8_clean($subject));
return true; return true;
} }
/** /**
* Get the subject. * Get the subject.
* *
@ -222,7 +222,7 @@ class SMS
{ {
return $this->subject; return $this->subject;
} }
/** /**
* Set the subject (alias to setSubject). * Set the subject (alias to setSubject).
* *
@ -233,7 +233,7 @@ class SMS
{ {
return $this->setSubject($subject); return $this->setSubject($subject);
} }
/** /**
* Get the subject (alias to getSubject). * Get the subject (alias to getSubject).
* *
@ -243,7 +243,7 @@ class SMS
{ {
return $this->getSubject(); return $this->getSubject();
} }
/** /**
* Set the content. * Set the content.
* *
@ -256,17 +256,17 @@ class SMS
$this->content = strtr($this->content, array("\r\n" => "\n")); $this->content = strtr($this->content, array("\r\n" => "\n"));
return true; return true;
} }
/** /**
* Get the content. * Get the content.
* *
* @return string * @return string
*/ */
public function getBody() public function getBody()
{ {
return $this->content; return $this->content;
} }
/** /**
* Set the content (alias to setBody). * Set the content (alias to setBody).
* *
@ -277,17 +277,17 @@ class SMS
{ {
return $this->setBody($content); return $this->setBody($content);
} }
/** /**
* Get the content (alias to getBody). * Get the content (alias to getBody).
* *
* @return string * @return string
*/ */
public function getContent() public function getContent()
{ {
return $this->getBody(); return $this->getBody();
} }
/** /**
* Attach a file. * Attach a file.
* *
@ -305,7 +305,7 @@ class SMS
{ {
return false; return false;
} }
$this->attachments[] = (object)array( $this->attachments[] = (object)array(
'type' => 'mms', 'type' => 'mms',
'local_filename' => $local_filename, 'local_filename' => $local_filename,
@ -314,20 +314,20 @@ class SMS
); );
return true; return true;
} }
/** /**
* Get the list of attachments to this message. * Get the list of attachments to this message.
* *
* @return array * @return array
*/ */
public function getAttachments() public function getAttachments()
{ {
return $this->attachments; return $this->attachments;
} }
/** /**
* Set an extra variable. * Set an extra variable.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @return void * @return void
@ -336,10 +336,10 @@ class SMS
{ {
$this->extra_vars[$key] = $value; $this->extra_vars[$key] = $value;
} }
/** /**
* Get an extra variable. * Get an extra variable.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -347,10 +347,10 @@ class SMS
{ {
return isset($this->extra_vars[$key]) ? $this->extra_vars[$key] : null; return isset($this->extra_vars[$key]) ? $this->extra_vars[$key] : null;
} }
/** /**
* Get all extra variables. * Get all extra variables.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -358,10 +358,10 @@ class SMS
{ {
return $this->extra_vars; return $this->extra_vars;
} }
/** /**
* Set all extra variables. * Set all extra variables.
* *
* @param array $vars * @param array $vars
* @return void * @return void
*/ */
@ -369,15 +369,15 @@ class SMS
{ {
$this->extra_vars = $vars; $this->extra_vars = $vars;
} }
/** /**
* Delay sending the message. * Delay sending the message.
* *
* Delays (in seconds) less than 1 year will be treated as relative to the * Delays (in seconds) less than 1 year will be treated as relative to the
* current time. Greater values will be interpreted as a Unix timestamp. * current time. Greater values will be interpreted as a Unix timestamp.
* *
* This feature may not be implemented by all drivers. * This feature may not be implemented by all drivers.
* *
* @param int $when Unix timestamp * @param int $when Unix timestamp
* @return bool * @return bool
*/ */
@ -391,119 +391,119 @@ class SMS
{ {
$when = 0; $when = 0;
} }
$this->delay_timestamp = intval($when); $this->delay_timestamp = intval($when);
return true; return true;
} }
/** /**
* Get the Unix timestamp of when to send the message. * Get the Unix timestamp of when to send the message.
* *
* This method always returns a Unix timestamp, even if the original value * This method always returns a Unix timestamp, even if the original value
* was given as a relative delay. * was given as a relative delay.
* *
* This feature may not be implemented by all drivers. * This feature may not be implemented by all drivers.
* *
* @return int * @return int
*/ */
public function getDelay() public function getDelay()
{ {
return $this->delay_timestamp; return $this->delay_timestamp;
} }
/** /**
* Force this message to use SMS (not LMS or MMS). * Force this message to use SMS (not LMS or MMS).
* *
* @return void * @return void
*/ */
public function forceSMS() public function forceSMS()
{ {
$this->force_sms = true; $this->force_sms = true;
} }
/** /**
* Unforce this message to use SMS (not LMS or MMS). * Unforce this message to use SMS (not LMS or MMS).
* *
* @return void * @return void
*/ */
public function unforceSMS() public function unforceSMS()
{ {
$this->force_sms = false; $this->force_sms = false;
} }
/** /**
* Check if this message is forced to use SMS. * Check if this message is forced to use SMS.
* *
* @return bool * @return bool
*/ */
public function isForceSMS() public function isForceSMS()
{ {
return $this->force_sms; return $this->force_sms;
} }
/** /**
* Allow this message to be split into multiple SMS. * Allow this message to be split into multiple SMS.
* *
* @return void * @return void
*/ */
public function allowSplitSMS() public function allowSplitSMS()
{ {
$this->allow_split_sms = true; $this->allow_split_sms = true;
} }
/** /**
* Allow this message to be split into multiple LMS. * Allow this message to be split into multiple LMS.
* *
* @return void * @return void
*/ */
public function allowSplitLMS() public function allowSplitLMS()
{ {
$this->allow_split_lms = true; $this->allow_split_lms = true;
} }
/** /**
* Disallow this message to be split into multiple SMS. * Disallow this message to be split into multiple SMS.
* *
* @return void * @return void
*/ */
public function disallowSplitSMS() public function disallowSplitSMS()
{ {
$this->allow_split_sms = false; $this->allow_split_sms = false;
} }
/** /**
* Disallow this message to be split into multiple LMS. * Disallow this message to be split into multiple LMS.
* *
* @return void * @return void
*/ */
public function disallowSplitLMS() public function disallowSplitLMS()
{ {
$this->allow_split_lms = false; $this->allow_split_lms = false;
} }
/** /**
* Check if splitting this message into multiple SMS is allowed. * Check if splitting this message into multiple SMS is allowed.
* *
* @return bool * @return bool
*/ */
public function isSplitSMSAllowed() public function isSplitSMSAllowed()
{ {
return $this->allow_split_sms; return $this->allow_split_sms;
} }
/** /**
* Check if splitting this message into multiple LMS is allowed. * Check if splitting this message into multiple LMS is allowed.
* *
* @return bool * @return bool
*/ */
public function isSplitLMSAllowed() public function isSplitLMSAllowed()
{ {
return $this->allow_split_lms; return $this->allow_split_lms;
} }
/** /**
* Send the message. * Send the message.
* *
* @return bool * @return bool
*/ */
public function send() public function send()
@ -514,19 +514,19 @@ class SMS
{ {
$this->caller = $backtrace[0]['file'] . ($backtrace[0]['line'] ? (' line ' . $backtrace[0]['line']) : ''); $this->caller = $backtrace[0]['file'] . ($backtrace[0]['line'] ? (' line ' . $backtrace[0]['line']) : '');
} }
$output = \ModuleHandler::triggerCall('sms.send', 'before', $this); $output = \ModuleHandler::triggerCall('sms.send', 'before', $this);
if(!$output->toBool()) if(!$output->toBool())
{ {
$this->errors[] = $output->getMessage(); $this->errors[] = $output->getMessage();
return false; return false;
} }
if (config('sms.default_force') && config('sms.default_from')) if (config('sms.default_force') && config('sms.default_from'))
{ {
$this->setFrom(config('sms.default_from')); $this->setFrom(config('sms.default_from'));
} }
try try
{ {
if ($this->driver) if ($this->driver)
@ -553,49 +553,49 @@ class SMS
$this->errors[] = class_basename($e) . ': ' . $e->getMessage(); $this->errors[] = class_basename($e) . ': ' . $e->getMessage();
$this->sent = false; $this->sent = false;
} }
$output = \ModuleHandler::triggerCall('sms.send', 'after', $this); $output = \ModuleHandler::triggerCall('sms.send', 'after', $this);
if(!$output->toBool()) if(!$output->toBool())
{ {
$this->errors[] = $output->getMessage(); $this->errors[] = $output->getMessage();
} }
return $this->sent; return $this->sent;
} }
/** /**
* Check if the message was sent. * Check if the message was sent.
* *
* @return bool * @return bool
*/ */
public function isSent() public function isSent()
{ {
return $this->sent; return $this->sent;
} }
/** /**
* Get caller information. * Get caller information.
* *
* @return string * @return string
*/ */
public function getCaller() public function getCaller()
{ {
return $this->caller; return $this->caller;
} }
/** /**
* Get errors. * Get errors.
* *
* @return array * @return array
*/ */
public function getErrors() public function getErrors()
{ {
return $this->errors; return $this->errors;
} }
/** /**
* Add an error message. * Add an error message.
* *
* @param string $message * @param string $message
* @return void * @return void
*/ */
@ -603,10 +603,10 @@ class SMS
{ {
$this->errors[] = $message; $this->errors[] = $message;
} }
/** /**
* Format the current message according to an API spec. * Format the current message according to an API spec.
* *
* @param array $spec API specifications * @param array $spec API specifications
* @return array * @return array
*/ */
@ -614,10 +614,10 @@ class SMS
{ {
// Initialize the return array. // Initialize the return array.
$result = array(); $result = array();
// Get the list of recipients. // Get the list of recipients.
$recipients = $this->getRecipientsGroupedByCountry(); $recipients = $this->getRecipientsGroupedByCountry();
// Group the recipients by country code. // Group the recipients by country code.
foreach ($recipients as $country_code => $country_recipients) foreach ($recipients as $country_code => $country_recipients)
{ {
@ -626,7 +626,7 @@ class SMS
{ {
$country_recipients = array_chunk($country_recipients, $spec['max_recipients']); $country_recipients = array_chunk($country_recipients, $spec['max_recipients']);
} }
// Send to each set of merged recipients. // Send to each set of merged recipients.
foreach ($country_recipients as $recipient_numbers) foreach ($country_recipients as $recipient_numbers)
{ {
@ -640,12 +640,12 @@ class SMS
{ {
$item->delay = $this->getDelay() ?: 0; $item->delay = $this->getDelay() ?: 0;
} }
// Get message content. // Get message content.
$subject = $this->getSubject(); $subject = $this->getSubject();
$content = $this->getContent(); $content = $this->getContent();
$attachments = $attachments = $this->getAttachments(); $attachments = $attachments = $this->getAttachments();
// Determine the message type. // Determine the message type.
if (!$this->isForceSMS() && ($spec['lms_supported'] || $spec['mms_supported'])) if (!$this->isForceSMS() && ($spec['lms_supported'] || $spec['mms_supported']))
{ {
@ -667,7 +667,7 @@ class SMS
{ {
$item->type = 'SMS'; $item->type = 'SMS';
} }
// Check the country code. // Check the country code.
if ($item->type === 'MMS' && $country_code && is_array($spec['mms_supported_country_codes']) && !in_array($country_code, $spec['mms_supported_country_codes'])) if ($item->type === 'MMS' && $country_code && is_array($spec['mms_supported_country_codes']) && !in_array($country_code, $spec['mms_supported_country_codes']))
{ {
@ -678,7 +678,7 @@ class SMS
$item->type = 'SMS'; $item->type = 'SMS';
} }
} }
// Remove subject and attachments if the message type is SMS. // Remove subject and attachments if the message type is SMS.
if ($item->type === 'SMS') if ($item->type === 'SMS')
{ {
@ -689,7 +689,7 @@ class SMS
} }
$attachments = array(); $attachments = array();
} }
// If message subject is not supported, prepend it to the content instead. // If message subject is not supported, prepend it to the content instead.
if (isset($item->subject) && $item->subject && !$spec[strtolower($item->type) . '_subject_supported']) if (isset($item->subject) && $item->subject && !$spec[strtolower($item->type) . '_subject_supported'])
{ {
@ -704,7 +704,7 @@ class SMS
$item->subject = $subject_short; $item->subject = $subject_short;
$content = $subject_remainder . "\n" . $content; $content = $subject_remainder . "\n" . $content;
} }
// Split the content if necessary. // Split the content if necessary.
if (($item->type === 'SMS' && $this->allow_split_sms) || ($item->type !== 'SMS' && $this->allow_split_lms)) if (($item->type === 'SMS' && $this->allow_split_sms) || ($item->type !== 'SMS' && $this->allow_split_lms))
{ {
@ -721,7 +721,7 @@ class SMS
{ {
$content_parts = array($content); $content_parts = array($content);
} }
// Generate a message for each part of the content and attachments. // Generate a message for each part of the content and attachments.
$message_count = max(count($content_parts), count($attachments)); $message_count = max(count($content_parts), count($attachments));
$last_content = $item->type; $last_content = $item->type;
@ -736,7 +736,7 @@ class SMS
{ {
$item->content = $last_content ?: $item->type; $item->content = $last_content ?: $item->type;
} }
// Get the attachment. // Get the attachment.
if ($attachment = array_shift($attachments)) if ($attachment = array_shift($attachments))
{ {
@ -746,42 +746,42 @@ class SMS
{ {
unset($item->image); unset($item->image);
} }
// Clone the item to make a part. // Clone the item to make a part.
$cloneitem = clone $item; $cloneitem = clone $item;
// Determine the best message type for this part. // Determine the best message type for this part.
if ($cloneitem->type !== 'SMS' && (!isset($cloneitem->subject) || !$cloneitem->subject)) if ($cloneitem->type !== 'SMS' && (!isset($cloneitem->subject) || !$cloneitem->subject))
{ {
$cloneitem->type = $attachment ? 'MMS' : ($this->_getLengthInCharset($content_part, $spec['sms_max_length_in_charset']) > $spec['sms_max_length'] ? 'LMS' : 'SMS'); $cloneitem->type = $attachment ? 'MMS' : ($this->_getLengthInCharset($content_part, $spec['sms_max_length_in_charset']) > $spec['sms_max_length'] ? 'LMS' : 'SMS');
} }
// Add the cloned part to the result array. // Add the cloned part to the result array.
$result[] = $cloneitem; $result[] = $cloneitem;
} }
} }
} }
// Return the message parts. // Return the message parts.
return $result; return $result;
} }
/** /**
* Get the length of a string in another character set. * Get the length of a string in another character set.
* *
* @param string $str String to measure * @param string $str String to measure
* @param string $charset Character set to measure length * @param string $charset Character set to measure length
* @return * @return
*/ */
protected function _getLengthInCharset($str, $charset) protected function _getLengthInCharset($str, $charset)
{ {
$str = @iconv('UTF-8', $charset . '//IGNORE', $str); $str = @iconv('UTF-8', $charset . '//IGNORE', $str);
return strlen($str); return strlen($str);
} }
/** /**
* Split a string into several short chunks. * Split a string into several short chunks.
* *
* @param string $str String to split * @param string $str String to split
* @param int $max_length Maximum length of a chunk * @param int $max_length Maximum length of a chunk
* @param string $charset Character set to measure length * @param string $charset Character set to measure length
@ -794,7 +794,7 @@ class SMS
$result = array(); $result = array();
$current_entry = ''; $current_entry = '';
$current_length = 0; $current_length = 0;
foreach ($chars as $char) foreach ($chars as $char)
{ {
$char_length = strlen(@iconv('UTF-8', $charset . '//IGNORE', $char)); $char_length = strlen(@iconv('UTF-8', $charset . '//IGNORE', $char));
@ -810,12 +810,12 @@ class SMS
$current_length += $char_length; $current_length += $char_length;
} }
} }
if ($current_entry !== '') if ($current_entry !== '')
{ {
$result[] = trim($current_entry); $result[] = trim($current_entry);
} }
return $result; return $result;
} }
} }

View file

@ -9,7 +9,7 @@ class Security
{ {
/** /**
* Sanitize a variable. * Sanitize a variable.
* *
* @param string $input * @param string $input
* @param string $type * @param string $type
* @return string|false * @return string|false
@ -22,30 +22,30 @@ class Security
case 'escape': case 'escape':
if (!utf8_check($input)) return false; if (!utf8_check($input)) return false;
return escape($input); return escape($input);
// Strip all HTML tags. // Strip all HTML tags.
case 'strip': case 'strip':
if (!utf8_check($input)) return false; if (!utf8_check($input)) return false;
return escape(strip_tags($input)); return escape(strip_tags($input));
// Clean up HTML content to prevent XSS attacks. // Clean up HTML content to prevent XSS attacks.
case 'html': case 'html':
if (!utf8_check($input)) return false; if (!utf8_check($input)) return false;
return Filters\HTMLFilter::clean($input); return Filters\HTMLFilter::clean($input);
// Clean up the input to be used as a safe filename. // Clean up the input to be used as a safe filename.
case 'filename': case 'filename':
if (!utf8_check($input)) return false; if (!utf8_check($input)) return false;
return Filters\FilenameFilter::clean($input); return Filters\FilenameFilter::clean($input);
// Unknown filters return false. // Unknown filters return false.
default: return false; default: return false;
} }
} }
/** /**
* Encrypt a string using AES. * Encrypt a string using AES.
* *
* @param string $plaintext * @param string $plaintext
* @param string $key (optional) * @param string $key (optional)
* @return string|false * @return string|false
@ -55,14 +55,14 @@ class Security
// Get the encryption key. // Get the encryption key.
$key = $key ?: config('crypto.encryption_key'); $key = $key ?: config('crypto.encryption_key');
$key = substr(hash('sha256', $key, true), 0, 16); $key = substr(hash('sha256', $key, true), 0, 16);
// Encrypt in a format that is compatible with defuse/php-encryption 1.2.x. // Encrypt in a format that is compatible with defuse/php-encryption 1.2.x.
return base64_encode(\CryptoCompat::encrypt($plaintext, $key)); return base64_encode(\CryptoCompat::encrypt($plaintext, $key));
} }
/** /**
* Decrypt a string using AES. * Decrypt a string using AES.
* *
* @param string $plaintext * @param string $plaintext
* @param string $key (optional) * @param string $key (optional)
* @return string|false * @return string|false
@ -72,21 +72,21 @@ class Security
// Get the encryption key. // Get the encryption key.
$key = $key ?: config('crypto.encryption_key'); $key = $key ?: config('crypto.encryption_key');
$key = substr(hash('sha256', $key, true), 0, 16); $key = substr(hash('sha256', $key, true), 0, 16);
// Check whether the ciphertext is valid. // Check whether the ciphertext is valid.
$ciphertext = @base64_decode($ciphertext); $ciphertext = @base64_decode($ciphertext);
if (strlen($ciphertext) < 48) if (strlen($ciphertext) < 48)
{ {
return false; return false;
} }
// Decrypt in a format that is compatible with defuse/php-encryption 1.2.x. // Decrypt in a format that is compatible with defuse/php-encryption 1.2.x.
return \CryptoCompat::decrypt($ciphertext, $key); return \CryptoCompat::decrypt($ciphertext, $key);
} }
/** /**
* Create a digital signature to verify the authenticity of a string. * Create a digital signature to verify the authenticity of a string.
* *
* @param string $string * @param string $string
* @return string * @return string
*/ */
@ -97,10 +97,10 @@ class Security
$hash = substr(base64_encode(hash_hmac('sha256', hash_hmac('sha256', $string, $salt), $key, true)), 0, 32); $hash = substr(base64_encode(hash_hmac('sha256', hash_hmac('sha256', $string, $salt), $key, true)), 0, 32);
return $salt . strtr($hash, '+/', '-_'); return $salt . strtr($hash, '+/', '-_');
} }
/** /**
* Check whether a signature is valid. * Check whether a signature is valid.
* *
* @param string $string * @param string $string
* @param string $signature * @param string $signature
* @return bool * @return bool
@ -111,16 +111,16 @@ class Security
{ {
return false; return false;
} }
$key = config('crypto.authentication_key'); $key = config('crypto.authentication_key');
$salt = substr($signature, 0, 8); $salt = substr($signature, 0, 8);
$hash = substr(base64_encode(hash_hmac('sha256', hash_hmac('sha256', $string, $salt), $key, true)), 0, 32); $hash = substr(base64_encode(hash_hmac('sha256', hash_hmac('sha256', $string, $salt), $key, true)), 0, 32);
return self::compareStrings(substr($signature, 8), strtr($hash, '+/', '-_')); return self::compareStrings(substr($signature, 8), strtr($hash, '+/', '-_'));
} }
/** /**
* Generate a cryptographically secure random string. * Generate a cryptographically secure random string.
* *
* @param int $length * @param int $length
* @param string $format * @param string $format
* @return string * @return string
@ -142,11 +142,11 @@ class Security
$entropy_required_bytes = ceil($length * 3 / 4); $entropy_required_bytes = ceil($length * 3 / 4);
break; break;
} }
// Cap entropy to 256 bits from any one source, because anything more is meaningless. // Cap entropy to 256 bits from any one source, because anything more is meaningless.
$entropy_capped_bytes = min(32, $entropy_required_bytes); $entropy_capped_bytes = min(32, $entropy_required_bytes);
$entropy = false; $entropy = false;
// Find and use the most secure way to generate a random string. // Find and use the most secure way to generate a random string.
if(function_exists('random_bytes')) if(function_exists('random_bytes'))
{ {
@ -159,7 +159,7 @@ class Security
$entropy = false; $entropy = false;
} }
} }
// Use other good sources of entropy if random_bytes() is not available. // Use other good sources of entropy if random_bytes() is not available.
if ($entropy === false) if ($entropy === false)
{ {
@ -186,7 +186,7 @@ class Security
fclose($fp); fclose($fp);
} }
} }
// Use built-in source of entropy if an error occurs while using other functions. // Use built-in source of entropy if an error occurs while using other functions.
if($entropy === false || strlen($entropy) < $entropy_capped_bytes) if($entropy === false || strlen($entropy) < $entropy_capped_bytes)
{ {
@ -196,14 +196,14 @@ class Security
$entropy .= pack('S', rand(0, 65536) ^ mt_rand(0, 65535)); $entropy .= pack('S', rand(0, 65536) ^ mt_rand(0, 65535));
} }
} }
// Mixing (see RFC 4086 section 5) // Mixing (see RFC 4086 section 5)
$output = ''; $output = '';
for($i = 0; $i < $entropy_required_bytes; $i += 32) for($i = 0; $i < $entropy_required_bytes; $i += 32)
{ {
$output .= hash('sha256', $entropy . $i . rand(), true); $output .= hash('sha256', $entropy . $i . rand(), true);
} }
// Encode and return the random string. // Encode and return the random string.
switch($format) switch($format)
{ {
@ -225,10 +225,10 @@ class Security
return strtr($salt, '+/=', $replacements); return strtr($salt, '+/=', $replacements);
} }
} }
/** /**
* Generate a cryptographically secure random number between $min and $max. * Generate a cryptographically secure random number between $min and $max.
* *
* @param int $min * @param int $min
* @param int $max * @param int $max
* @return int * @return int
@ -247,10 +247,10 @@ class Security
return intval($min + $offset); return intval($min + $offset);
} }
} }
/** /**
* Generate a random UUID. * Generate a random UUID.
* *
* @return string * @return string
*/ */
public static function getRandomUUID() public static function getRandomUUID()
@ -260,10 +260,10 @@ class Security
$randpool[8] = chr(ord($randpool[8]) & 0x3f | 0x80); $randpool[8] = chr(ord($randpool[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($randpool), 4)); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($randpool), 4));
} }
/** /**
* Compare two strings in constant time. * Compare two strings in constant time.
* *
* @param string $a * @param string $a
* @param string $b * @param string $b
* @return bool * @return bool
@ -274,7 +274,7 @@ class Security
{ {
return hash_equals($a, $b); return hash_equals($a, $b);
} }
$diff = strlen($a) ^ strlen($b); $diff = strlen($a) ^ strlen($b);
$maxlen = min(strlen($a), strlen($b)); $maxlen = min(strlen($a), strlen($b));
for($i = 0; $i < $maxlen; $i++) for($i = 0; $i < $maxlen; $i++)
@ -283,13 +283,13 @@ class Security
} }
return $diff === 0; return $diff === 0;
} }
/** /**
* Check if the current request seems to be a CSRF attack. * Check if the current request seems to be a CSRF attack.
* *
* This method returns true if the request seems to be innocent, * This method returns true if the request seems to be innocent,
* and false if it seems to be a CSRF attack. * and false if it seems to be a CSRF attack.
* *
* @param string $referer (optional) * @param string $referer (optional)
* @return bool * @return bool
*/ */
@ -315,7 +315,7 @@ class Security
{ {
trigger_error('CSRF token missing in POST request: ' . (\Context::get('act') ?: '(no act)'), \E_USER_WARNING); trigger_error('CSRF token missing in POST request: ' . (\Context::get('act') ?: '(no act)'), \E_USER_WARNING);
} }
if (!$referer) if (!$referer)
{ {
$referer = strval(($_SERVER['HTTP_ORIGIN'] ?? '') ?: ($_SERVER['HTTP_REFERER'] ?? '')); $referer = strval(($_SERVER['HTTP_ORIGIN'] ?? '') ?: ($_SERVER['HTTP_REFERER'] ?? ''));
@ -330,15 +330,15 @@ class Security
} }
} }
} }
/** /**
* Check if the current request seems to be an XXE (XML external entity) attack. * Check if the current request seems to be an XXE (XML external entity) attack.
* *
* This method returns true if the request seems to be innocent, * This method returns true if the request seems to be innocent,
* and false if it seems to be an XXE attack. * and false if it seems to be an XXE attack.
* This is the opposite of XE's Security::detectingXEE() method. * This is the opposite of XE's Security::detectingXEE() method.
* The name has also been changed to the more accurate acronym XXE. * The name has also been changed to the more accurate acronym XXE.
* *
* @param string $xml (optional) * @param string $xml (optional)
* @return bool * @return bool
*/ */
@ -349,33 +349,33 @@ class Security
{ {
return true; return true;
} }
// Reject entity tags. // Reject entity tags.
if (strpos($xml, '<!ENTITY') !== false) if (strpos($xml, '<!ENTITY') !== false)
{ {
return false; return false;
} }
// Check if there is no content after the xml tag. // Check if there is no content after the xml tag.
$header = preg_replace('/<\?xml.*?\?'.'>/s', '', substr($xml, 0, 100), 1); $header = preg_replace('/<\?xml.*?\?'.'>/s', '', substr($xml, 0, 100), 1);
if (($xml = trim(substr_replace($xml, $header, 0, 100))) === '') if (($xml = trim(substr_replace($xml, $header, 0, 100))) === '')
{ {
return false; return false;
} }
// Check if there is no content after the DTD. // Check if there is no content after the DTD.
$header = preg_replace('/^<!DOCTYPE[^>]*+>/i', '', substr($xml, 0, 200), 1); $header = preg_replace('/^<!DOCTYPE[^>]*+>/i', '', substr($xml, 0, 200), 1);
if (($xml = trim(substr_replace($xml, $header, 0, 200))) === '') if (($xml = trim(substr_replace($xml, $header, 0, 200))) === '')
{ {
return false; return false;
} }
// Check that the root tag is valid. // Check that the root tag is valid.
if (!preg_match('/^<(methodCall|methodResponse|fault)/', $xml)) if (!preg_match('/^<(methodCall|methodResponse|fault)/', $xml))
{ {
return false; return false;
} }
return true; return true;
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -11,25 +11,25 @@ class Storage
* Use atomic rename to overwrite files. * Use atomic rename to overwrite files.
*/ */
public static $safe_overwrite = true; public static $safe_overwrite = true;
/** /**
* Cache the umask here. * Cache the umask here.
*/ */
protected static $_umask; protected static $_umask;
/** /**
* Cache the opcache status here. * Cache the opcache status here.
*/ */
protected static $_opcache; protected static $_opcache;
/** /**
* Cache locks here. * Cache locks here.
*/ */
protected static $_locks = array(); protected static $_locks = array();
/** /**
* Check if a path really exists. * Check if a path really exists.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -39,10 +39,10 @@ class Storage
clearstatcache(true, $path); clearstatcache(true, $path);
return @file_exists($path); return @file_exists($path);
} }
/** /**
* Check if the given path is a file. * Check if the given path is a file.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -51,10 +51,10 @@ class Storage
$path = rtrim($path, '/\\'); $path = rtrim($path, '/\\');
return @self::exists($path) && @is_file($path); return @self::exists($path) && @is_file($path);
} }
/** /**
* Check if the given path is an empty file. * Check if the given path is an empty file.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -63,11 +63,11 @@ class Storage
$path = rtrim($path, '/\\'); $path = rtrim($path, '/\\');
return @self::exists($path) && @is_file($path) && (@filesize($path) == 0); return @self::exists($path) && @is_file($path) && (@filesize($path) == 0);
} }
/** /**
* Check if the given path is a directory. * Check if the given path is a directory.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -76,10 +76,10 @@ class Storage
$path = rtrim($path, '/\\'); $path = rtrim($path, '/\\');
return @self::exists($path) && @is_dir($path); return @self::exists($path) && @is_dir($path);
} }
/** /**
* Check if the given path is an empty directory. * Check if the given path is an empty directory.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -90,14 +90,14 @@ class Storage
{ {
return false; return false;
} }
$iterator = new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS); $iterator = new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS);
return (iterator_count($iterator)) === 0 ? true : false; return (iterator_count($iterator)) === 0 ? true : false;
} }
/** /**
* Check if the given path is a symbolic link. * Check if the given path is a symbolic link.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -106,10 +106,10 @@ class Storage
$path = rtrim($path, '/\\'); $path = rtrim($path, '/\\');
return @is_link($path); return @is_link($path);
} }
/** /**
* Check if the given path is a valid symbolic link. * Check if the given path is a valid symbolic link.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -118,10 +118,10 @@ class Storage
$path = rtrim($path, '/\\'); $path = rtrim($path, '/\\');
return @is_link($path) && ($target = @readlink($path)) !== false && self::exists($target); return @is_link($path) && ($target = @readlink($path)) !== false && self::exists($target);
} }
/** /**
* Check if the given path is readable. * Check if the given path is readable.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -130,10 +130,10 @@ class Storage
$path = rtrim($path, '/\\'); $path = rtrim($path, '/\\');
return @self::exists($path) && @is_readable($path); return @self::exists($path) && @is_readable($path);
} }
/** /**
* Check if the given path is writable. * Check if the given path is writable.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -142,10 +142,10 @@ class Storage
$path = rtrim($path, '/\\'); $path = rtrim($path, '/\\');
return @self::exists($path) && @is_writable($path); return @self::exists($path) && @is_writable($path);
} }
/** /**
* Check if the given path is executable. * Check if the given path is executable.
* *
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
@ -169,12 +169,12 @@ class Storage
return @self::exists($path) && @is_executable($path); return @self::exists($path) && @is_executable($path);
} }
} }
/** /**
* Get the size of a file. * Get the size of a file.
* *
* This method returns the size of a file, or false on error. * This method returns the size of a file, or false on error.
* *
* @param string $filename * @param string $filename
* @return int|false * @return int|false
*/ */
@ -190,15 +190,15 @@ class Storage
return false; return false;
} }
} }
/** /**
* Get the content of a file. * Get the content of a file.
* *
* This method returns the content if it exists and is readable. * This method returns the content if it exists and is readable.
* If $stream is true, it will return the content as a stream instead of * If $stream is true, it will return the content as a stream instead of
* loading the entire content in memory. This may be useful for large files. * loading the entire content in memory. This may be useful for large files.
* If the file cannot be opened, this method returns false. * If the file cannot be opened, this method returns false.
* *
* @param string $filename * @param string $filename
* @param bool $stream (optional) * @param bool $stream (optional)
* @return string|resource|false * @return string|resource|false
@ -216,7 +216,7 @@ class Storage
{ {
$result = @file_get_contents($filename); $result = @file_get_contents($filename);
} }
if ($result === false) if ($result === false)
{ {
trigger_error('Cannot read file: ' . $filename, \E_USER_WARNING); trigger_error('Cannot read file: ' . $filename, \E_USER_WARNING);
@ -228,12 +228,12 @@ class Storage
return false; return false;
} }
} }
/** /**
* Read PHP data from a file, formatted for easy retrieval. * Read PHP data from a file, formatted for easy retrieval.
* *
* This method returns the data on success and false on failure. * This method returns the data on success and false on failure.
* *
* @param string $filename * @param string $filename
* @return mixed * @return mixed
*/ */
@ -249,14 +249,14 @@ class Storage
return false; return false;
} }
} }
/** /**
* Write $content to a file. * Write $content to a file.
* *
* If $content is a stream, this method will copy it to the target file * If $content is a stream, this method will copy it to the target file
* without loading the entire content in memory. This may be useful for large files. * without loading the entire content in memory. This may be useful for large files.
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $filename * @param string $filename
* @param string|resource $content * @param string|resource $content
* @param string $mode (optional) * @param string $mode (optional)
@ -276,7 +276,7 @@ class Storage
return false; return false;
} }
} }
if (self::$safe_overwrite && strncasecmp($mode, 'a', 1) && @is_writable($destination_dir)) if (self::$safe_overwrite && strncasecmp($mode, 'a', 1) && @is_writable($destination_dir))
{ {
$use_atomic_rename = true; $use_atomic_rename = true;
@ -287,7 +287,7 @@ class Storage
{ {
$use_atomic_rename = false; $use_atomic_rename = false;
} }
if ($fp = @fopen($filename, $mode)) if ($fp = @fopen($filename, $mode))
{ {
flock($fp, \LOCK_EX); flock($fp, \LOCK_EX);
@ -302,7 +302,7 @@ class Storage
fflush($fp); fflush($fp);
flock($fp, \LOCK_UN); flock($fp, \LOCK_UN);
fclose($fp); fclose($fp);
if ($result === false || (is_string($content) && strlen($content) !== $result)) if ($result === false || (is_string($content) && strlen($content) !== $result))
{ {
trigger_error('Cannot write file: ' . (isset($original_filename) ? $original_filename : $filename), \E_USER_WARNING); trigger_error('Cannot write file: ' . (isset($original_filename) ? $original_filename : $filename), \E_USER_WARNING);
@ -314,9 +314,9 @@ class Storage
trigger_error('Cannot write file: ' . (isset($original_filename) ? $original_filename : $filename), \E_USER_WARNING); trigger_error('Cannot write file: ' . (isset($original_filename) ? $original_filename : $filename), \E_USER_WARNING);
return false; return false;
} }
@chmod($filename, ($perms === null ? (0666 & ~self::getUmask()) : $perms)); @chmod($filename, ($perms === null ? (0666 & ~self::getUmask()) : $perms));
if ($use_atomic_rename) if ($use_atomic_rename)
{ {
$rename_success = @rename($filename, $original_filename); $rename_success = @rename($filename, $original_filename);
@ -333,7 +333,7 @@ class Storage
} }
$filename = $original_filename; $filename = $original_filename;
} }
if (self::$_opcache === null) if (self::$_opcache === null)
{ {
self::$_opcache = function_exists('opcache_invalidate'); self::$_opcache = function_exists('opcache_invalidate');
@ -342,17 +342,17 @@ class Storage
{ {
@opcache_invalidate($filename, true); @opcache_invalidate($filename, true);
} }
clearstatcache(true, $filename); clearstatcache(true, $filename);
return true; return true;
} }
/** /**
* Write PHP data to a file, formatted for easy retrieval. * Write PHP data to a file, formatted for easy retrieval.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* Resources and anonymous functions cannot be saved. * Resources and anonymous functions cannot be saved.
* *
* @param string $filename * @param string $filename
* @param mixed $data * @param mixed $data
* @param string $comment (optional) * @param string $comment (optional)
@ -375,13 +375,13 @@ class Storage
} }
return self::write($filename, $content); return self::write($filename, $content);
} }
/** /**
* Copy $source to $destination. * Copy $source to $destination.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the destination permissions are not given, they will be copied from the source. * If the destination permissions are not given, they will be copied from the source.
* *
* @param string $source * @param string $source
* @param string $destination * @param string $destination
* @param int $destination_perms * @param int $destination_perms
@ -396,7 +396,7 @@ class Storage
trigger_error('Cannot copy because the source does not exist: ' . $source, \E_USER_WARNING); trigger_error('Cannot copy because the source does not exist: ' . $source, \E_USER_WARNING);
return false; return false;
} }
$destination_dir = dirname($destination); $destination_dir = dirname($destination);
if (!self::exists($destination_dir) && !self::createDirectory($destination_dir)) if (!self::exists($destination_dir) && !self::createDirectory($destination_dir))
{ {
@ -408,7 +408,7 @@ class Storage
$destination_dir = $destination; $destination_dir = $destination;
$destination = $destination . '/' . basename($source); $destination = $destination . '/' . basename($source);
} }
if (self::$safe_overwrite && @is_writable($destination_dir)) if (self::$safe_overwrite && @is_writable($destination_dir))
{ {
$use_atomic_rename = true; $use_atomic_rename = true;
@ -419,14 +419,14 @@ class Storage
{ {
$use_atomic_rename = false; $use_atomic_rename = false;
} }
$copy_success = @copy($source, $destination); $copy_success = @copy($source, $destination);
if (!$copy_success) if (!$copy_success)
{ {
trigger_error('Cannot copy ' . $source . ' to ' . (isset($original_destination) ? $original_destination : $destination), \E_USER_WARNING); trigger_error('Cannot copy ' . $source . ' to ' . (isset($original_destination) ? $original_destination : $destination), \E_USER_WARNING);
return false; return false;
} }
if ($destination_perms === null) if ($destination_perms === null)
{ {
if (is_uploaded_file($source)) if (is_uploaded_file($source))
@ -442,7 +442,7 @@ class Storage
{ {
@chmod($destination, $destination_perms); @chmod($destination, $destination_perms);
} }
if ($use_atomic_rename) if ($use_atomic_rename)
{ {
$rename_success = @rename($destination, $original_destination); $rename_success = @rename($destination, $original_destination);
@ -459,7 +459,7 @@ class Storage
} }
$destination = $original_destination; $destination = $original_destination;
} }
if (self::$_opcache === null) if (self::$_opcache === null)
{ {
self::$_opcache = function_exists('opcache_invalidate'); self::$_opcache = function_exists('opcache_invalidate');
@ -468,16 +468,16 @@ class Storage
{ {
@opcache_invalidate($destination, true); @opcache_invalidate($destination, true);
} }
clearstatcache(true, $destination); clearstatcache(true, $destination);
return true; return true;
} }
/** /**
* Move $source to $destination. * Move $source to $destination.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $source * @param string $source
* @param string $destination * @param string $destination
* @return bool * @return bool
@ -491,7 +491,7 @@ class Storage
trigger_error('Cannot move because the source does not exist: ' . $source, \E_USER_WARNING); trigger_error('Cannot move because the source does not exist: ' . $source, \E_USER_WARNING);
return false; return false;
} }
$destination_dir = dirname($destination); $destination_dir = dirname($destination);
if (!self::exists($destination_dir) && !self::createDirectory($destination_dir)) if (!self::exists($destination_dir) && !self::createDirectory($destination_dir))
{ {
@ -502,19 +502,19 @@ class Storage
{ {
$destination = $destination . '/' . basename($source); $destination = $destination . '/' . basename($source);
} }
$result = @rename($source, $destination); $result = @rename($source, $destination);
if (!$result) if (!$result)
{ {
trigger_error('Cannot move ' . $source . ' to ' . $destination, \E_USER_WARNING); trigger_error('Cannot move ' . $source . ' to ' . $destination, \E_USER_WARNING);
return false; return false;
} }
if (is_uploaded_file($source)) if (is_uploaded_file($source))
{ {
@chmod($destination, 0666 & ~self::getUmask()); @chmod($destination, 0666 & ~self::getUmask());
} }
if (self::$_opcache === null) if (self::$_opcache === null)
{ {
self::$_opcache = function_exists('opcache_invalidate'); self::$_opcache = function_exists('opcache_invalidate');
@ -530,16 +530,16 @@ class Storage
@opcache_invalidate($destination, true); @opcache_invalidate($destination, true);
} }
} }
clearstatcache(true, $destination); clearstatcache(true, $destination);
return true; return true;
} }
/** /**
* Move uploaded $source to $destination. * Move uploaded $source to $destination.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $source * @param string $source
* @param string $destination * @param string $destination
* @param string $type * @param string $type
@ -579,13 +579,13 @@ class Storage
} }
return true; return true;
} }
/** /**
* Delete a file. * Delete a file.
* *
* This method returns true if the file exists and has been successfully * This method returns true if the file exists and has been successfully
* deleted, and false on any kind of failure. * deleted, and false on any kind of failure.
* *
* @param string $filename * @param string $filename
* @return bool * @return bool
*/ */
@ -596,13 +596,13 @@ class Storage
{ {
return false; return false;
} }
$result = @is_file($filename) && @unlink($filename); $result = @is_file($filename) && @unlink($filename);
if (!$result) if (!$result)
{ {
trigger_error('Cannot delete file: ' . $filename, \E_USER_WARNING); trigger_error('Cannot delete file: ' . $filename, \E_USER_WARNING);
} }
if (self::$_opcache === null) if (self::$_opcache === null)
{ {
self::$_opcache = function_exists('opcache_invalidate'); self::$_opcache = function_exists('opcache_invalidate');
@ -613,10 +613,10 @@ class Storage
} }
return $result; return $result;
} }
/** /**
* Create a directory. * Create a directory.
* *
* @param string $dirname * @param string $dirname
* @return bool * @return bool
*/ */
@ -627,7 +627,7 @@ class Storage
{ {
$mode = 0777 & ~self::getUmask(); $mode = 0777 & ~self::getUmask();
} }
$result = @mkdir($dirname, $mode, true); $result = @mkdir($dirname, $mode, true);
if (!$result) if (!$result)
{ {
@ -646,10 +646,10 @@ class Storage
return true; return true;
} }
} }
/** /**
* Read the list of files in a directory. * Read the list of files in a directory.
* *
* @param string $dirname * @param string $dirname
* @param bool $full_path (optional) * @param bool $full_path (optional)
* @param bool $skip_dotfiles (optional) * @param bool $skip_dotfiles (optional)
@ -663,7 +663,7 @@ class Storage
{ {
return false; return false;
} }
try try
{ {
$iterator = new \FilesystemIterator($dirname, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS); $iterator = new \FilesystemIterator($dirname, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS);
@ -673,7 +673,7 @@ class Storage
trigger_error('Cannot read directory: ' . $dirname, \E_USER_WARNING); trigger_error('Cannot read directory: ' . $dirname, \E_USER_WARNING);
return false; return false;
} }
$result = array(); $result = array();
foreach ($iterator as $fileinfo) foreach ($iterator as $fileinfo)
{ {
@ -689,7 +689,7 @@ class Storage
sort($result); sort($result);
return $result; return $result;
} }
/** /**
* Copy a directory recursively. * Copy a directory recursively.
* *
@ -712,11 +712,11 @@ class Storage
trigger_error('Cannot create directory to copy into: ' . $destination, \E_USER_WARNING); trigger_error('Cannot create directory to copy into: ' . $destination, \E_USER_WARNING);
return false; return false;
} }
$rdi_options = \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS; $rdi_options = \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS;
$rii_options = \RecursiveIteratorIterator::CHILD_FIRST; $rii_options = \RecursiveIteratorIterator::CHILD_FIRST;
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, $rdi_options), $rii_options); $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, $rdi_options), $rii_options);
foreach ($iterator as $path) foreach ($iterator as $path)
{ {
$path_source = $path->getPathname(); $path_source = $path->getPathname();
@ -728,7 +728,7 @@ class Storage
{ {
continue; continue;
} }
$path_destination = $destination . substr($path_source, strlen($source)); $path_destination = $destination . substr($path_source, strlen($source));
if ($path->isDir()) if ($path->isDir())
{ {
@ -747,13 +747,13 @@ class Storage
} }
} }
} }
return true; return true;
} }
/** /**
* Move a directory. * Move a directory.
* *
* @param string $source * @param string $source
* @param string $destination * @param string $destination
* @return bool * @return bool
@ -762,10 +762,10 @@ class Storage
{ {
return self::move($source, $destination); return self::move($source, $destination);
} }
/** /**
* Delete a directory recursively. * Delete a directory recursively.
* *
* @param string $dirname * @param string $dirname
* @param bool $delete_self (optional) * @param bool $delete_self (optional)
* @return bool * @return bool
@ -782,11 +782,11 @@ class Storage
trigger_error('Delete target is not a directory: ' . $dirname, \E_USER_WARNING); trigger_error('Delete target is not a directory: ' . $dirname, \E_USER_WARNING);
return false; return false;
} }
$rdi_options = \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS; $rdi_options = \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS;
$rii_options = \RecursiveIteratorIterator::CHILD_FIRST; $rii_options = \RecursiveIteratorIterator::CHILD_FIRST;
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dirname, $rdi_options), $rii_options); $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dirname, $rdi_options), $rii_options);
foreach ($iterator as $path) foreach ($iterator as $path)
{ {
if ($path->isDir()) if ($path->isDir())
@ -806,7 +806,7 @@ class Storage
} }
} }
} }
if ($delete_self) if ($delete_self)
{ {
$result = @rmdir($dirname); $result = @rmdir($dirname);
@ -825,10 +825,10 @@ class Storage
return true; return true;
} }
} }
/** /**
* Delete a directory only if it is empty. * Delete a directory only if it is empty.
* *
* @param string $dirname * @param string $dirname
* @param bool $delete_empty_parents (optional) * @param bool $delete_empty_parents (optional)
* @return bool * @return bool
@ -840,7 +840,7 @@ class Storage
{ {
return false; return false;
} }
$result = @rmdir($dirname); $result = @rmdir($dirname);
if (!$result) if (!$result)
{ {
@ -855,10 +855,10 @@ class Storage
return true; return true;
} }
} }
/** /**
* Get the current umask. * Get the current umask.
* *
* @return int * @return int
*/ */
public static function getUmask() public static function getUmask()
@ -869,10 +869,10 @@ class Storage
} }
return self::$_umask; return self::$_umask;
} }
/** /**
* Set the current umask. * Set the current umask.
* *
* @param int $umask * @param int $umask
* @return void * @return void
*/ */
@ -880,10 +880,10 @@ class Storage
{ {
self::$_umask = intval($umask); self::$_umask = intval($umask);
} }
/** /**
* Determine the best umask for this installation of Rhymix. * Determine the best umask for this installation of Rhymix.
* *
* @return string * @return string
*/ */
public static function recommendUmask() public static function recommendUmask()
@ -893,29 +893,29 @@ class Storage
{ {
return '0000'; return '0000';
} }
// Get the UID of the owner of the current file. // Get the UID of the owner of the current file.
$file_uid = fileowner(__FILE__); $file_uid = fileowner(__FILE__);
// Get the UID of the current PHP process. // Get the UID of the current PHP process.
$php_uid = self::getServerUID(); $php_uid = self::getServerUID();
// If both UIDs are the same, set the umask to 0022. // If both UIDs are the same, set the umask to 0022.
if ($file_uid == $php_uid) if ($file_uid == $php_uid)
{ {
return '0022'; return '0022';
} }
// Otherwise, set the umask to 0000. // Otherwise, set the umask to 0000.
else else
{ {
return '0000'; return '0000';
} }
} }
/** /**
* Get the UID of the server process. * Get the UID of the server process.
* *
* @return int|false * @return int|false
*/ */
public static function getServerUID() public static function getServerUID()
@ -931,7 +931,7 @@ class Storage
{ {
self::delete($testfile); self::delete($testfile);
} }
if (self::write($testfile, 'TEST')) if (self::write($testfile, 'TEST'))
{ {
$uid = fileowner($testfile); $uid = fileowner($testfile);
@ -944,10 +944,10 @@ class Storage
} }
} }
} }
/** /**
* Obtain an exclusive lock. * Obtain an exclusive lock.
* *
* @return bool * @return bool
*/ */
public static function getLock($name) public static function getLock($name)
@ -957,20 +957,20 @@ class Storage
{ {
return false; return false;
} }
$lockdir = \RX_BASEDIR . 'files/locks'; $lockdir = \RX_BASEDIR . 'files/locks';
if (!self::isDirectory($lockdir) && !self::createDirectory($lockdir)) if (!self::isDirectory($lockdir) && !self::createDirectory($lockdir))
{ {
return false; return false;
} }
self::$_locks[$name] = @fopen($lockdir . '/' . $name . '.lock', 'w'); self::$_locks[$name] = @fopen($lockdir . '/' . $name . '.lock', 'w');
if (!self::$_locks[$name]) if (!self::$_locks[$name])
{ {
unset(self::$_locks[$name]); unset(self::$_locks[$name]);
return false; return false;
} }
$result = @flock(self::$_locks[$name], \LOCK_EX | \LOCK_NB); $result = @flock(self::$_locks[$name], \LOCK_EX | \LOCK_NB);
if (!$result) if (!$result)
{ {
@ -978,14 +978,14 @@ class Storage
unset(self::$_locks[$name]); unset(self::$_locks[$name]);
return false; return false;
} }
register_shutdown_function('\\Rhymix\\Framework\\Storage::clearLocks'); register_shutdown_function('\\Rhymix\\Framework\\Storage::clearLocks');
return true; return true;
} }
/** /**
* Clear all locks. * Clear all locks.
* *
* @return void * @return void
*/ */
public static function clearLocks() public static function clearLocks()

View file

@ -11,34 +11,34 @@ class Timer
* Timestamps are stored here. * Timestamps are stored here.
*/ */
protected static $_timestamps = array(); protected static $_timestamps = array();
/** /**
* Start a timer. * Start a timer.
* *
* This method returns the current microtime. * This method returns the current microtime.
* *
* @param string $name (optional) * @param string $name (optional)
* @return float * @return float
*/ */
public static function start($name = null) public static function start($name = null)
{ {
$timestamp = microtime(true); $timestamp = microtime(true);
if ($name === null) if ($name === null)
{ {
$name = 'anon-timer-' . $timestamp; $name = 'anon-timer-' . $timestamp;
} }
self::$_timestamps[$name] = $timestamp; self::$_timestamps[$name] = $timestamp;
return $timestamp; return $timestamp;
} }
/** /**
* Stop a timer and return the elapsed time. * Stop a timer and return the elapsed time.
* *
* If the name is not given, the most recently started timer will be stopped. * If the name is not given, the most recently started timer will be stopped.
* If no timer has been started, this method returns false. * If no timer has been started, this method returns false.
* *
* @param string $name (optional) * @param string $name (optional)
* @return float|false * @return float|false
*/ */
@ -46,7 +46,7 @@ class Timer
{ {
$timestamp = microtime(true); $timestamp = microtime(true);
$started_timestamp = 0; $started_timestamp = 0;
if ($name === null) if ($name === null)
{ {
if (count(self::$_timestamps)) if (count(self::$_timestamps))
@ -67,16 +67,16 @@ class Timer
{ {
return false; return false;
} }
return $timestamp - $started_timestamp; return $timestamp - $started_timestamp;
} }
/** /**
* Stop a timer and return the elapsed time in a human-readable format. * Stop a timer and return the elapsed time in a human-readable format.
* *
* If the name is not given, the most recently started timer will be stopped. * If the name is not given, the most recently started timer will be stopped.
* If no timer has been started, this method returns false. * If no timer has been started, this method returns false.
* *
* @param string $name (optional) * @param string $name (optional)
* @return string|false * @return string|false
*/ */
@ -86,17 +86,17 @@ class Timer
if ($result === false) return $result; if ($result === false) return $result;
return number_format($result * 1000, 1, '.', ',') . 'ms'; return number_format($result * 1000, 1, '.', ',') . 'ms';
} }
/** /**
* This method returns how much time has elapsed since Rhymix startup. * This method returns how much time has elapsed since Rhymix startup.
* *
* @return float * @return float
*/ */
public static function sinceStartup() public static function sinceStartup()
{ {
return microtime(true) - \RX_MICROTIME; return microtime(true) - \RX_MICROTIME;
} }
/** /**
* This method returns how much time has elapsed since startup in a human-readable format. * This method returns how much time has elapsed since startup in a human-readable format.
* *

View file

@ -13,7 +13,7 @@ class UA
protected static $_mobile_cache = array(); protected static $_mobile_cache = array();
protected static $_tablet_cache = array(); protected static $_tablet_cache = array();
protected static $_robot_cache = array(); protected static $_robot_cache = array();
/** /**
* Windows version lookup table. * Windows version lookup table.
*/ */
@ -25,10 +25,10 @@ class UA
'6.2' => '8', '6.2' => '8',
'6.3' => '8.1', '6.3' => '8.1',
); );
/** /**
* Check whether the current visitor is using a mobile device. * Check whether the current visitor is using a mobile device.
* *
* @param string $ua (optional) * @param string $ua (optional)
* @return bool * @return bool
*/ */
@ -44,37 +44,37 @@ class UA
{ {
$using_header = false; $using_header = false;
} }
// If the User-Agent header is missing, it's probably not a mobile browser. // If the User-Agent header is missing, it's probably not a mobile browser.
if (is_null($ua)) if (is_null($ua))
{ {
return false; return false;
} }
// Look for headers that are only used in mobile browsers. // Look for headers that are only used in mobile browsers.
if ($using_header && (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA']))) if ($using_header && (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])))
{ {
return true; return true;
} }
// Look up the cache. // Look up the cache.
if (isset(self::$_mobile_cache[$ua])) if (isset(self::$_mobile_cache[$ua]))
{ {
return self::$_mobile_cache[$ua]; return self::$_mobile_cache[$ua];
} }
// Look for the 'mobile' keyword and common mobile platform names. // Look for the 'mobile' keyword and common mobile platform names.
if (preg_match('/android|ip(hone|ad|od)|blackberry|nokia|palm|mobile/i', $ua)) if (preg_match('/android|ip(hone|ad|od)|blackberry|nokia|palm|mobile/i', $ua))
{ {
return self::$_mobile_cache[$ua] = true; return self::$_mobile_cache[$ua] = true;
} }
// Look for common non-mobile OS names. // Look for common non-mobile OS names.
if (preg_match('/windows|linux|os [x9]|bsd/i', $ua)) if (preg_match('/windows|linux|os [x9]|bsd/i', $ua))
{ {
return self::$_mobile_cache[$ua] = false; return self::$_mobile_cache[$ua] = false;
} }
// Look for other platform, manufacturer, and device names that are known to be mobile. // Look for other platform, manufacturer, and device names that are known to be mobile.
if (preg_match('/kindle|opera (mini|mobi)|polaris|netfront|fennec|motorola|symbianos|webos/i', $ua)) if (preg_match('/kindle|opera (mini|mobi)|polaris|netfront|fennec|motorola|symbianos|webos/i', $ua))
{ {
@ -84,14 +84,14 @@ class UA
{ {
return self::$_mobile_cache[$ua] = true; return self::$_mobile_cache[$ua] = true;
} }
// If we're here, it's probably not a mobile device. // If we're here, it's probably not a mobile device.
return self::$_mobile_cache[$ua] = false; return self::$_mobile_cache[$ua] = false;
} }
/** /**
* Check whether the current visitor is using a tablet. * Check whether the current visitor is using a tablet.
* *
* @param string $ua (optional) * @param string $ua (optional)
* @return bool * @return bool
*/ */
@ -99,44 +99,44 @@ class UA
{ {
// Get the User-Agent header if the caller did not specify $ua. // Get the User-Agent header if the caller did not specify $ua.
$ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null); $ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null);
// If the User-Agent header is missing, it's probably not a tablet. // If the User-Agent header is missing, it's probably not a tablet.
if (is_null($ua)) if (is_null($ua))
{ {
return false; return false;
} }
// Look up the cache. // Look up the cache.
if (isset(self::$_tablet_cache[$ua])) if (isset(self::$_tablet_cache[$ua]))
{ {
return self::$_tablet_cache[$ua]; return self::$_tablet_cache[$ua];
} }
// Check if the user-agent is mobile. // Check if the user-agent is mobile.
if (!self::isMobile($ua)) if (!self::isMobile($ua))
{ {
return self::$_tablet_cache[$ua] = false; return self::$_tablet_cache[$ua] = false;
} }
// Check for Android tablets without the 'mobile' keyword. // Check for Android tablets without the 'mobile' keyword.
if (stripos($ua, 'android') !== false && stripos($ua, 'mobile') === false) if (stripos($ua, 'android') !== false && stripos($ua, 'mobile') === false)
{ {
return self::$_tablet_cache[$ua] = true; return self::$_tablet_cache[$ua] = true;
} }
// Check for common tablet identifiers. // Check for common tablet identifiers.
if (preg_match('/tablet|pad\b|tab\b|\bgt-\d+|kindle|nook|playbook|webos|xoom/i', $ua)) if (preg_match('/tablet|pad\b|tab\b|\bgt-\d+|kindle|nook|playbook|webos|xoom/i', $ua))
{ {
return self::$_tablet_cache[$ua] = true; return self::$_tablet_cache[$ua] = true;
} }
// If we're here, it's probably not a tablet. // If we're here, it's probably not a tablet.
return self::$_tablet_cache[$ua] = false; return self::$_tablet_cache[$ua] = false;
} }
/** /**
* Check whether the current visitor is a robot. * Check whether the current visitor is a robot.
* *
* @param string $ua (optional) * @param string $ua (optional)
* @return bool * @return bool
*/ */
@ -144,25 +144,25 @@ class UA
{ {
// Get the User-Agent header if the caller did not specify $ua. // Get the User-Agent header if the caller did not specify $ua.
$ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null); $ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null);
// If the User-Agent header is missing, it's probably not a robot. // If the User-Agent header is missing, it's probably not a robot.
if (is_null($ua)) if (is_null($ua))
{ {
return false; return false;
} }
// Look up the cache. // Look up the cache.
if (isset(self::$_robot_cache[$ua])) if (isset(self::$_robot_cache[$ua]))
{ {
return self::$_robot_cache[$ua]; return self::$_robot_cache[$ua];
} }
// Look for common search engine names and the 'bot' keyword. // Look for common search engine names and the 'bot' keyword.
if (preg_match('/bot|spider|crawler|archiver|wget|curl|php|slurp|wordpress|facebook|teoma|yeti|daum|apachebench|mediapartners-google|[(<+]https?:|@/i', $ua)) if (preg_match('/bot|spider|crawler|archiver|wget|curl|php|slurp|wordpress|facebook|teoma|yeti|daum|apachebench|mediapartners-google|[(<+]https?:|@/i', $ua))
{ {
return self::$_robot_cache[$ua] = true; return self::$_robot_cache[$ua] = true;
} }
// Use the custom user-agent list. // Use the custom user-agent list.
$customlist = Config::get('security.robot_user_agents') ?: array(); $customlist = Config::get('security.robot_user_agents') ?: array();
foreach ($customlist as $item) foreach ($customlist as $item)
@ -172,14 +172,14 @@ class UA
return self::$_robot_cache[$ua] = true; return self::$_robot_cache[$ua] = true;
} }
} }
// If we're here, it's probably not a robot. // If we're here, it's probably not a robot.
return self::$_robot_cache[$ua] = false; return self::$_robot_cache[$ua] = false;
} }
/** /**
* This method parses the Accept-Language header to guess the browser's default locale. * This method parses the Accept-Language header to guess the browser's default locale.
* *
* @param string $header (optional) * @param string $header (optional)
* @return string * @return string
*/ */
@ -187,14 +187,14 @@ class UA
{ {
// Get the Accept-Language header if the caller did not specify $header. // Get the Accept-Language header if the caller did not specify $header.
$header = $header ?: (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en-US'); $header = $header ?: (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en-US');
// Return the first locale name found. // Return the first locale name found.
return preg_match('/^([a-z0-9_-]+)/i', $header, $matches) ? $matches[1] : 'en-US'; return preg_match('/^([a-z0-9_-]+)/i', $header, $matches) ? $matches[1] : 'en-US';
} }
/** /**
* This method parses the User-Agent string to guess what kind of browser it is. * This method parses the User-Agent string to guess what kind of browser it is.
* *
* @param string $ua (optional) * @param string $ua (optional)
* @return object * @return object
*/ */
@ -202,7 +202,7 @@ class UA
{ {
// Get the User-Agent header if the caller did not specify $ua. // Get the User-Agent header if the caller did not specify $ua.
$ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null); $ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null);
// Initialize the result. // Initialize the result.
$result = (object)array( $result = (object)array(
'browser' => null, 'browser' => null,
@ -219,7 +219,7 @@ class UA
{ {
return $result; return $result;
} }
// Try to guess the OS. // Try to guess the OS.
if (preg_match('#(Windows|Android|Linux|i(?:Phone|P[ao]d)|OS X|Macintosh)#i', $ua, $matches)) if (preg_match('#(Windows|Android|Linux|i(?:Phone|P[ao]d)|OS X|Macintosh)#i', $ua, $matches))
{ {
@ -258,13 +258,13 @@ class UA
} }
} }
} }
// Fill in miscellaneous fields. // Fill in miscellaneous fields.
$result->is_mobile = self::isMobile($ua); $result->is_mobile = self::isMobile($ua);
$result->is_tablet = self::isTablet($ua); $result->is_tablet = self::isTablet($ua);
$result->is_webview = strpos($ua, '; wv)') !== false; $result->is_webview = strpos($ua, '; wv)') !== false;
$result->is_robot = self::isRobot($ua); $result->is_robot = self::isRobot($ua);
// Try to match some of the most common browsers. // Try to match some of the most common browsers.
if ($result->os === 'Android' && preg_match('#Android ([0-9]+\\.[0-9]+)#', $ua, $matches)) if ($result->os === 'Android' && preg_match('#Android ([0-9]+\\.[0-9]+)#', $ua, $matches))
{ {
@ -361,15 +361,15 @@ class UA
$result->version = isset($matches[2]) ? ($matches[2] ?: null) : null; $result->version = isset($matches[2]) ? ($matches[2] ?: null) : null;
return $result; return $result;
} }
return $result; return $result;
} }
/** /**
* This method encodes a UTF-8 filename for downloading in the current visitor's browser. * This method encodes a UTF-8 filename for downloading in the current visitor's browser.
* *
* See: https://blog.bloodcat.com/302 * See: https://blog.bloodcat.com/302
* *
* @param string $filename * @param string $filename
* @param string $ua (optional) * @param string $ua (optional)
* @return string * @return string
@ -378,10 +378,10 @@ class UA
{ {
// Get the User-Agent header if the caller did not specify $ua. // Get the User-Agent header if the caller did not specify $ua.
$ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null); $ua = $ua ?: (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null);
// Get the browser name and version. // Get the browser name and version.
$browser = self::getBrowserInfo($ua); $browser = self::getBrowserInfo($ua);
// Find the best format that this browser supports. // Find the best format that this browser supports.
if ($browser->browser === 'Chrome' && $browser->version >= 11 & !$browser->is_webview) if ($browser->browser === 'Chrome' && $browser->version >= 11 & !$browser->is_webview)
{ {
@ -419,30 +419,30 @@ class UA
{ {
$output_format = 'old_ie'; $output_format = 'old_ie';
} }
// Clean the filename. // Clean the filename.
$filename = Filters\FilenameFilter::clean($filename); $filename = Filters\FilenameFilter::clean($filename);
// Apply the format and return. // Apply the format and return.
switch ($output_format) switch ($output_format)
{ {
case 'raw': case 'raw':
return 'filename="' . $filename . '"'; return 'filename="' . $filename . '"';
case 'rfc5987': case 'rfc5987':
$filename = rawurlencode($filename); $filename = rawurlencode($filename);
return "filename*=UTF-8''" . $filename; return "filename*=UTF-8''" . $filename;
case 'old_ie': case 'old_ie':
default: default:
$filename = rawurlencode($filename); $filename = rawurlencode($filename);
return 'filename="' . preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1) . '"'; return 'filename="' . preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1) . '"';
} }
} }
/** /**
* Get the current color scheme (auto, light, dark) * Get the current color scheme (auto, light, dark)
* *
* @return string * @return string
*/ */
public static function getColorScheme(): string public static function getColorScheme(): string
@ -456,10 +456,10 @@ class UA
return 'auto'; return 'auto';
} }
} }
/** /**
* Set the color scheme (auto, light, dark) * Set the color scheme (auto, light, dark)
* *
* @param string $color_scheme * @param string $color_scheme
* @return void * @return void
*/ */

View file

@ -9,10 +9,10 @@ class URL
{ {
/** /**
* Get the current URL. * Get the current URL.
* *
* If $changes are given, they will be appended to the current URL as a query string. * If $changes are given, they will be appended to the current URL as a query string.
* To delete an existing query string, set its value to null. * To delete an existing query string, set its value to null.
* *
* @param array $changes * @param array $changes
* @return string * @return string
*/ */
@ -29,10 +29,10 @@ class URL
return self::getCanonicalURL($url); return self::getCanonicalURL($url);
} }
} }
/** /**
* Get the current domain. * Get the current domain.
* *
* @param string $path * @param string $path
* @return string * @return string
*/ */
@ -42,10 +42,10 @@ class URL
$host = isset($_SERVER['HTTP_HOST']) ? self::decodeIdna($_SERVER['HTTP_HOST']) : 'localhost'; $host = isset($_SERVER['HTTP_HOST']) ? self::decodeIdna($_SERVER['HTTP_HOST']) : 'localhost';
return $proto . $host . '/' . ltrim($path, '/'); return $proto . $host . '/' . ltrim($path, '/');
} }
/** /**
* Convert a URL to its canonical format. * Convert a URL to its canonical format.
* *
* @param string $url * @param string $url
* @return string * @return string
*/ */
@ -60,10 +60,10 @@ class URL
return $matches[1] . '//' . self::decodeIdna($matches[2]); return $matches[1] . '//' . self::decodeIdna($matches[2]);
}, $url); }, $url);
} }
/** /**
* Get the domain from a URL. * Get the domain from a URL.
* *
* @param string $url * @param string $url
* @return string|false * @return string|false
*/ */
@ -79,10 +79,10 @@ class URL
return self::decodeIdna($domain); return self::decodeIdna($domain);
} }
} }
/** /**
* Check if a URL is internal to this site. * Check if a URL is internal to this site.
* *
* @param string $url * @param string $url
* @return bool * @return bool
*/ */
@ -93,26 +93,26 @@ class URL
{ {
return true; return true;
} }
if ($domain === self::getDomainFromURL('http://' . $_SERVER['HTTP_HOST'])) if ($domain === self::getDomainFromURL('http://' . $_SERVER['HTTP_HOST']))
{ {
return true; return true;
} }
if (\ModuleModel::getInstance()->getSiteInfoByDomain($domain)) if (\ModuleModel::getInstance()->getSiteInfoByDomain($domain))
{ {
return true; return true;
} }
return false; return false;
} }
/** /**
* Modify a URL. * Modify a URL.
* *
* If $changes are given, they will be appended to the current URL as a query string. * If $changes are given, they will be appended to the current URL as a query string.
* To delete an existing query string, set its value to null. * To delete an existing query string, set its value to null.
* *
* @param string $url * @param string $url
* @param array $changes * @param array $changes
* @return string * @return string
@ -133,13 +133,13 @@ class URL
return $prefix; return $prefix;
} }
} }
/** /**
* Convert a server-side path to a URL. * Convert a server-side path to a URL.
* *
* This method returns false if the path cannot be converted to a URL, * This method returns false if the path cannot be converted to a URL,
* e.g. if the path is outside of the document root. * e.g. if the path is outside of the document root.
* *
* @param string $path * @param string $path
* @return string|false * @return string|false
*/ */
@ -161,13 +161,13 @@ class URL
} }
return false; return false;
} }
/** /**
* Convert a URL to a server-side path. * Convert a URL to a server-side path.
* *
* This method returns false if the URL cannot be converted to a server-side path, * This method returns false if the URL cannot be converted to a server-side path,
* e.g. if the URL belongs to an external domain. * e.g. if the URL belongs to an external domain.
* *
* @param string $url * @param string $url
* @return string * @return string
*/ */
@ -180,10 +180,10 @@ class URL
} }
return Filters\FilenameFilter::cleanPath($_SERVER['DOCUMENT_ROOT'] . parse_url($url, \PHP_URL_PATH)); return Filters\FilenameFilter::cleanPath($_SERVER['DOCUMENT_ROOT'] . parse_url($url, \PHP_URL_PATH));
} }
/** /**
* Encode UTF-8 domain into IDNA (punycode) * Encode UTF-8 domain into IDNA (punycode)
* *
* @param string $url * @param string $url
* @return string * @return string
*/ */
@ -203,7 +203,7 @@ class URL
$domain = $url; $domain = $url;
$position = 0; $position = 0;
} }
if (function_exists('idn_to_ascii')) if (function_exists('idn_to_ascii'))
{ {
$new_domain = idn_to_ascii($domain); $new_domain = idn_to_ascii($domain);
@ -213,13 +213,13 @@ class URL
$encoder = new \TrueBV\Punycode(); $encoder = new \TrueBV\Punycode();
$new_domain = $encoder->encode($domain); $new_domain = $encoder->encode($domain);
} }
return substr_replace($url, $new_domain, $position, strlen($domain)); return substr_replace($url, $new_domain, $position, strlen($domain));
} }
/** /**
* Convert IDNA (punycode) domain into UTF-8 * Convert IDNA (punycode) domain into UTF-8
* *
* @param string $url * @param string $url
* @return string * @return string
*/ */
@ -239,7 +239,7 @@ class URL
$domain = $url; $domain = $url;
$position = 0; $position = 0;
} }
if (function_exists('idn_to_utf8')) if (function_exists('idn_to_utf8'))
{ {
$new_domain = idn_to_utf8($domain); $new_domain = idn_to_utf8($domain);
@ -249,7 +249,7 @@ class URL
$decoder = new \TrueBV\Punycode(); $decoder = new \TrueBV\Punycode();
$new_domain = $decoder->decode($domain); $new_domain = $decoder->decode($domain);
} }
return substr_replace($url, $new_domain, $position, strlen($domain)); return substr_replace($url, $new_domain, $position, strlen($domain));
} }
} }

View file

@ -9,47 +9,47 @@ interface CacheInterface
{ {
/** /**
* Create a new instance of the current cache driver, using the given settings. * Create a new instance of the current cache driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
public static function getInstance(array $config); public static function getInstance(array $config);
/** /**
* Check if the current cache driver is supported on this server. * Check if the current cache driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported(); public static function isSupported();
/** /**
* Validate cache settings. * Validate cache settings.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param mixed $config * @param mixed $config
* @return bool * @return bool
*/ */
public static function validateSettings($config); public static function validateSettings($config);
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
public function get($key); public function get($key);
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is zero, the key should not expire. * $ttl is measured in seconds. If it is zero, the key should not expire.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl * @param int $ttl
@ -57,57 +57,57 @@ interface CacheInterface
* @return bool * @return bool
*/ */
public function set($key, $value, $ttl = 0, $force = false); public function set($key, $value, $ttl = 0, $force = false);
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
public function delete($key); public function delete($key);
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
public function exists($key); public function exists($key);
/** /**
* Increase the value of a key by $amount. * Increase the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
*/ */
public function incr($key, $amount); public function incr($key, $amount);
/** /**
* Decrease the value of a key by $amount. * Decrease the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
*/ */
public function decr($key, $amount); public function decr($key, $amount);
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public function clear(); public function clear();

View file

@ -9,61 +9,61 @@ interface MailInterface
{ {
/** /**
* Create a new instance of the current mail driver, using the given settings. * Create a new instance of the current mail driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
public static function getInstance(array $config); public static function getInstance(array $config);
/** /**
* Get the human-readable name of this mail driver. * Get the human-readable name of this mail driver.
* *
* @return string * @return string
*/ */
public static function getName(); public static function getName();
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig(); public static function getRequiredConfig();
/** /**
* Get the list of API types supported by this mail driver. * Get the list of API types supported by this mail driver.
* *
* @return array * @return array
*/ */
public static function getAPITypes(); public static function getAPITypes();
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint(); public static function getSPFHint();
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint(); public static function getDKIMHint();
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported(); public static function isSupported();
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */

View file

@ -9,47 +9,47 @@ interface PushInterface
{ {
/** /**
* Create a new instance of the current Push driver, using the given settings. * Create a new instance of the current Push driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
public static function getInstance(array $config): PushInterface; public static function getInstance(array $config): PushInterface;
/** /**
* Get the human-readable name of this Push driver. * Get the human-readable name of this Push driver.
* *
* @return string * @return string
*/ */
public static function getName(): string; public static function getName(): string;
/** /**
* Get the list of configuration fields required by this Push driver. * Get the list of configuration fields required by this Push driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig(): array; public static function getRequiredConfig(): array;
/** /**
* Get the list of configuration fields optionally used by this Push driver. * Get the list of configuration fields optionally used by this Push driver.
* *
* @return array * @return array
*/ */
public static function getOptionalConfig(): array; public static function getOptionalConfig(): array;
/** /**
* Check if the current SMS driver is supported on this server. * Check if the current SMS driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported(): bool; public static function isSupported(): bool;
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @param array $tokens * @param array $tokens
* @return \stdClass * @return \stdClass

View file

@ -9,61 +9,61 @@ interface SMSInterface
{ {
/** /**
* Create a new instance of the current SMS driver, using the given settings. * Create a new instance of the current SMS driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
public static function getInstance(array $config); public static function getInstance(array $config);
/** /**
* Get the human-readable name of this SMS driver. * Get the human-readable name of this SMS driver.
* *
* @return string * @return string
*/ */
public static function getName(); public static function getName();
/** /**
* Get the list of configuration fields required by this SMS driver. * Get the list of configuration fields required by this SMS driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig(); public static function getRequiredConfig();
/** /**
* Get the list of configuration fields optionally used by this SMS driver. * Get the list of configuration fields optionally used by this SMS driver.
* *
* @return array * @return array
*/ */
public static function getOptionalConfig(); public static function getOptionalConfig();
/** /**
* Get the list of API types supported by this SMS driver. * Get the list of API types supported by this SMS driver.
* *
* @return array * @return array
*/ */
public static function getAPITypes(); public static function getAPITypes();
/** /**
* Get the spec for this SMS driver. * Get the spec for this SMS driver.
* *
* @return array * @return array
*/ */
public static function getAPISpec(); public static function getAPISpec();
/** /**
* Check if the current SMS driver is supported on this server. * Check if the current SMS driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported(); public static function isSupported();
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param array $messages * @param array $messages
* @param object $original * @param object $original
* @return bool * @return bool

View file

@ -11,23 +11,23 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
* Set this flag to false to disable cache prefixes. * Set this flag to false to disable cache prefixes.
*/ */
public $prefix = true; public $prefix = true;
/** /**
* The singleton instance is stored here. * The singleton instance is stored here.
*/ */
protected static $_instance = null; protected static $_instance = null;
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
protected function __construct() protected function __construct()
{ {
} }
/** /**
* Create a new instance of the current cache driver, using the given settings. * Create a new instance of the current cache driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
@ -39,24 +39,24 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
} }
return self::$_instance; return self::$_instance;
} }
/** /**
* Check if the current cache driver is supported on this server. * Check if the current cache driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return function_exists('apcu_exists'); return function_exists('apcu_exists');
} }
/** /**
* Validate cache settings. * Validate cache settings.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param mixed $config * @param mixed $config
* @return bool * @return bool
*/ */
@ -64,12 +64,12 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return true; return true;
} }
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -78,13 +78,13 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
$value = apcu_fetch($key); $value = apcu_fetch($key);
return $value === false ? null : $value; return $value === false ? null : $value;
} }
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is zero, the key should not expire. * $ttl is measured in seconds. If it is zero, the key should not expire.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl * @param int $ttl
@ -95,13 +95,13 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return apcu_store($key, $value, $ttl); return apcu_store($key, $value, $ttl);
} }
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -109,12 +109,12 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return apcu_delete($key); return apcu_delete($key);
} }
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -122,13 +122,13 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return apcu_exists($key); return apcu_exists($key);
} }
/** /**
* Increase the value of a key by $amount. * Increase the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -143,13 +143,13 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
} }
return $result; return $result;
} }
/** /**
* Decrease the value of a key by $amount. * Decrease the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -164,12 +164,12 @@ class APC implements \Rhymix\Framework\Drivers\CacheInterface
} }
return $result; return $result;
} }
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public function clear() public function clear()

View file

@ -11,32 +11,32 @@ class Dummy extends File implements \Rhymix\Framework\Drivers\CacheInterface
* Set this flag to false to disable cache prefixes. * Set this flag to false to disable cache prefixes.
*/ */
public $prefix = false; public $prefix = false;
/** /**
* The singleton instance is stored here. * The singleton instance is stored here.
*/ */
protected static $_instance = null; protected static $_instance = null;
/** /**
* Dummy data is stored here. * Dummy data is stored here.
*/ */
public $data = array(); public $data = array();
/** /**
* Override the isSupported() method of the file driver. * Override the isSupported() method of the file driver.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -61,13 +61,13 @@ class Dummy extends File implements \Rhymix\Framework\Drivers\CacheInterface
return null; return null;
} }
} }
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is zero, the key should not expire. * $ttl is measured in seconds. If it is zero, the key should not expire.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl * @param int $ttl
@ -86,13 +86,13 @@ class Dummy extends File implements \Rhymix\Framework\Drivers\CacheInterface
return true; return true;
} }
} }
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -112,12 +112,12 @@ class Dummy extends File implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -125,12 +125,12 @@ class Dummy extends File implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return parent::exists($key) || isset($this->data[$key]); return parent::exists($key) || isset($this->data[$key]);
} }
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public function clear() public function clear()

View file

@ -13,17 +13,17 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
* Set this flag to false to disable cache prefixes. * Set this flag to false to disable cache prefixes.
*/ */
public $prefix = false; public $prefix = false;
/** /**
* The singleton instance is stored here. * The singleton instance is stored here.
*/ */
protected static $_instance = null; protected static $_instance = null;
/** /**
* The cache directory. * The cache directory.
*/ */
protected $_dir; protected $_dir;
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -35,10 +35,10 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
Storage::createDirectory($this->_dir); Storage::createDirectory($this->_dir);
} }
} }
/** /**
* Create a new instance of the current cache driver, using the given settings. * Create a new instance of the current cache driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
@ -50,23 +50,23 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
} }
return static::$_instance; return static::$_instance;
} }
/** /**
* Since Rhymix 2.1, This method always returns false. * Since Rhymix 2.1, This method always returns false.
* The file cache driver can only be used through the dummy driver. * The file cache driver can only be used through the dummy driver.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return false; return false;
} }
/** /**
* Validate cache settings. * Validate cache settings.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param mixed $config * @param mixed $config
* @return bool * @return bool
*/ */
@ -74,12 +74,12 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return true; return true;
} }
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -87,7 +87,7 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
{ {
$filename = $this->_getFilename($key); $filename = $this->_getFilename($key);
$data = Storage::readPHPData($filename); $data = Storage::readPHPData($filename);
if ($data === false) if ($data === false)
{ {
return null; return null;
@ -102,13 +102,13 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
return $data[1]; return $data[1];
} }
} }
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is zero, the key should not expire. * $ttl is measured in seconds. If it is zero, the key should not expire.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl * @param int $ttl
@ -119,13 +119,13 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return Storage::writePHPData($this->_getFilename($key), array($ttl ? (time() + $ttl) : 0, $value), $key); return Storage::writePHPData($this->_getFilename($key), array($ttl ? (time() + $ttl) : 0, $value), $key);
} }
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -133,12 +133,12 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return Storage::delete($this->_getFilename($key)); return Storage::delete($this->_getFilename($key));
} }
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -146,13 +146,13 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return $this->get($key) !== null; return $this->get($key) !== null;
} }
/** /**
* Increase the value of a key by $amount. * Increase the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -163,13 +163,13 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
$success = $this->set($key, $value + $amount, 0, true); $success = $this->set($key, $value + $amount, 0, true);
return $success ? ($value + $amount) : false; return $success ? ($value + $amount) : false;
} }
/** /**
* Decrease the value of a key by $amount. * Decrease the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -178,22 +178,22 @@ class File implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return $this->incr($key, 0 - $amount); return $this->incr($key, 0 - $amount);
} }
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public function clear() public function clear()
{ {
return Storage::deleteDirectory($this->_dir) ? true : false; return Storage::deleteDirectory($this->_dir) ? true : false;
} }
/** /**
* Get the filename to store a key. * Get the filename to store a key.
* *
* @param string $key * @param string $key
* @return string * @return string
*/ */

View file

@ -11,18 +11,18 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
* Set this flag to false to disable cache prefixes. * Set this flag to false to disable cache prefixes.
*/ */
public $prefix = true; public $prefix = true;
/** /**
* The singleton instance is stored here. * The singleton instance is stored here.
*/ */
protected static $_instance = null; protected static $_instance = null;
/** /**
* The Memcached connection is stored here. * The Memcached connection is stored here.
*/ */
protected $_conn = null; protected $_conn = null;
protected $_ext = null; protected $_ext = null;
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -42,7 +42,7 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return; return;
} }
foreach ($config as $url) foreach ($config as $url)
{ {
if (starts_with('/', $url)) if (starts_with('/', $url))
@ -59,10 +59,10 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
} }
} }
} }
/** /**
* Create a new instance of the current cache driver, using the given settings. * Create a new instance of the current cache driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
@ -74,24 +74,24 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
} }
return self::$_instance; return self::$_instance;
} }
/** /**
* Check if the current cache driver is supported on this server. * Check if the current cache driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return class_exists('\\Memcached', false) || class_exists('\\Memcache', false); return class_exists('\\Memcached', false) || class_exists('\\Memcache', false);
} }
/** /**
* Validate cache settings. * Validate cache settings.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param mixed $config * @param mixed $config
* @return bool * @return bool
*/ */
@ -111,7 +111,7 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return false; return false;
} }
foreach ($config as $url) foreach ($config as $url)
{ {
if (starts_with('/', $url)) if (starts_with('/', $url))
@ -127,7 +127,7 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
} }
} }
} }
for ($i = 0; $i < 5; $i++) for ($i = 0; $i < 5; $i++)
{ {
$key = 'rhymix:test:' . md5($i); $key = 'rhymix:test:' . md5($i);
@ -136,12 +136,12 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
} }
return true; return true;
} }
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -157,13 +157,13 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
return $value; return $value;
} }
} }
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is zero, the key should not expire. * $ttl is measured in seconds. If it is zero, the key should not expire.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl * @param int $ttl
@ -181,13 +181,13 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
return $this->_conn->set($key, $value, MEMCACHE_COMPRESSED, $ttl); return $this->_conn->set($key, $value, MEMCACHE_COMPRESSED, $ttl);
} }
} }
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -195,12 +195,12 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return $this->_conn->delete($key); return $this->_conn->delete($key);
} }
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -208,13 +208,13 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return $this->_conn->get($key) !== false; return $this->_conn->get($key) !== false;
} }
/** /**
* Increase the value of a key by $amount. * Increase the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -229,13 +229,13 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
} }
return $result; return $result;
} }
/** /**
* Decrease the value of a key by $amount. * Decrease the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -250,12 +250,12 @@ class Memcached implements \Rhymix\Framework\Drivers\CacheInterface
} }
return $result; return $result;
} }
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public function clear() public function clear()

View file

@ -11,17 +11,17 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
* Set this flag to false to disable cache prefixes. * Set this flag to false to disable cache prefixes.
*/ */
public $prefix = true; public $prefix = true;
/** /**
* The singleton instance is stored here. * The singleton instance is stored here.
*/ */
protected static $_instance = null; protected static $_instance = null;
/** /**
* The Redis connection is stored here. * The Redis connection is stored here.
*/ */
protected $_conn = null; protected $_conn = null;
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -71,10 +71,10 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
$this->_conn = null; $this->_conn = null;
} }
} }
/** /**
* Create a new instance of the current cache driver, using the given settings. * Create a new instance of the current cache driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
@ -86,24 +86,24 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
} }
return self::$_instance; return self::$_instance;
} }
/** /**
* Check if the current cache driver is supported on this server. * Check if the current cache driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return class_exists('\\Redis', false); return class_exists('\\Redis', false);
} }
/** /**
* Validate cache settings. * Validate cache settings.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param mixed $config * @param mixed $config
* @return bool * @return bool
*/ */
@ -150,12 +150,12 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -169,7 +169,7 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return null; return null;
} }
if ($value === false) if ($value === false)
{ {
return null; return null;
@ -178,7 +178,7 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return $value; return $value;
} }
$value = unserialize($value); $value = unserialize($value);
if ($value === false) if ($value === false)
{ {
@ -186,13 +186,13 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
} }
return $value; return $value;
} }
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is zero, the key should not expire. * $ttl is measured in seconds. If it is zero, the key should not expire.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl * @param int $ttl
@ -211,13 +211,13 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -232,12 +232,12 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -252,13 +252,13 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Increase the value of a key by $amount. * Increase the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -274,13 +274,13 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Decrease the value of a key by $amount. * Decrease the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -296,12 +296,12 @@ class Redis implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public function clear() public function clear()

View file

@ -13,18 +13,18 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
* Set this flag to false to disable cache prefixes. * Set this flag to false to disable cache prefixes.
*/ */
public $prefix = false; public $prefix = false;
/** /**
* The singleton instance is stored here. * The singleton instance is stored here.
*/ */
protected static $_instance = null; protected static $_instance = null;
/** /**
* The database handle and prepared statements are stored here. * The database handle and prepared statements are stored here.
*/ */
protected $_dbh = null; protected $_dbh = null;
protected $_ps = array(); protected $_ps = array();
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -35,7 +35,7 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
Storage::createDirectory($dir); Storage::createDirectory($dir);
} }
$key = substr(hash_hmac('sha256', $dir, config('crypto.authentication_key')), 0, 32); $key = substr(hash_hmac('sha256', $dir, config('crypto.authentication_key')), 0, 32);
$filename = "$dir/$key.db"; $filename = "$dir/$key.db";
if (Storage::exists($filename)) if (Storage::exists($filename))
@ -51,10 +51,10 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
} }
} }
} }
/** /**
* Connect to an SQLite3 database. * Connect to an SQLite3 database.
* *
* @param string $filename * @param string $filename
* @return void * @return void
*/ */
@ -65,10 +65,10 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
$this->_dbh->exec('PRAGMA journal_mode = MEMORY'); $this->_dbh->exec('PRAGMA journal_mode = MEMORY');
$this->_dbh->exec('PRAGMA synchronous = OFF'); $this->_dbh->exec('PRAGMA synchronous = OFF');
} }
/** /**
* Create a new instance of the current cache driver, using the given settings. * Create a new instance of the current cache driver, using the given settings.
* *
* @param array $config * @param array $config
* @return void * @return void
*/ */
@ -80,24 +80,24 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
} }
return self::$_instance; return self::$_instance;
} }
/** /**
* Check if the current cache driver is supported on this server. * Check if the current cache driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return class_exists('\\SQLite3', false) && config('crypto.authentication_key') !== null && stripos(\PHP_SAPI, 'win') === false; return class_exists('\\SQLite3', false) && config('crypto.authentication_key') !== null && stripos(\PHP_SAPI, 'win') === false;
} }
/** /**
* Validate cache settings. * Validate cache settings.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param mixed $config * @param mixed $config
* @return bool * @return bool
*/ */
@ -105,12 +105,12 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return true; return true;
} }
/** /**
* Get the value of a key. * Get the value of a key.
* *
* This method returns null if the key was not found. * This method returns null if the key was not found.
* *
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
@ -122,14 +122,14 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return null; return null;
} }
$stmt->bindValue(':key', $key, \SQLITE3_TEXT); $stmt->bindValue(':key', $key, \SQLITE3_TEXT);
$result = $stmt->execute(); $result = $stmt->execute();
if (!$result) if (!$result)
{ {
return null; return null;
} }
$row = $result->fetchArray(\SQLITE3_NUM); $row = $result->fetchArray(\SQLITE3_NUM);
if ($row) if ($row)
{ {
@ -148,13 +148,13 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
return null; return null;
} }
} }
/** /**
* Set the value to a key. * Set the value to a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* $ttl is measured in seconds. If it is zero, the key should not expire. * $ttl is measured in seconds. If it is zero, the key should not expire.
* *
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* @param int $ttl * @param int $ttl
@ -169,19 +169,19 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return false; return false;
} }
$stmt->bindValue(':key', $key, \SQLITE3_TEXT); $stmt->bindValue(':key', $key, \SQLITE3_TEXT);
$stmt->bindValue(':val', serialize($value), \SQLITE3_TEXT); $stmt->bindValue(':val', serialize($value), \SQLITE3_TEXT);
$stmt->bindValue(':exp', $ttl ? (time() + $ttl) : 0, \SQLITE3_INTEGER); $stmt->bindValue(':exp', $ttl ? (time() + $ttl) : 0, \SQLITE3_INTEGER);
return $stmt->execute() ? true : false; return $stmt->execute() ? true : false;
} }
/** /**
* Delete a key. * Delete a key.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* If the key does not exist, it should return false. * If the key does not exist, it should return false.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -193,16 +193,16 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return false; return false;
} }
$stmt->bindValue(':key', $key, \SQLITE3_TEXT); $stmt->bindValue(':key', $key, \SQLITE3_TEXT);
return $stmt->execute() ? true : false; return $stmt->execute() ? true : false;
} }
/** /**
* Check if a key exists. * Check if a key exists.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param string $key * @param string $key
* @return bool * @return bool
*/ */
@ -214,7 +214,7 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return false; return false;
} }
$stmt->bindValue(':key', $key, \SQLITE3_TEXT); $stmt->bindValue(':key', $key, \SQLITE3_TEXT);
$stmt->bindValue(':exp', time(), \SQLITE3_INTEGER); $stmt->bindValue(':exp', time(), \SQLITE3_INTEGER);
$result = $stmt->execute(); $result = $stmt->execute();
@ -222,7 +222,7 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return false; return false;
} }
$row = $result->fetchArray(\SQLITE3_NUM); $row = $result->fetchArray(\SQLITE3_NUM);
if ($row) if ($row)
{ {
@ -233,13 +233,13 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Increase the value of a key by $amount. * Increase the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -260,13 +260,13 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
return false; return false;
} }
} }
/** /**
* Decrease the value of a key by $amount. * Decrease the value of a key by $amount.
* *
* If the key does not exist, this method assumes that the current value is zero. * If the key does not exist, this method assumes that the current value is zero.
* This method returns the new value. * This method returns the new value.
* *
* @param string $key * @param string $key
* @param int $amount * @param int $amount
* @return int * @return int
@ -275,12 +275,12 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
return $this->incr($key, 0 - $amount); return $this->incr($key, 0 - $amount);
} }
/** /**
* Clear all keys from the cache. * Clear all keys from the cache.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public function clear() public function clear()
@ -289,12 +289,12 @@ class SQLite implements \Rhymix\Framework\Drivers\CacheInterface
{ {
$this->_dbh->exec('DROP TABLE cache_' . $i); $this->_dbh->exec('DROP TABLE cache_' . $i);
} }
for ($i = 0; $i < 32; $i++) for ($i = 0; $i < 32; $i++)
{ {
$this->_dbh->exec('CREATE TABLE cache_' . $i . ' (k TEXT PRIMARY KEY, v TEXT, exp INT)'); $this->_dbh->exec('CREATE TABLE cache_' . $i . ' (k TEXT PRIMARY KEY, v TEXT, exp INT)');
} }
return true; return true;
} }
} }

View file

@ -11,12 +11,12 @@ abstract class Base implements \Rhymix\Framework\Drivers\MailInterface
* The configuration is stored here. * The configuration is stored here.
*/ */
protected $_config = null; protected $_config = null;
/** /**
* The mailer instance is stored here. * The mailer instance is stored here.
*/ */
protected $_mailer = null; protected $_mailer = null;
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -24,10 +24,10 @@ abstract class Base implements \Rhymix\Framework\Drivers\MailInterface
{ {
$this->_config = $config; $this->_config = $config;
} }
/** /**
* Create a new instance of the current mail driver, using the given settings. * Create a new instance of the current mail driver, using the given settings.
* *
* @param array $config * @param array $config
* @return object * @return object
*/ */
@ -35,74 +35,74 @@ abstract class Base implements \Rhymix\Framework\Drivers\MailInterface
{ {
return new static($config); return new static($config);
} }
/** /**
* Get the human-readable name of this mail driver. * Get the human-readable name of this mail driver.
* *
* @return string * @return string
*/ */
public static function getName() public static function getName()
{ {
return class_basename(get_called_class()); return class_basename(get_called_class());
} }
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array(); return array();
} }
/** /**
* Get the list of API types supported by this mail driver. * Get the list of API types supported by this mail driver.
* *
* @return array * @return array
*/ */
public static function getAPITypes() public static function getAPITypes()
{ {
return array(); return array();
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return ''; return '';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()
{ {
return ''; return '';
} }
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return false; return false;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */

View file

@ -9,21 +9,21 @@ class Dummy extends Base implements \Rhymix\Framework\Drivers\MailInterface
{ {
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */

View file

@ -15,44 +15,44 @@ class MailFunction extends Base implements \Rhymix\Framework\Drivers\MailInterfa
include_once \RX_BASEDIR . 'common/libraries/swift_mail.php'; include_once \RX_BASEDIR . 'common/libraries/swift_mail.php';
$this->mailer = new \Swift_Mailer(new \Swift_MailTransport); $this->mailer = new \Swift_Mailer(new \Swift_MailTransport);
} }
/** /**
* Get the human-readable name of this mail driver. * Get the human-readable name of this mail driver.
* *
* @return string * @return string
*/ */
public static function getName() public static function getName()
{ {
return 'mail() Function'; return 'mail() Function';
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'ip4:$SERVER_ADDR'; return 'ip4:$SERVER_ADDR';
} }
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */
@ -67,7 +67,7 @@ class MailFunction extends Base implements \Rhymix\Framework\Drivers\MailInterfa
$message->errors[] = $e->getMessage(); $message->errors[] = $e->getMessage();
return false; return false;
} }
foreach ($errors as $error) foreach ($errors as $error)
{ {
$message->errors[] = $error; $message->errors[] = $error;

View file

@ -11,54 +11,54 @@ class Mailgun extends Base implements \Rhymix\Framework\Drivers\MailInterface
* The API URL. * The API URL.
*/ */
protected static $_url = 'https://api.mailgun.net/v3'; protected static $_url = 'https://api.mailgun.net/v3';
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('api_domain', 'api_token'); return array('api_domain', 'api_token');
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'include:mailgun.org'; return 'include:mailgun.org';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()
{ {
return 'mailo._domainkey'; return 'mailo._domainkey';
} }
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */
@ -87,7 +87,7 @@ class Mailgun extends Base implements \Rhymix\Framework\Drivers\MailInterface
$recipients[] = $address; $recipients[] = $address;
} }
} }
// Prepare data and options for Requests. // Prepare data and options for Requests.
$boundary = str_repeat('-', 24) . substr(md5(mt_rand()), 0, 16); $boundary = str_repeat('-', 24) . substr(md5(mt_rand()), 0, 16);
$headers = array( $headers = array(
@ -112,12 +112,12 @@ class Mailgun extends Base implements \Rhymix\Framework\Drivers\MailInterface
'timeout' => 5, 'timeout' => 5,
'useragent' => 'PHP', 'useragent' => 'PHP',
); );
// Send the API request. // Send the API request.
$url = self::$_url . '/' . $this->_config['api_domain'] . '/messages.mime'; $url = self::$_url . '/' . $this->_config['api_domain'] . '/messages.mime';
$request = \Requests::post($url, $headers, $data, $options); $request = \Requests::post($url, $headers, $data, $options);
$result = @json_decode($request->body); $result = @json_decode($request->body);
// Parse the result. // Parse the result.
if (!$result) if (!$result)
{ {

View file

@ -19,30 +19,30 @@ class Mandrill extends SMTP implements \Rhymix\Framework\Drivers\MailInterface
$config['smtp_pass'] = $config['api_token']; $config['smtp_pass'] = $config['api_token'];
parent::__construct($config); parent::__construct($config);
} }
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('api_user', 'api_token'); return array('api_user', 'api_token');
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'include:spf.mandrillapp.com'; return 'include:spf.mandrillapp.com';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()

View file

@ -19,30 +19,30 @@ class Postmark extends SMTP implements \Rhymix\Framework\Drivers\MailInterface
$config['smtp_pass'] = $config['api_token']; $config['smtp_pass'] = $config['api_token'];
parent::__construct($config); parent::__construct($config);
} }
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('api_token'); return array('api_token');
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'include:spf.mtasv.net'; return 'include:spf.mtasv.net';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()

View file

@ -11,54 +11,54 @@ class SendGrid extends Base implements \Rhymix\Framework\Drivers\MailInterface
* The API URL. * The API URL.
*/ */
protected static $_url = 'https://api.sendgrid.com/v3/mail/send'; protected static $_url = 'https://api.sendgrid.com/v3/mail/send';
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('api_token'); return array('api_token');
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'include:sendgrid.net'; return 'include:sendgrid.net';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()
{ {
return 'smtpapi._domainkey'; return 'smtpapi._domainkey';
} }
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */
@ -70,11 +70,11 @@ class SendGrid extends Base implements \Rhymix\Framework\Drivers\MailInterface
$message->errors[] = 'SendGrid: Please use API key (token) instead of username and password.'; $message->errors[] = 'SendGrid: Please use API key (token) instead of username and password.';
return; return;
} }
// Initialize the request data. // Initialize the request data.
$data = []; $data = [];
$data['personalizations'] = []; $data['personalizations'] = [];
// Assemble the list of recipients. // Assemble the list of recipients.
$to_list = []; $to_list = [];
if ($to = $message->message->getTo()) if ($to = $message->message->getTo())
@ -103,7 +103,7 @@ class SendGrid extends Base implements \Rhymix\Framework\Drivers\MailInterface
} }
$data['personalizations'][] = ['bcc' => $bcc_list]; $data['personalizations'][] = ['bcc' => $bcc_list];
} }
// Set the sender information. // Set the sender information.
$from = $message->message->getFrom(); $from = $message->message->getFrom();
if ($from) if ($from)
@ -114,21 +114,21 @@ class SendGrid extends Base implements \Rhymix\Framework\Drivers\MailInterface
$data['from']['name'] = array_first($from); $data['from']['name'] = array_first($from);
} }
} }
// Set the Reply-To address. // Set the Reply-To address.
$replyTo = $message->message->getReplyTo(); $replyTo = $message->message->getReplyTo();
if ($replyTo) if ($replyTo)
{ {
$data['reply_to']['email'] = array_first_key($from); $data['reply_to']['email'] = array_first_key($from);
} }
// Set the subject. // Set the subject.
$data['subject'] = strval($message->getSubject()) ?: 'Title'; $data['subject'] = strval($message->getSubject()) ?: 'Title';
// Set the body. // Set the body.
$data['content'][0]['type'] = $message->getContentType(); $data['content'][0]['type'] = $message->getContentType();
$data['content'][0]['value'] = $message->getBody(); $data['content'][0]['value'] = $message->getBody();
// Add attachments. // Add attachments.
foreach ($message->getAttachments() as $attachment) foreach ($message->getAttachments() as $attachment)
{ {
@ -142,7 +142,7 @@ class SendGrid extends Base implements \Rhymix\Framework\Drivers\MailInterface
} }
$data['attachments'][] = $file_info; $data['attachments'][] = $file_info;
} }
// Prepare data and options for Requests. // Prepare data and options for Requests.
$headers = array( $headers = array(
'Authorization' => 'Bearer ' . $this->_config['api_token'], 'Authorization' => 'Bearer ' . $this->_config['api_token'],
@ -152,11 +152,11 @@ class SendGrid extends Base implements \Rhymix\Framework\Drivers\MailInterface
'timeout' => 8, 'timeout' => 8,
'useragent' => 'PHP', 'useragent' => 'PHP',
); );
// Send the API request. // Send the API request.
$request = \Requests::post(self::$_url, $headers, json_encode($data), $options); $request = \Requests::post(self::$_url, $headers, json_encode($data), $options);
$response_code = intval($request->status_code);; $response_code = intval($request->status_code);;
// Parse the result. // Parse the result.
if (!$response_code) if (!$response_code)
{ {
@ -168,7 +168,7 @@ class SendGrid extends Base implements \Rhymix\Framework\Drivers\MailInterface
$message->errors[] = 'SendGrid: Response code ' . $response_code . ': ' . $request->body; $message->errors[] = 'SendGrid: Response code ' . $response_code . ': ' . $request->body;
return false; return false;
} }
return true; return true;
} }
} }

View file

@ -11,7 +11,7 @@ class SES extends SMTP implements \Rhymix\Framework\Drivers\MailInterface
* Cache the message here for debug access. * Cache the message here for debug access.
*/ */
protected $_message; protected $_message;
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -22,30 +22,30 @@ class SES extends SMTP implements \Rhymix\Framework\Drivers\MailInterface
$config['smtp_security'] = 'tls'; $config['smtp_security'] = 'tls';
parent::__construct($config); parent::__construct($config);
} }
/** /**
* Get the human-readable name of this mail driver. * Get the human-readable name of this mail driver.
* *
* @return string * @return string
*/ */
public static function getName() public static function getName()
{ {
return 'Amazon SES (SMTP)'; return 'Amazon SES (SMTP)';
} }
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('smtp_user', 'smtp_pass', 'api_type'); return array('smtp_user', 'smtp_pass', 'api_type');
} }
/** /**
* Get the list of API types supported by this mail driver. * Get the list of API types supported by this mail driver.
* *
* @return array * @return array
*/ */
public static function getAPITypes() public static function getAPITypes()
@ -57,20 +57,20 @@ class SES extends SMTP implements \Rhymix\Framework\Drivers\MailInterface
'ap-southeast-1', 'ap-southeast-2', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-south-1',
); );
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'include:amazonses.com'; return 'include:amazonses.com';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()

View file

@ -23,34 +23,34 @@ class SMTP extends Base implements \Rhymix\Framework\Drivers\MailInterface
} }
$this->mailer = new \Swift_Mailer($transport); $this->mailer = new \Swift_Mailer($transport);
} }
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('smtp_host', 'smtp_port', 'smtp_security', 'smtp_user', 'smtp_pass'); return array('smtp_host', 'smtp_port', 'smtp_security', 'smtp_user', 'smtp_pass');
} }
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return function_exists('proc_open'); return function_exists('proc_open');
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */
@ -65,7 +65,7 @@ class SMTP extends Base implements \Rhymix\Framework\Drivers\MailInterface
$message->errors[] = $e->getMessage(); $message->errors[] = $e->getMessage();
return false; return false;
} }
foreach ($errors as $error) foreach ($errors as $error)
{ {
$message->errors[] = 'Failed to send to ' . $error; $message->errors[] = 'Failed to send to ' . $error;

View file

@ -11,54 +11,54 @@ class SparkPost extends Base implements \Rhymix\Framework\Drivers\MailInterface
* The API URL. * The API URL.
*/ */
protected static $_url = 'https://api.sparkpost.com/api/v1/transmissions'; protected static $_url = 'https://api.sparkpost.com/api/v1/transmissions';
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('api_token'); return array('api_token');
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'include:sparkpostmail.com'; return 'include:sparkpostmail.com';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()
{ {
return '********._domainkey'; return '********._domainkey';
} }
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */
@ -87,7 +87,7 @@ class SparkPost extends Base implements \Rhymix\Framework\Drivers\MailInterface
$recipients[] = array('address' => array('name' => $name, 'email' => $address)); $recipients[] = array('address' => array('name' => $name, 'email' => $address));
} }
} }
// Prepare data and options for Requests. // Prepare data and options for Requests.
$headers = array( $headers = array(
'Authorization' => $this->_config['api_token'], 'Authorization' => $this->_config['api_token'],
@ -106,11 +106,11 @@ class SparkPost extends Base implements \Rhymix\Framework\Drivers\MailInterface
'timeout' => 5, 'timeout' => 5,
'useragent' => 'PHP', 'useragent' => 'PHP',
); );
// Send the API request. // Send the API request.
$request = \Requests::post(self::$_url, $headers, $data, $options); $request = \Requests::post(self::$_url, $headers, $data, $options);
$result = @json_decode($request->body); $result = @json_decode($request->body);
// Parse the result. // Parse the result.
if (!$result) if (!$result)
{ {
@ -124,7 +124,7 @@ class SparkPost extends Base implements \Rhymix\Framework\Drivers\MailInterface
$message->errors[] = 'SparkPost: ' . $error->message . ': ' . $error->description . ' (code ' . $error->code . ')'; $message->errors[] = 'SparkPost: ' . $error->message . ': ' . $error->description . ' (code ' . $error->code . ')';
} }
} }
if ($result->results) if ($result->results)
{ {
return $result->results->total_accepted_recipients > 0 ? true : false; return $result->results->total_accepted_recipients > 0 ? true : false;

View file

@ -11,7 +11,7 @@ class Woorimail extends Base implements \Rhymix\Framework\Drivers\MailInterface
* The API URL. * The API URL.
*/ */
protected static $_url = 'https://woorimail.com/index.php'; protected static $_url = 'https://woorimail.com/index.php';
/** /**
* Error codes and messages. * Error codes and messages.
*/ */
@ -25,69 +25,69 @@ class Woorimail extends Base implements \Rhymix\Framework\Drivers\MailInterface
'me_007' => '이메일과 등록일 갯수가 다릅니다.', 'me_007' => '이메일과 등록일 갯수가 다릅니다.',
'me_008' => '이메일 갯수가 2,000개가 넘습니다.', 'me_008' => '이메일 갯수가 2,000개가 넘습니다.',
'me_009' => 'type이 api가 아닙니다.', 'me_009' => 'type이 api가 아닙니다.',
'me_010' => '인증키가 없습니다.', 'me_010' => '인증키가 없습니다.',
'me_011' => '인증키가 부정확합니다.', 'me_011' => '인증키가 부정확합니다.',
'me_012' => '포인트가 부족합니다.', 'me_012' => '포인트가 부족합니다.',
'me_013' => '전용채널에 도메인이 등록되어 있지 않습니다.', 'me_013' => '전용채널에 도메인이 등록되어 있지 않습니다.',
); );
/** /**
* Get the list of configuration fields required by this mail driver. * Get the list of configuration fields required by this mail driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return array('api_domain', 'api_token', 'api_type'); return array('api_domain', 'api_token', 'api_type');
} }
/** /**
* Get the list of API types supported by this mail driver. * Get the list of API types supported by this mail driver.
* *
* @return array * @return array
*/ */
public static function getAPITypes() public static function getAPITypes()
{ {
return array('free', 'paid'); return array('free', 'paid');
} }
/** /**
* Get the SPF hint. * Get the SPF hint.
* *
* @return string * @return string
*/ */
public static function getSPFHint() public static function getSPFHint()
{ {
return 'include:woorimail.com'; return 'include:woorimail.com';
} }
/** /**
* Get the DKIM hint. * Get the DKIM hint.
* *
* @return string * @return string
*/ */
public static function getDKIMHint() public static function getDKIMHint()
{ {
return ''; return '';
} }
/** /**
* Check if the current mail driver is supported on this server. * Check if the current mail driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @return bool * @return bool
*/ */
@ -112,7 +112,7 @@ class Woorimail extends Base implements \Rhymix\Framework\Drivers\MailInterface
'callback' => '', 'callback' => '',
'is_sendok' => 'W', 'is_sendok' => 'W',
); );
// Fill the sender info. // Fill the sender info.
$from = $message->message->getFrom(); $from = $message->message->getFrom();
foreach($from as $email => $name) foreach($from as $email => $name)
@ -137,7 +137,7 @@ class Woorimail extends Base implements \Rhymix\Framework\Drivers\MailInterface
$data['sender_email'] = $replyTo; $data['sender_email'] = $replyTo;
} }
} }
// Fill the recipient info. // Fill the recipient info.
if ($to = $message->message->getTo()) if ($to = $message->message->getTo())
{ {
@ -166,7 +166,7 @@ class Woorimail extends Base implements \Rhymix\Framework\Drivers\MailInterface
$data['member_regdate'] = implode(',', array_fill(0, count($data['receiver_email']), date('YmdHis'))); $data['member_regdate'] = implode(',', array_fill(0, count($data['receiver_email']), date('YmdHis')));
$data['receiver_email'] = implode(',', $data['receiver_email']); $data['receiver_email'] = implode(',', $data['receiver_email']);
$data['receiver_nickname'] = implode(',', $data['receiver_nickname']); $data['receiver_nickname'] = implode(',', $data['receiver_nickname']);
// Define connection options. // Define connection options.
$headers = array( $headers = array(
'Accept' => 'application/json, text/javascript, */*; q=0.1', 'Accept' => 'application/json, text/javascript, */*; q=0.1',
@ -175,7 +175,7 @@ class Woorimail extends Base implements \Rhymix\Framework\Drivers\MailInterface
'timeout' => 5, 'timeout' => 5,
'useragent' => 'PHP', 'useragent' => 'PHP',
); );
// Send the API request. // Send the API request.
try try
{ {
@ -187,7 +187,7 @@ class Woorimail extends Base implements \Rhymix\Framework\Drivers\MailInterface
$message->errors[] = 'Woorimail: ' . $e->getMessage(); $message->errors[] = 'Woorimail: ' . $e->getMessage();
return false; return false;
} }
// Parse the result. // Parse the result.
if (!$result) if (!$result)
{ {

View file

@ -12,34 +12,34 @@ class APNs extends Base implements \Rhymix\Framework\Drivers\PushInterface
*/ */
protected static $_required_config = array('certificate', 'passphrase'); protected static $_required_config = array('certificate', 'passphrase');
protected static $_optional_config = array(); protected static $_optional_config = array();
/** /**
* Get the human-readable name of this Push driver. * Get the human-readable name of this Push driver.
* *
* @return string * @return string
*/ */
public static function getName(): string public static function getName(): string
{ {
return 'APNs'; return 'APNs';
} }
/** /**
* Check if the current Push driver is supported on this server. * Check if the current Push driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported(): bool public static function isSupported(): bool
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @param array $tokens * @param array $tokens
* @return \stdClass * @return \stdClass
@ -86,7 +86,7 @@ class APNs extends Base implements \Rhymix\Framework\Drivers\PushInterface
$output->success[] = $token; $output->success[] = $token;
fclose($fp); fclose($fp);
} }
return $output; return $output;
} }
} }

View file

@ -13,13 +13,13 @@ abstract class Base implements PushInterface
* The configuration is stored here. * The configuration is stored here.
*/ */
protected $_config = null; protected $_config = null;
/** /**
* Config keys used by this driver are stored here. * Config keys used by this driver are stored here.
*/ */
protected static $_required_config = array(); protected static $_required_config = array();
protected static $_optional_config = array(); protected static $_optional_config = array();
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -27,10 +27,10 @@ abstract class Base implements PushInterface
{ {
$this->_config = $config; $this->_config = $config;
} }
/** /**
* Create a new instance of the current Push driver, using the given settings. * Create a new instance of the current Push driver, using the given settings.
* *
* @param array $config * @param array $config
* @return PushInterface * @return PushInterface
*/ */
@ -38,54 +38,54 @@ abstract class Base implements PushInterface
{ {
return new static($config); return new static($config);
} }
/** /**
* Get the human-readable name of this Push driver. * Get the human-readable name of this Push driver.
* *
* @return string * @return string
*/ */
public static function getName(): string public static function getName(): string
{ {
return class_basename(get_called_class()); return class_basename(get_called_class());
} }
/** /**
* Get the list of configuration fields required by this Push driver. * Get the list of configuration fields required by this Push driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig(): array public static function getRequiredConfig(): array
{ {
return static::$_required_config; return static::$_required_config;
} }
/** /**
* Get the list of configuration fields optionally used by this Push driver. * Get the list of configuration fields optionally used by this Push driver.
* *
* @return array * @return array
*/ */
public static function getOptionalConfig(): array public static function getOptionalConfig(): array
{ {
return static::$_optional_config; return static::$_optional_config;
} }
/** /**
* Check if the current Push driver is supported on this server. * Check if the current Push driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported(): bool public static function isSupported(): bool
{ {
return false; return false;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @param array $tokens * @param array $tokens
* @return \stdClass * @return \stdClass

View file

@ -12,34 +12,34 @@ class FCM extends Base implements \Rhymix\Framework\Drivers\PushInterface
*/ */
protected static $_required_config = array('api_key'); protected static $_required_config = array('api_key');
protected static $_optional_config = array(); protected static $_optional_config = array();
/** /**
* Get the human-readable name of this Push driver. * Get the human-readable name of this Push driver.
* *
* @return string * @return string
*/ */
public static function getName(): string public static function getName(): string
{ {
return 'Google FCM'; return 'Google FCM';
} }
/** /**
* Check if the current Push driver is supported on this server. * Check if the current Push driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported(): bool public static function isSupported(): bool
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param object $message * @param object $message
* @param array $tokens * @param array $tokens
* @return \stdClass * @return \stdClass

View file

@ -23,34 +23,34 @@ class ApiStore extends Base implements \Rhymix\Framework\Drivers\SMSInterface
'mms_supported' => false, 'mms_supported' => false,
'delay_supported' => true, 'delay_supported' => true,
); );
/** /**
* Config keys used by this driver are stored here. * Config keys used by this driver are stored here.
*/ */
protected static $_required_config = array('api_user', 'api_key'); protected static $_required_config = array('api_user', 'api_key');
/** /**
* Check if the current SMS driver is supported on this server. * Check if the current SMS driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Store the last response. * Store the last response.
*/ */
protected $_last_response = ''; protected $_last_response = '';
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param array $messages * @param array $messages
* @param object $original * @param object $original
* @return bool * @return bool
@ -58,7 +58,7 @@ class ApiStore extends Base implements \Rhymix\Framework\Drivers\SMSInterface
public function send(array $messages, \Rhymix\Framework\SMS $original) public function send(array $messages, \Rhymix\Framework\SMS $original)
{ {
$status = true; $status = true;
foreach ($messages as $i => $message) foreach ($messages as $i => $message)
{ {
$data = array(); $data = array();
@ -69,7 +69,7 @@ class ApiStore extends Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
$data['subject'] = $message->subject; $data['subject'] = $message->subject;
} }
$result = $this->_apiCall(sprintf('message/%s', strtolower($message->type)), $data); $result = $this->_apiCall(sprintf('message/%s', strtolower($message->type)), $data);
if (!$result) if (!$result)
{ {
@ -81,13 +81,13 @@ class ApiStore extends Base implements \Rhymix\Framework\Drivers\SMSInterface
$message->errors[] = 'ApiStore API error: ' . $result->result_code . ' ' . $result->result_message; $message->errors[] = 'ApiStore API error: ' . $result->result_code . ' ' . $result->result_message;
} }
} }
return $status; return $status;
} }
/** /**
* API call. * API call.
* *
* @param string $url * @param string $url
* @param array $data * @param array $data
* @param string $method (optional) * @param string $method (optional)
@ -106,12 +106,12 @@ class ApiStore extends Base implements \Rhymix\Framework\Drivers\SMSInterface
$version = 1; $version = 1;
} }
$url = sprintf('http://api.apistore.co.kr/ppurio/%d/%s/%s', $version, trim($url, '/'), $this->_config['api_user']); $url = sprintf('http://api.apistore.co.kr/ppurio/%d/%s/%s', $version, trim($url, '/'), $this->_config['api_user']);
// Set the API key in the header. // Set the API key in the header.
$headers = array( $headers = array(
'x-waple-authorization' => $this->_config['api_key'], 'x-waple-authorization' => $this->_config['api_key'],
); );
// Send the API reqeust. // Send the API reqeust.
if ($method === 'GET') if ($method === 'GET')
{ {
@ -128,10 +128,10 @@ class ApiStore extends Base implements \Rhymix\Framework\Drivers\SMSInterface
$result = @json_decode($this->_last_response); $result = @json_decode($this->_last_response);
return $result ?: false; return $result ?: false;
} }
/** /**
* Fetch the last API response. * Fetch the last API response.
* *
* @return string * @return string
*/ */
protected function _getLastResponse() protected function _getLastResponse()

View file

@ -11,18 +11,18 @@ abstract class Base implements \Rhymix\Framework\Drivers\SMSInterface
* The configuration is stored here. * The configuration is stored here.
*/ */
protected $_config = null; protected $_config = null;
/** /**
* The driver specification is stored here. * The driver specification is stored here.
*/ */
protected static $_spec = array(); protected static $_spec = array();
/** /**
* Config keys used by this driver are stored here. * Config keys used by this driver are stored here.
*/ */
protected static $_required_config = array(); protected static $_required_config = array();
protected static $_optional_config = array(); protected static $_optional_config = array();
/** /**
* Direct invocation of the constructor is not permitted. * Direct invocation of the constructor is not permitted.
*/ */
@ -30,10 +30,10 @@ abstract class Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
$this->_config = $config; $this->_config = $config;
} }
/** /**
* Create a new instance of the current SMS driver, using the given settings. * Create a new instance of the current SMS driver, using the given settings.
* *
* @param array $config * @param array $config
* @return object * @return object
*/ */
@ -41,74 +41,74 @@ abstract class Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
return new static($config); return new static($config);
} }
/** /**
* Get the human-readable name of this SMS driver. * Get the human-readable name of this SMS driver.
* *
* @return string * @return string
*/ */
public static function getName() public static function getName()
{ {
return class_basename(get_called_class()); return class_basename(get_called_class());
} }
/** /**
* Get the list of configuration fields required by this SMS driver. * Get the list of configuration fields required by this SMS driver.
* *
* @return array * @return array
*/ */
public static function getRequiredConfig() public static function getRequiredConfig()
{ {
return static::$_required_config; return static::$_required_config;
} }
/** /**
* Get the list of configuration fields optionally used by this SMS driver. * Get the list of configuration fields optionally used by this SMS driver.
* *
* @return array * @return array
*/ */
public static function getOptionalConfig() public static function getOptionalConfig()
{ {
return static::$_optional_config; return static::$_optional_config;
} }
/** /**
* Get the list of API types supported by this SMS driver. * Get the list of API types supported by this SMS driver.
* *
* @return array * @return array
*/ */
public static function getAPITypes() public static function getAPITypes()
{ {
return array(); return array();
} }
/** /**
* Get the spec for this SMS driver. * Get the spec for this SMS driver.
* *
* @return array * @return array
*/ */
public static function getAPISpec() public static function getAPISpec()
{ {
return static::$_spec; return static::$_spec;
} }
/** /**
* Check if the current SMS driver is supported on this server. * Check if the current SMS driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return false; return false;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param array $messages * @param array $messages
* @param object $original * @param object $original
* @return bool * @return bool

View file

@ -31,30 +31,30 @@ class CoolSMS extends Base implements \Rhymix\Framework\Drivers\SMSInterface
'image_max_filesize' => 300000, 'image_max_filesize' => 300000,
'delay_supported' => true, 'delay_supported' => true,
); );
/** /**
* Config keys used by this driver are stored here. * Config keys used by this driver are stored here.
*/ */
protected static $_required_config = array('api_key', 'api_secret'); protected static $_required_config = array('api_key', 'api_secret');
protected static $_optional_config = array('sender_key'); protected static $_optional_config = array('sender_key');
/** /**
* Check if the current SMS driver is supported on this server. * Check if the current SMS driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param array $messages * @param array $messages
* @param object $original * @param object $original
* @return bool * @return bool
@ -111,7 +111,7 @@ class CoolSMS extends Base implements \Rhymix\Framework\Drivers\SMSInterface
$status = false; $status = false;
} }
} }
return $status; return $status;
} }
catch (\Nurigo\Exceptions\CoolsmsException $e) catch (\Nurigo\Exceptions\CoolsmsException $e)

View file

@ -31,29 +31,29 @@ class Dummy extends Base implements \Rhymix\Framework\Drivers\SMSInterface
'image_max_filesize' => 300000, 'image_max_filesize' => 300000,
'delay_supported' => true, 'delay_supported' => true,
); );
/** /**
* Sent messages are stored here for debugging and testing. * Sent messages are stored here for debugging and testing.
*/ */
protected $_sent_messages = array(); protected $_sent_messages = array();
/** /**
* Check if the current SMS driver is supported on this server. * Check if the current SMS driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param array $messages * @param array $messages
* @param object $original * @param object $original
* @return bool * @return bool
@ -66,20 +66,20 @@ class Dummy extends Base implements \Rhymix\Framework\Drivers\SMSInterface
} }
return true; return true;
} }
/** /**
* Get sent messages. * Get sent messages.
* *
* @return array * @return array
*/ */
public function getSentMessages() public function getSentMessages()
{ {
return $this->_sent_messages; return $this->_sent_messages;
} }
/** /**
* Reset sent messages. * Reset sent messages.
* *
* @return void * @return void
*/ */
public function resetSentMessages() public function resetSentMessages()

View file

@ -11,7 +11,7 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
* API endpoint URL (fallback if URL is not explicitly configured) * API endpoint URL (fallback if URL is not explicitly configured)
*/ */
const LEGACY_API_URL = 'https://sms.service.iwinv.kr/send/'; const LEGACY_API_URL = 'https://sms.service.iwinv.kr/send/';
/** /**
* API specifications. * API specifications.
*/ */
@ -54,10 +54,10 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
return true; return true;
} }
/** /**
* Get the list of API URLs supported by this driver. * Get the list of API URLs supported by this driver.
* *
* @return array * @return array
*/ */
public static function getApiUrls() public static function getApiUrls()
@ -81,7 +81,7 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
$status = true; $status = true;
$curl = null; $curl = null;
foreach ($messages as $i => $message) foreach ($messages as $i => $message)
{ {
// Authentication // Authentication
@ -89,7 +89,7 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
'Content-Type: multipart/form-data', 'Content-Type: multipart/form-data',
'secret: ' . base64_encode($this->_config['api_key'] . '&' . $this->_config['api_secret']), 'secret: ' . base64_encode($this->_config['api_key'] . '&' . $this->_config['api_secret']),
); );
// Sender and recipient // Sender and recipient
$data = array(); $data = array();
$data['from'] = str_replace('-', '', \Rhymix\Framework\Korea::formatPhoneNumber($message->from)); $data['from'] = str_replace('-', '', \Rhymix\Framework\Korea::formatPhoneNumber($message->from));
@ -100,26 +100,26 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
$data['to'] = array_first($data['to']); $data['to'] = array_first($data['to']);
} }
// Subject and content // Subject and content
if ($message->type === 'LMS' && $message->subject) if ($message->type === 'LMS' && $message->subject)
{ {
$data['title'] = $message->subject; $data['title'] = $message->subject;
} }
$data['text'] = $message->content; $data['text'] = $message->content;
// Image attachment // Image attachment
if ($message->image) if ($message->image)
{ {
$data['image'] = curl_file_create(realpath($message->image)); $data['image'] = curl_file_create(realpath($message->image));
} }
// Set delay // Set delay
if ($message->delay && $message->delay > time() + 900) if ($message->delay && $message->delay > time() + 900)
{ {
$data['date'] = gmdate('Y-m-d H:i:s', $message->delay + (3600 * 9)); $data['date'] = gmdate('Y-m-d H:i:s', $message->delay + (3600 * 9));
} }
// Set API URL // Set API URL
if (!empty($this->_config['api_url'])) if (!empty($this->_config['api_url']))
{ {
@ -129,7 +129,7 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
$api_url = self::LEGACY_API_URL; $api_url = self::LEGACY_API_URL;
} }
// We need to use curl because Filehandler::getRemoteResource() doesn't work with this API for some reason. // We need to use curl because Filehandler::getRemoteResource() doesn't work with this API for some reason.
if (!$curl) if (!$curl)
{ {
@ -143,7 +143,7 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
curl_setopt($curl, \CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, \CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($curl); $result = curl_exec($curl);
$err = curl_error($curl); $err = curl_error($curl);
// Check the result. // Check the result.
if ($err) if ($err)
{ {
@ -161,12 +161,12 @@ class iwinv extends Base implements \Rhymix\Framework\Drivers\SMSInterface
$status = false; $status = false;
} }
} }
if ($curl) if ($curl)
{ {
@curl_close($curl); @curl_close($curl);
} }
return $status; return $status;
} }
} }

View file

@ -23,29 +23,29 @@ class Ppurio extends Base implements \Rhymix\Framework\Drivers\SMSInterface
'mms_supported' => false, 'mms_supported' => false,
'delay_supported' => true, 'delay_supported' => true,
); );
/** /**
* Config keys used by this driver are stored here. * Config keys used by this driver are stored here.
*/ */
protected static $_required_config = array('api_user'); protected static $_required_config = array('api_user');
/** /**
* Check if the current SMS driver is supported on this server. * Check if the current SMS driver is supported on this server.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @return bool * @return bool
*/ */
public static function isSupported() public static function isSupported()
{ {
return true; return true;
} }
/** /**
* Send a message. * Send a message.
* *
* This method returns true on success and false on failure. * This method returns true on success and false on failure.
* *
* @param array $messages * @param array $messages
* @param object $original * @param object $original
* @return bool * @return bool
@ -59,26 +59,26 @@ class Ppurio extends Base implements \Rhymix\Framework\Drivers\SMSInterface
// Authentication and basic information // Authentication and basic information
$data = array(); $data = array();
$data['userid'] = $this->_config['api_user']; $data['userid'] = $this->_config['api_user'];
// Sender and recipient // Sender and recipient
$data['callback'] = preg_replace('/[^0-9]/', '', $message->from); $data['callback'] = preg_replace('/[^0-9]/', '', $message->from);
$data['phone'] = implode('|', array_map(function($num) { $data['phone'] = implode('|', array_map(function($num) {
return preg_replace('/[^0-9]/', '', $num); return preg_replace('/[^0-9]/', '', $num);
}, $message->to)); }, $message->to));
// Subject and content // Subject and content
if ($message->type === 'LMS' && $message->subject) if ($message->type === 'LMS' && $message->subject)
{ {
$data['subject'] = $message->subject; $data['subject'] = $message->subject;
} }
$data['msg'] = $message->content; $data['msg'] = $message->content;
// Set delay // Set delay
if ($message->delay && $message->delay > time() + 600) if ($message->delay && $message->delay > time() + 600)
{ {
$data['appdate'] = gmdate('YmdHis', $message->delay + (3600 * 9)); $data['appdate'] = gmdate('YmdHis', $message->delay + (3600 * 9));
} }
// Send! // Send!
$url = 'https://www.ppurio.com/api/send_utf8_json.php'; $url = 'https://www.ppurio.com/api/send_utf8_json.php';
$result = \FileHandler::getRemoteResource($url, $data, 5, 'POST'); $result = \FileHandler::getRemoteResource($url, $data, 5, 'POST');
@ -97,7 +97,7 @@ class Ppurio extends Base implements \Rhymix\Framework\Drivers\SMSInterface
} }
} }
} }
return $status; return $status;
} }
} }

View file

@ -8,7 +8,7 @@ namespace Rhymix\Framework\Drivers\SMS;
class SolAPI extends Base implements \Rhymix\Framework\Drivers\SMSInterface class SolAPI extends Base implements \Rhymix\Framework\Drivers\SMSInterface
{ {
const appId = 'PAOe9c8ftH8R'; const appId = 'PAOe9c8ftH8R';
/** /**
* API specifications. * API specifications.
*/ */
@ -115,7 +115,7 @@ class SolAPI extends Base implements \Rhymix\Framework\Drivers\SMSInterface
} }
$groupArray[] = $options; $groupArray[] = $options;
} }
if($groupMessage) if($groupMessage)
{ {
$jsonObject = new \stdClass(); $jsonObject = new \stdClass();
@ -156,7 +156,7 @@ class SolAPI extends Base implements \Rhymix\Framework\Drivers\SMSInterface
return true; return true;
} }
/** /**
* Create header string for http protocol * Create header string for http protocol
* @param $config * @param $config
@ -212,7 +212,7 @@ class SolAPI extends Base implements \Rhymix\Framework\Drivers\SMSInterface
private function request($method, $url, $data = false) private function request($method, $url, $data = false)
{ {
$url = 'https://api.solapi.com/' . $url; $url = 'https://api.solapi.com/' . $url;
if(!$data) if(!$data)
{ {
$data = null; $data = null;
@ -222,7 +222,7 @@ class SolAPI extends Base implements \Rhymix\Framework\Drivers\SMSInterface
$data = json_encode($data); $data = json_encode($data);
} }
$result = \FileHandler::getRemoteResource($url, $data, 3, $method, 'application/json', array('Authorization' => $this->getHeader())); $result = \FileHandler::getRemoteResource($url, $data, 3, $method, 'application/json', array('Authorization' => $this->getHeader()));
return $result; return $result;
} }
} }

View file

@ -11,10 +11,10 @@ class FileContentFilter
* Fileinfo instance cache * Fileinfo instance cache
*/ */
protected static $_finfo = null; protected static $_finfo = null;
/** /**
* Generic checker * Generic checker
* *
* @param string $file Actual path to the file to be checked * @param string $file Actual path to the file to be checked
* @param string $filename Filename hint for type detection * @param string $filename Filename hint for type detection
* @return bool * @return bool
@ -26,62 +26,62 @@ class FileContentFilter
{ {
return false; return false;
} }
// Return error if the file size is zero. // Return error if the file size is zero.
if (($filesize = filesize($file)) == 0) if (($filesize = filesize($file)) == 0)
{ {
return false; return false;
} }
// Get the extension and MIME type. // Get the extension and MIME type.
$ext = $filename ? strtolower(substr(strrchr($filename, '.'), 1)) : ''; $ext = $filename ? strtolower(substr(strrchr($filename, '.'), 1)) : '';
$mime_type = self::_getMimetype($file, true); $mime_type = self::_getMimetype($file, true);
// Check the first 4KB of the file for possible XML content. // Check the first 4KB of the file for possible XML content.
$fp = fopen($file, 'rb'); $fp = fopen($file, 'rb');
$first4kb = fread($fp, 4096); $first4kb = fread($fp, 4096);
$is_xml = preg_match('/<(?:\?xml|!DOCTYPE|html|head|body|meta|script|svg)\b/i', $first4kb); $is_xml = preg_match('/<(?:\?xml|!DOCTYPE|html|head|body|meta|script|svg)\b/i', $first4kb);
// Check SVG files. // Check SVG files.
if (($ext === 'svg' || $is_xml) && !self::_checkSVG($fp, 0, $filesize)) if (($ext === 'svg' || $is_xml) && !self::_checkSVG($fp, 0, $filesize))
{ {
fclose($fp); fclose($fp);
return false; return false;
} }
// Check other image files. // Check other image files.
if (in_array($ext, array('jpg', 'jpeg', 'png', 'gif')) && $mime_type !== false && $mime_type !== 'image') if (in_array($ext, array('jpg', 'jpeg', 'png', 'gif')) && $mime_type !== false && $mime_type !== 'image')
{ {
fclose($fp); fclose($fp);
return false; return false;
} }
// Check audio and video files. // Check audio and video files.
if (preg_match('/(wm[va]|mpe?g|avi|flv|mp[1-4]|as[fx]|wav|midi?|moo?v|qt|r[am]{1,2}|m4v)$/', $file) && $mime_type !== false && $mime_type !== 'audio' && $mime_type !== 'video') if (preg_match('/(wm[va]|mpe?g|avi|flv|mp[1-4]|as[fx]|wav|midi?|moo?v|qt|r[am]{1,2}|m4v)$/', $file) && $mime_type !== false && $mime_type !== 'audio' && $mime_type !== 'video')
{ {
fclose($fp); fclose($fp);
return false; return false;
} }
// Check XML files. // Check XML files.
if (($ext === 'xml' || $is_xml) && !self::_checkXML($fp, 0, $filesize)) if (($ext === 'xml' || $is_xml) && !self::_checkXML($fp, 0, $filesize))
{ {
fclose($fp); fclose($fp);
return false; return false;
} }
// Check HTML files. // Check HTML files.
if (($ext === 'html' || $ext === 'shtml' || $ext === 'xhtml' || $ext === 'phtml' || $is_xml) && !self::_checkHTML($fp, 0, $filesize)) if (($ext === 'html' || $ext === 'shtml' || $ext === 'xhtml' || $ext === 'phtml' || $is_xml) && !self::_checkHTML($fp, 0, $filesize))
{ {
fclose($fp); fclose($fp);
return false; return false;
} }
// Return true if everything is OK. // Return true if everything is OK.
fclose($fp); fclose($fp);
return true; return true;
} }
/** /**
* Check SVG file for XSS or SSRF vulnerabilities (#1088, #1089) * Check SVG file for XSS or SSRF vulnerabilities (#1088, #1089)
* *
@ -100,10 +100,10 @@ class FileContentFilter
{ {
return false; return false;
} }
return true; return true;
} }
/** /**
* Check XML file for external entity inclusion. * Check XML file for external entity inclusion.
* *
@ -118,10 +118,10 @@ class FileContentFilter
{ {
return false; return false;
} }
return true; return true;
} }
/** /**
* Check HTML file for PHP code, server-side includes, and other nastiness. * Check HTML file for PHP code, server-side includes, and other nastiness.
* *
@ -136,18 +136,18 @@ class FileContentFilter
{ {
return false; return false;
} }
return true; return true;
} }
/** /**
* Match a stream against a regular expression. * Match a stream against a regular expression.
* *
* This method is useful when dealing with large files, * This method is useful when dealing with large files,
* because we don't need to load the entire file into memory. * because we don't need to load the entire file into memory.
* We allow a generous overlap in case the matching string * We allow a generous overlap in case the matching string
* occurs across a block boundary. * occurs across a block boundary.
* *
* @param string $regexp * @param string $regexp
* @param resource $fp * @param resource $fp
* @param int $from * @param int $from
@ -169,10 +169,10 @@ class FileContentFilter
} }
return false; return false;
} }
/** /**
* Attempt to detect the MIME type of a file. * Attempt to detect the MIME type of a file.
* *
* @param string $file Path of file to check * @param string $file Path of file to check
* @param bool $trim_subtype Whether to remove the subtype from the return value * @param bool $trim_subtype Whether to remove the subtype from the return value
* @return string|false * @return string|false

View file

@ -9,7 +9,7 @@ class FilenameFilter
{ {
/** /**
* Remove illegal and dangerous characters from a filename. * Remove illegal and dangerous characters from a filename.
* *
* @param string $filename * @param string $filename
* @return string * @return string
*/ */
@ -19,27 +19,27 @@ class FilenameFilter
$illegal = array('\\', '/', '<', '>', '{', '}', ':', ';', '|', '"', '~', '`', '$', '%', '^', '*', '?'); $illegal = array('\\', '/', '<', '>', '{', '}', ':', ';', '|', '"', '~', '`', '$', '%', '^', '*', '?');
$replace = array('', '', '(', ')', '(', ')', '_', ',', '_', '', '_', '\'', '_', '_', '_', '', ''); $replace = array('', '', '(', ')', '(', ')', '_', ',', '_', '', '_', '\'', '_', '_', '_', '', '');
$filename = str_replace($illegal, $replace, $filename); $filename = str_replace($illegal, $replace, $filename);
// Remove control characters. // Remove control characters.
$filename = preg_replace('/([\\x00-\\x1f\\x7f\\xff]+)/u', '', $filename); $filename = preg_replace('/([\\x00-\\x1f\\x7f\\xff]+)/u', '', $filename);
// Standardize whitespace characters. // Standardize whitespace characters.
$filename = trim(preg_replace('/[\\pZ\\pC]+/u', ' ', $filename)); $filename = trim(preg_replace('/[\\pZ\\pC]+/u', ' ', $filename));
// Remove excess spaces and replacement characters. // Remove excess spaces and replacement characters.
$filename = trim($filename, ' .-_'); $filename = trim($filename, ' .-_');
$filename = preg_replace('/__+/', '_', $filename); $filename = preg_replace('/__+/', '_', $filename);
$filename = preg_replace('/\.\.+/', '.', $filename); $filename = preg_replace('/\.\.+/', '.', $filename);
// Clean up unnecessary encodings. // Clean up unnecessary encodings.
$filename = strtr($filename, array('&amp;' => '&')); $filename = strtr($filename, array('&amp;' => '&'));
// Change .php files to .phps to make them non-executable. // Change .php files to .phps to make them non-executable.
if (strtolower(substr($filename, strlen($filename) - 4)) === '.php') if (strtolower(substr($filename, strlen($filename) - 4)) === '.php')
{ {
$filename = substr($filename, 0, strlen($filename) - 4) . '.phps'; $filename = substr($filename, 0, strlen($filename) - 4) . '.phps';
} }
// Truncate filenames over 127 chars long, or extensions over 16 chars long. // Truncate filenames over 127 chars long, or extensions over 16 chars long.
if (mb_strlen($filename, 'UTF-8') > 127) if (mb_strlen($filename, 'UTF-8') > 127)
{ {
@ -47,13 +47,13 @@ class FilenameFilter
if (mb_strlen($extension, 'UTF-8') > 16) $extension = mb_substr($extension, 0, 16); if (mb_strlen($extension, 'UTF-8') > 16) $extension = mb_substr($extension, 0, 16);
$filename = mb_substr($filename, 0, 127 - mb_strlen($extension)) . $extension; $filename = mb_substr($filename, 0, 127 - mb_strlen($extension)) . $extension;
} }
return $filename; return $filename;
} }
/** /**
* Clean a path to remove ./, ../, trailing slashes, etc. * Clean a path to remove ./, ../, trailing slashes, etc.
* *
* @param string $path * @param string $path
* @return string * @return string
*/ */
@ -64,35 +64,35 @@ class FilenameFilter
{ {
$path = \RX_BASEDIR . $path; $path = \RX_BASEDIR . $path;
} }
// Convert backslashes to forward slashes. // Convert backslashes to forward slashes.
$path = str_replace('\\', '/', $path); $path = str_replace('\\', '/', $path);
// Remove querystrings and URL fragments. // Remove querystrings and URL fragments.
if (($querystring = strpbrk($path, '?#')) !== false) if (($querystring = strpbrk($path, '?#')) !== false)
{ {
$path = substr($path, 0, -1 * strlen($querystring)); $path = substr($path, 0, -1 * strlen($querystring));
} }
// Remove single dots, three or more dots, and duplicate slashes. // Remove single dots, three or more dots, and duplicate slashes.
$path = preg_replace(array( $path = preg_replace(array(
'@(?<!^|^http:|^https:)/{2,}@', '@(?<!^|^http:|^https:)/{2,}@',
'@/(?:(?:\.|\.{3,})/)+@', '@/(?:(?:\.|\.{3,})/)+@',
), '/', $path); ), '/', $path);
// Remove double dots and the preceding directory. // Remove double dots and the preceding directory.
while (preg_match('@/(?!\.\.)[^/]+/\.\.(?:/|$)@', $path, $matches)) while (preg_match('@/(?!\.\.)[^/]+/\.\.(?:/|$)@', $path, $matches))
{ {
$path = str_replace($matches[0], '/', $path); $path = str_replace($matches[0], '/', $path);
} }
// Trim trailing slashes. // Trim trailing slashes.
return rtrim($path, '/'); return rtrim($path, '/');
} }
/** /**
* Check if a file has an extension that would allow direct download. * Check if a file has an extension that would allow direct download.
* *
* @param string $filename * @param string $filename
* @param bool $include_multimedia (optional) * @param bool $include_multimedia (optional)
* @return bool * @return bool
@ -103,7 +103,7 @@ class FilenameFilter
$audios = 'mp3|wav|ogg|flac|aac'; $audios = 'mp3|wav|ogg|flac|aac';
$videos = 'mp4|webm|ogv'; $videos = 'mp4|webm|ogv';
$legacy = 'avi|as[fx]|flv|m4[av]|midi?|mkv|moo?v|mpe?g|qt|r[am]m?|wm[av]'; $legacy = 'avi|as[fx]|flv|m4[av]|midi?|mkv|moo?v|mpe?g|qt|r[am]m?|wm[av]';
if ($include_multimedia) if ($include_multimedia)
{ {
$pattern = sprintf('/\.(?:%s|%s|%s|%s)$/i', $images, $audios, $videos, $legacy); $pattern = sprintf('/\.(?:%s|%s|%s|%s)$/i', $images, $audios, $videos, $legacy);
@ -112,7 +112,7 @@ class FilenameFilter
{ {
$pattern = sprintf('/\.(?:%s)$/i', $images); $pattern = sprintf('/\.(?:%s)$/i', $images);
} }
return preg_match($pattern, $filename) ? true : false; return preg_match($pattern, $filename) ? true : false;
} }
} }

View file

@ -16,16 +16,16 @@ class HTMLFilter
* HTMLPurifier instances are cached here. * HTMLPurifier instances are cached here.
*/ */
protected static $_instances = array(); protected static $_instances = array();
/** /**
* Pre-processing and post-processing filters are stored here. * Pre-processing and post-processing filters are stored here.
*/ */
protected static $_preproc = array(); protected static $_preproc = array();
protected static $_postproc = array(); protected static $_postproc = array();
/** /**
* Prepend a pre-processing filter. * Prepend a pre-processing filter.
* *
* @param callable $callback * @param callable $callback
* @return void * @return void
*/ */
@ -33,10 +33,10 @@ class HTMLFilter
{ {
array_unshift(self::$_preproc, $callback); array_unshift(self::$_preproc, $callback);
} }
/** /**
* Append a pre-processing filter. * Append a pre-processing filter.
* *
* @param callable $callback * @param callable $callback
* @return void * @return void
*/ */
@ -44,10 +44,10 @@ class HTMLFilter
{ {
self::$_preproc[] = $callback; self::$_preproc[] = $callback;
} }
/** /**
* Prepend a post-processing filter. * Prepend a post-processing filter.
* *
* @param callable $callback * @param callable $callback
* @return void * @return void
*/ */
@ -55,10 +55,10 @@ class HTMLFilter
{ {
array_unshift(self::$_postproc, $callback); array_unshift(self::$_postproc, $callback);
} }
/** /**
* Append a post-processing filter. * Append a post-processing filter.
* *
* @param callable $callback * @param callable $callback
* @return void * @return void
*/ */
@ -66,10 +66,10 @@ class HTMLFilter
{ {
self::$_postproc[] = $callback; self::$_postproc[] = $callback;
} }
/** /**
* Filter HTML content to block XSS attacks. * Filter HTML content to block XSS attacks.
* *
* @param string $input * @param string $input
* @param array|bool $allow_classes (optional) * @param array|bool $allow_classes (optional)
* @param bool $allow_editor_components (optional) * @param bool $allow_editor_components (optional)
@ -82,7 +82,7 @@ class HTMLFilter
{ {
$input = $callback($input); $input = $callback($input);
} }
if ($allow_classes === true) if ($allow_classes === true)
{ {
$allowed_classes = null; $allowed_classes = null;
@ -97,36 +97,36 @@ class HTMLFilter
{ {
$allowed_classes = Config::get('mediafilter.classes') ?: array(); $allowed_classes = Config::get('mediafilter.classes') ?: array();
} }
if ($allow_widgets) if ($allow_widgets)
{ {
$allowed_classes[] = 'zbxe_widget_output'; $allowed_classes[] = 'zbxe_widget_output';
} }
} }
$input = self::_preprocess($input, $allow_editor_components, $allow_widgets); $input = self::_preprocess($input, $allow_editor_components, $allow_widgets);
$output = self::getHTMLPurifier($allowed_classes)->purify($input); $output = self::getHTMLPurifier($allowed_classes)->purify($input);
$output = self::_postprocess($output, $allow_editor_components, $allow_widgets); $output = self::_postprocess($output, $allow_editor_components, $allow_widgets);
foreach (self::$_postproc as $callback) foreach (self::$_postproc as $callback)
{ {
$output = $callback($output); $output = $callback($output);
} }
return $output; return $output;
} }
/** /**
* Convert relative URLs to absolute URLs in HTML content. * Convert relative URLs to absolute URLs in HTML content.
* *
* This is useful when sending content outside of the website, * This is useful when sending content outside of the website,
* such as e-mail and RSS, where relative URLs might not mean the same. * such as e-mail and RSS, where relative URLs might not mean the same.
* *
* This method also removes attributes that don't mean anything * This method also removes attributes that don't mean anything
* when sent outside of the website, such as editor component names. * when sent outside of the website, such as editor component names.
* *
* This method DOES NOT check HTML content for XSS or other attacks. * This method DOES NOT check HTML content for XSS or other attacks.
* *
* @param string $content * @param string $content
* @return string * @return string
*/ */
@ -146,10 +146,10 @@ class HTMLFilter
return preg_replace($patterns, $replacements, $match[0]); return preg_replace($patterns, $replacements, $match[0]);
}, $content); }, $content);
} }
/** /**
* Get an instance of HTMLPurifier. * Get an instance of HTMLPurifier.
* *
* @param array|null $allowed_classes (optional) * @param array|null $allowed_classes (optional)
* @return object * @return object
*/ */
@ -162,13 +162,13 @@ class HTMLFilter
sort($allowed_classes); sort($allowed_classes);
} }
$key = sha1(serialize($allowed_classes)); $key = sha1(serialize($allowed_classes));
// Create an instance with reasonable defaults. // Create an instance with reasonable defaults.
if (!isset(self::$_instances[$key])) if (!isset(self::$_instances[$key]))
{ {
// Get the default configuration. // Get the default configuration.
$config = \HTMLPurifier_Config::createDefault(); $config = \HTMLPurifier_Config::createDefault();
// Customize the default configuration. // Customize the default configuration.
$config->set('Attr.AllowedClasses', $allowed_classes); $config->set('Attr.AllowedClasses', $allowed_classes);
$config->set('Attr.AllowedFrameTargets', array('_blank', '_self')); $config->set('Attr.AllowedFrameTargets', array('_blank', '_self'));
@ -188,42 +188,42 @@ class HTMLFilter
$config->set('Output.FlashCompat', true); $config->set('Output.FlashCompat', true);
$config->set('Output.Newline', "\n"); $config->set('Output.Newline', "\n");
$config->set('URI.MakeAbsolute', false); $config->set('URI.MakeAbsolute', false);
// Allow embedding of external multimedia content. // Allow embedding of external multimedia content.
$config->set('HTML.SafeEmbed', true); $config->set('HTML.SafeEmbed', true);
$config->set('HTML.SafeIframe', true); $config->set('HTML.SafeIframe', true);
$config->set('HTML.SafeObject', true); $config->set('HTML.SafeObject', true);
$config->set('URI.SafeIframeRegexp', MediaFilter::getWhitelistRegex()); $config->set('URI.SafeIframeRegexp', MediaFilter::getWhitelistRegex());
// Set the serializer path. // Set the serializer path.
$config->set('Cache.SerializerPath', \RX_BASEDIR . 'files/cache/htmlpurifier'); $config->set('Cache.SerializerPath', \RX_BASEDIR . 'files/cache/htmlpurifier');
Storage::createDirectory(\RX_BASEDIR . 'files/cache/htmlpurifier'); Storage::createDirectory(\RX_BASEDIR . 'files/cache/htmlpurifier');
// Modify the HTML definition to support editor components and widgets. // Modify the HTML definition to support editor components and widgets.
$def = $config->getHTMLDefinition(true); $def = $config->getHTMLDefinition(true);
$def->addAttribute('img', 'editor_component', 'Text'); $def->addAttribute('img', 'editor_component', 'Text');
$def->addAttribute('div', 'editor_component', 'Text'); $def->addAttribute('div', 'editor_component', 'Text');
$def->addAttribute('img', 'rx_encoded_properties', 'Text'); $def->addAttribute('img', 'rx_encoded_properties', 'Text');
$def->addAttribute('div', 'rx_encoded_properties', 'Text'); $def->addAttribute('div', 'rx_encoded_properties', 'Text');
// Support HTML5 and CSS3. // Support HTML5 and CSS3.
self::_supportHTML5($config); self::_supportHTML5($config);
self::_supportCSS3($config); self::_supportCSS3($config);
// Cache our instance of HTMLPurifier. // Cache our instance of HTMLPurifier.
self::$_instances[$key] = new \HTMLPurifier($config); self::$_instances[$key] = new \HTMLPurifier($config);
} }
// Return the cached instance. // Return the cached instance.
return self::$_instances[$key]; return self::$_instances[$key];
} }
/** /**
* Patch HTMLPurifier to support some HTML5 tags and attributes. * Patch HTMLPurifier to support some HTML5 tags and attributes.
* *
* These changes are based on https://github.com/xemlock/htmlpurifier-html5 * These changes are based on https://github.com/xemlock/htmlpurifier-html5
* but modified to support even more tags and attributes. * but modified to support even more tags and attributes.
* *
* @param object $config * @param object $config
* @return void * @return void
*/ */
@ -231,7 +231,7 @@ class HTMLFilter
{ {
// Get the HTML definition. // Get the HTML definition.
$def = $config->getHTMLDefinition(true); $def = $config->getHTMLDefinition(true);
// Add various block-level tags. // Add various block-level tags.
$def->addElement('header', 'Block', 'Flow', 'Common'); $def->addElement('header', 'Block', 'Flow', 'Common');
$def->addElement('footer', 'Block', 'Flow', 'Common'); $def->addElement('footer', 'Block', 'Flow', 'Common');
@ -240,26 +240,26 @@ class HTMLFilter
$def->addElement('section', 'Block', 'Flow', 'Common'); $def->addElement('section', 'Block', 'Flow', 'Common');
$def->addElement('article', 'Block', 'Flow', 'Common'); $def->addElement('article', 'Block', 'Flow', 'Common');
$def->addElement('aside', 'Block', 'Flow', 'Common'); $def->addElement('aside', 'Block', 'Flow', 'Common');
// Add various inline tags. // Add various inline tags.
$def->addElement('s', 'Inline', 'Inline', 'Common'); $def->addElement('s', 'Inline', 'Inline', 'Common');
$def->addElement('sub', 'Inline', 'Inline', 'Common'); $def->addElement('sub', 'Inline', 'Inline', 'Common');
$def->addElement('sup', 'Inline', 'Inline', 'Common'); $def->addElement('sup', 'Inline', 'Inline', 'Common');
$def->addElement('mark', 'Inline', 'Inline', 'Common'); $def->addElement('mark', 'Inline', 'Inline', 'Common');
$def->addElement('wbr', 'Inline', 'Empty', 'Core'); $def->addElement('wbr', 'Inline', 'Empty', 'Core');
// Support figures. // Support figures.
$def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common'); $def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common');
$def->addElement('figcaption', 'Inline', 'Flow', 'Common'); $def->addElement('figcaption', 'Inline', 'Flow', 'Common');
// Support insertions and deletions. // Support insertions and deletions.
$def->addElement('ins', 'Block', 'Flow', 'Common', array('cite' => 'URI', 'datetime' => 'Text')); $def->addElement('ins', 'Block', 'Flow', 'Common', array('cite' => 'URI', 'datetime' => 'Text'));
$def->addElement('del', 'Block', 'Flow', 'Common', array('cite' => 'URI', 'datetime' => 'Text')); $def->addElement('del', 'Block', 'Flow', 'Common', array('cite' => 'URI', 'datetime' => 'Text'));
// Support the <time> tag. // Support the <time> tag.
$time = $def->addElement('time', 'Inline', 'Inline', 'Common', array('datetime' => 'Text', 'pubdate' => 'Bool')); $time = $def->addElement('time', 'Inline', 'Inline', 'Common', array('datetime' => 'Text', 'pubdate' => 'Bool'));
$time->excludes = array('time' => true); $time->excludes = array('time' => true);
// Suppport <audio> and <video> tags. // Suppport <audio> and <video> tags.
$def->addElement('audio', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array( $def->addElement('audio', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', array(
'src' => 'URI', 'src' => 'URI',
@ -296,23 +296,23 @@ class HTMLFilter
'kind' => 'Enum#captions,chapters,descriptions,metadata,subtitles', 'kind' => 'Enum#captions,chapters,descriptions,metadata,subtitles',
'default' => 'Bool', 'default' => 'Bool',
)); ));
// Support additional properties. // Support additional properties.
$def->addAttribute('i', 'aria-hidden', 'Text'); $def->addAttribute('i', 'aria-hidden', 'Text');
$def->addAttribute('img', 'srcset', 'Text'); $def->addAttribute('img', 'srcset', 'Text');
$def->addAttribute('img', 'data-file-srl', 'Number'); $def->addAttribute('img', 'data-file-srl', 'Number');
$def->addAttribute('iframe', 'allowfullscreen', 'Bool'); $def->addAttribute('iframe', 'allowfullscreen', 'Bool');
// Support contenteditable="false" (#1710) // Support contenteditable="false" (#1710)
$def->addAttribute('div', 'contenteditable', 'Enum#false'); $def->addAttribute('div', 'contenteditable', 'Enum#false');
} }
/** /**
* Patch HTMLPurifier to support more CSS2 and some CSS3 properties. * Patch HTMLPurifier to support more CSS2 and some CSS3 properties.
* *
* These changes are based on: * These changes are based on:
* - https://github.com/mattiaswelander/htmlpurifier * - https://github.com/mattiaswelander/htmlpurifier
* *
* @param object $config * @param object $config
* @return void * @return void
*/ */
@ -320,14 +320,14 @@ class HTMLFilter
{ {
// Initialize $info. // Initialize $info.
$info = array(); $info = array();
// min-width, max-width, etc. // min-width, max-width, etc.
$info['min-width'] = $info['max-width'] = $info['min-height'] = $info['min-width'] = $info['max-width'] = $info['min-height'] =
$info['max-height'] = new \HTMLPurifier_AttrDef_CSS_Composite(array( $info['max-height'] = new \HTMLPurifier_AttrDef_CSS_Composite(array(
new \HTMLPurifier_AttrDef_CSS_Length(0), new \HTMLPurifier_AttrDef_CSS_Length(0),
new \HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')), new \HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')),
)); ));
// border-radius, etc. // border-radius, etc.
$border_radius = $info['border-top-left-radius'] = $border_radius = $info['border-top-left-radius'] =
$info['border-top-right-radius'] = $info['border-bottom-left-radius'] = $info['border-top-right-radius'] = $info['border-bottom-left-radius'] =
@ -337,7 +337,7 @@ class HTMLFilter
new \HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')), new \HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')),
)); ));
$info['border-radius'] = new \HTMLPurifier_AttrDef_CSS_Multiple($border_radius); $info['border-radius'] = new \HTMLPurifier_AttrDef_CSS_Multiple($border_radius);
// word-break word-wrap, etc. // word-break word-wrap, etc.
$info['word-break'] = new \HTMLPurifier_AttrDef_Enum(array( $info['word-break'] = new \HTMLPurifier_AttrDef_Enum(array(
'normal', 'break-all', 'keep-all', 'initial', 'inherit', 'normal', 'break-all', 'keep-all', 'initial', 'inherit',
@ -348,7 +348,7 @@ class HTMLFilter
$info['text-overflow'] = new \HTMLPurifier_AttrDef_CSS_Composite(array( $info['text-overflow'] = new \HTMLPurifier_AttrDef_CSS_Composite(array(
new \HTMLPurifier_AttrDef_Enum(array('clip', 'ellipsis', 'initial', 'inherit')), new \HTMLPurifier_AttrDef_Enum(array('clip', 'ellipsis', 'initial', 'inherit')),
)); ));
// text-shadow // text-shadow
$info['text-shadow'] = new \HTMLPurifier_AttrDef_CSS_Composite(array( $info['text-shadow'] = new \HTMLPurifier_AttrDef_CSS_Composite(array(
new \HTMLPurifier_AttrDef_CSS_Multiple(new \HTMLPurifier_AttrDef_CSS_Composite(array( new \HTMLPurifier_AttrDef_CSS_Multiple(new \HTMLPurifier_AttrDef_CSS_Composite(array(
@ -357,7 +357,7 @@ class HTMLFilter
))), ))),
new \HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')), new \HTMLPurifier_AttrDef_Enum(array('none', 'initial', 'inherit')),
)); ));
// box-shadow and box-sizing // box-shadow and box-sizing
$info['box-shadow'] = new \HTMLPurifier_AttrDef_CSS_Multiple(new \HTMLPurifier_AttrDef_CSS_Composite(array( $info['box-shadow'] = new \HTMLPurifier_AttrDef_CSS_Multiple(new \HTMLPurifier_AttrDef_CSS_Composite(array(
new \HTMLPurifier_AttrDef_CSS_Length(), new \HTMLPurifier_AttrDef_CSS_Length(),
@ -368,7 +368,7 @@ class HTMLFilter
$info['box-sizing'] = new \HTMLPurifier_AttrDef_Enum(array( $info['box-sizing'] = new \HTMLPurifier_AttrDef_Enum(array(
'content-box', 'border-box', 'initial', 'inherit', 'content-box', 'border-box', 'initial', 'inherit',
)); ));
// outline // outline
$info['outline-color'] = new \HTMLPurifier_AttrDef_CSS_Composite(array( $info['outline-color'] = new \HTMLPurifier_AttrDef_CSS_Composite(array(
new \HTMLPurifier_AttrDef_CSS_Color(), new \HTMLPurifier_AttrDef_CSS_Color(),
@ -389,7 +389,7 @@ class HTMLFilter
$info['outline-color'], $info['outline-style'], $info['outline-width'], $info['outline-color'], $info['outline-style'], $info['outline-width'],
new \HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')), new \HTMLPurifier_AttrDef_Enum(array('initial', 'inherit')),
))); )));
// flexbox // flexbox
$info['display'] = new \HTMLPurifier_AttrDef_Enum(array( $info['display'] = new \HTMLPurifier_AttrDef_Enum(array(
'block', 'flex', '-webkit-flex', 'inline', 'inline-block', 'inline-flex', '-webkit-inline-flex', 'inline-table', 'block', 'flex', '-webkit-flex', 'inline', 'inline-block', 'inline-flex', '-webkit-inline-flex', 'inline-table',
@ -424,7 +424,7 @@ class HTMLFilter
$info['flex-grow'], $info['flex-shrink'], $info['flex-basis'], $info['flex-grow'], $info['flex-shrink'], $info['flex-basis'],
new \HTMLPurifier_AttrDef_Enum(array('auto', 'none', 'initial', 'inherit')), new \HTMLPurifier_AttrDef_Enum(array('auto', 'none', 'initial', 'inherit')),
))); )));
// misc // misc
$info['caption-side'] = new \HTMLPurifier_AttrDef_Enum(array( $info['caption-side'] = new \HTMLPurifier_AttrDef_Enum(array(
'top', 'bottom', 'initial', 'inherit', 'top', 'bottom', 'initial', 'inherit',
@ -449,7 +449,7 @@ class HTMLFilter
$info['object-fit'] = new \HTMLPurifier_AttrDef_Enum(array( $info['object-fit'] = new \HTMLPurifier_AttrDef_Enum(array(
'contain', 'cover', 'fill', 'none', 'scale-down', 'initial', 'inherit', 'contain', 'cover', 'fill', 'none', 'scale-down', 'initial', 'inherit',
)); ));
// Wrap all new properties with a decorator that handles !important. // Wrap all new properties with a decorator that handles !important.
$allow_important = $config->get('CSS.AllowImportant'); $allow_important = $config->get('CSS.AllowImportant');
$css_definition = $config->getCSSDefinition(); $css_definition = $config->getCSSDefinition();
@ -458,10 +458,10 @@ class HTMLFilter
$css_definition->info[$key] = new \HTMLPurifier_AttrDef_CSS_ImportantDecorator($val, $allow_important); $css_definition->info[$key] = new \HTMLPurifier_AttrDef_CSS_ImportantDecorator($val, $allow_important);
} }
} }
/** /**
* Rhymix-specific preprocessing method. * Rhymix-specific preprocessing method.
* *
* @param string $content * @param string $content
* @param bool $allow_editor_components (optional) * @param bool $allow_editor_components (optional)
* @param bool $allow_widgets (optional) * @param bool $allow_widgets (optional)
@ -476,10 +476,10 @@ class HTMLFilter
} }
return $content; return $content;
} }
/** /**
* Rhymix-specific postprocessing method. * Rhymix-specific postprocessing method.
* *
* @param string $content * @param string $content
* @param bool $allow_editor_components (optional) * @param bool $allow_editor_components (optional)
* @param bool $allow_widgets (optional) * @param bool $allow_widgets (optional)
@ -490,12 +490,12 @@ class HTMLFilter
// Define acts to allow and deny. // Define acts to allow and deny.
$allow_acts = array('procFileDownload'); $allow_acts = array('procFileDownload');
$deny_acts = array('dispMemberLogout', 'dispLayoutPreview'); $deny_acts = array('dispMemberLogout', 'dispLayoutPreview');
// Remove tags not supported in Rhymix. Some of these may also have been removed by HTMLPurifier. // Remove tags not supported in Rhymix. Some of these may also have been removed by HTMLPurifier.
$content = preg_replace_callback('!</?(?:html|body|head|title|meta|base|link|script|style|applet)\b[^>]*>!i', function($matches) { $content = preg_replace_callback('!</?(?:html|body|head|title|meta|base|link|script|style|applet)\b[^>]*>!i', function($matches) {
return htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8'); return htmlspecialchars($matches[0], ENT_QUOTES, 'UTF-8');
}, $content); }, $content);
// Remove object and embed URLs that are not allowed. // Remove object and embed URLs that are not allowed.
$whitelist = MediaFilter::getWhitelistRegex(); $whitelist = MediaFilter::getWhitelistRegex();
$content = preg_replace_callback('!<(object|embed|param|audio|video|source|track)([^>]+)>!i', function($matches) use($whitelist) { $content = preg_replace_callback('!<(object|embed|param|audio|video|source|track)([^>]+)>!i', function($matches) use($whitelist) {
@ -511,7 +511,7 @@ class HTMLFilter
return $attr[0]; return $attr[0];
}, $matches[0]); }, $matches[0]);
}, $content); }, $content);
// Remove link URLs that may be CSRF attempts. // Remove link URLs that may be CSRF attempts.
$content = preg_replace_callback('!\b(src|href|data|value)="([^"]+)"!i', function($matches) use($allow_acts, $deny_acts) { $content = preg_replace_callback('!\b(src|href|data|value)="([^"]+)"!i', function($matches) use($allow_acts, $deny_acts) {
$url = preg_replace('!\s+!', '', htmlspecialchars_decode(rawurldecode($matches[2]))); $url = preg_replace('!\s+!', '', htmlspecialchars_decode(rawurldecode($matches[2])));
@ -525,15 +525,15 @@ class HTMLFilter
} }
return $matches[0]; return $matches[0];
}, $content); }, $content);
// Restore widget and editor component properties. // Restore widget and editor component properties.
$content = self::_decodeWidgetsAndEditorComponents($content, $allow_editor_components, $allow_widgets); $content = self::_decodeWidgetsAndEditorComponents($content, $allow_editor_components, $allow_widgets);
return $content; return $content;
} }
/** /**
* Encode widgets and editor components before processing. * Encode widgets and editor components before processing.
* *
* @param string $content * @param string $content
* @param bool $allow_editor_components (optional) * @param bool $allow_editor_components (optional)
* @param bool $allow_widgets (optional) * @param bool $allow_widgets (optional)
@ -554,7 +554,7 @@ class HTMLFilter
{ {
return $content; return $content;
} }
return preg_replace_callback('!<(div|img)([^>]*)(' . implode('|', $regexp) . ')([^>]*)>!i', function($match) { return preg_replace_callback('!<(div|img)([^>]*)(' . implode('|', $regexp) . ')([^>]*)>!i', function($match) {
$tag = strtolower($match[1]); $tag = strtolower($match[1]);
$attrs = array(); $attrs = array();
@ -585,10 +585,10 @@ class HTMLFilter
return substr($html, 0, 4) . ' rx_encoded_properties="' . $encoded_properties . '"' . substr($html, 4); return substr($html, 0, 4) . ' rx_encoded_properties="' . $encoded_properties . '"' . substr($html, 4);
}, $content); }, $content);
} }
/** /**
* Decode widgets and editor components after processing. * Decode widgets and editor components after processing.
* *
* @param string $content * @param string $content
* @param bool $allow_editor_components (optional) * @param bool $allow_editor_components (optional)
* @param bool $allow_widgets (optional) * @param bool $allow_widgets (optional)
@ -608,7 +608,7 @@ class HTMLFilter
{ {
return $content; return $content;
} }
return preg_replace_callback('!<(div|img)([^>]*)(\srx_encoded_properties="([^"]+)")!i', function($match) { return preg_replace_callback('!<(div|img)([^>]*)(\srx_encoded_properties="([^"]+)")!i', function($match) {
$attrs = array(); $attrs = array();
list($encoded_properties, $signature) = explode(':', $match[4]); list($encoded_properties, $signature) = explode(':', $match[4]);

View file

@ -9,7 +9,7 @@ class IpFilter
{ {
/** /**
* Check whether the given IP address belongs to a range. * Check whether the given IP address belongs to a range.
* *
* @param string $ip * @param string $ip
* @param string $range * @param string $range
* @return bool * @return bool
@ -27,7 +27,7 @@ class IpFilter
$ip = strtolower($ip); $ip = strtolower($ip);
$ip_type = 6; $ip_type = 6;
} }
// Determine the type of the range. // Determine the type of the range.
if ($ip_type === 6 && strpos($range, ':') !== false) if ($ip_type === 6 && strpos($range, ':') !== false)
{ {
@ -49,7 +49,7 @@ class IpFilter
{ {
$range_type = 'unknown'; $range_type = 'unknown';
} }
// Check! // Check!
switch ($range_type) switch ($range_type)
{ {
@ -65,10 +65,10 @@ class IpFilter
return false; return false;
} }
} }
/** /**
* Check whether the given IP address belongs to a set of ranges. * Check whether the given IP address belongs to a set of ranges.
* *
* @param string $ip * @param string $ip
* @param array $ranges * @param array $ranges
* @return bool * @return bool
@ -84,10 +84,10 @@ class IpFilter
} }
return false; return false;
} }
/** /**
* Check whether a range definition is valid. * Check whether a range definition is valid.
* *
* @param string $range * @param string $range
* @return bool * @return bool
*/ */
@ -99,7 +99,7 @@ class IpFilter
'/^\d+\.\d+\.\d+\.\d+-\d+\.\d+\.\d+\.\d+$/', '/^\d+\.\d+\.\d+\.\d+-\d+\.\d+\.\d+\.\d+$/',
'/^[0-9a-f:]+(\/\d+)?$/i', '/^[0-9a-f:]+(\/\d+)?$/i',
); );
foreach ($regexes as $regex) foreach ($regexes as $regex)
{ {
if (preg_match($regex, $range)) if (preg_match($regex, $range))
@ -109,10 +109,10 @@ class IpFilter
} }
return false; return false;
} }
/** /**
* Check whether a set of range definitions is valid. * Check whether a set of range definitions is valid.
* *
* @param array $ranges * @param array $ranges
* @return bool * @return bool
*/ */
@ -127,10 +127,10 @@ class IpFilter
} }
return true; return true;
} }
/** /**
* Get real IP from CloudFlare headers. * Get real IP from CloudFlare headers.
* *
* @return string|false * @return string|false
*/ */
public static function getCloudFlareRealIP() public static function getCloudFlareRealIP()
@ -139,7 +139,7 @@ class IpFilter
{ {
return false; return false;
} }
$cloudflare_ranges = (include \RX_BASEDIR . 'common/defaults/cloudflare.php'); $cloudflare_ranges = (include \RX_BASEDIR . 'common/defaults/cloudflare.php');
foreach ($cloudflare_ranges as $cloudflare_range) foreach ($cloudflare_ranges as $cloudflare_range)
{ {
@ -150,12 +150,12 @@ class IpFilter
} }
return false; return false;
} }
/** /**
* Check whether the given IPv4 address belongs to a IPv4 CIDR range with mask. * Check whether the given IPv4 address belongs to a IPv4 CIDR range with mask.
* *
* Example: 172.16.0.0/12 * Example: 172.16.0.0/12
* *
* @param string $ip * @param string $ip
* @param string $range * @param string $range
* @return bool * @return bool
@ -168,12 +168,12 @@ class IpFilter
$range = ip2long($range) & (0xffffffff << (32 - $mask)); $range = ip2long($range) & (0xffffffff << (32 - $mask));
return $ip === $range; return $ip === $range;
} }
/** /**
* Check whether the given IPv4 address belongs to a IPv6 CIDR range with mask. * Check whether the given IPv4 address belongs to a IPv6 CIDR range with mask.
* *
* Example: 2400:cb00::/32 * Example: 2400:cb00::/32
* *
* @param string $ip * @param string $ip
* @param string $range * @param string $range
* @return bool * @return bool
@ -193,12 +193,12 @@ class IpFilter
return false; return false;
} }
} }
/** /**
* Check whether the given IPv4 address belongs to a IPv4 wildcard range. * Check whether the given IPv4 address belongs to a IPv4 wildcard range.
* *
* Example: 192.168.*.* * Example: 192.168.*.*
* *
* @param string $ip * @param string $ip
* @param string $range * @param string $range
* @return bool * @return bool
@ -213,12 +213,12 @@ class IpFilter
$range = str_replace(array('.', '*'), array('\\.', '\\d+'), trim($range)); $range = str_replace(array('.', '*'), array('\\.', '\\d+'), trim($range));
return preg_match("/^$range$/", $ip) ? true : false; return preg_match("/^$range$/", $ip) ? true : false;
} }
/** /**
* Check whether the given IPv4 address belongs to a IPv4 hyphen range. * Check whether the given IPv4 address belongs to a IPv4 hyphen range.
* *
* Example: 192.168.0.0-192.168.255.255 * Example: 192.168.0.0-192.168.255.255
* *
* @param string $ip * @param string $ip
* @param string $range * @param string $range
* @return bool * @return bool

View file

@ -13,10 +13,10 @@ class MediaFilter
* Whitelists are cached here. * Whitelists are cached here.
*/ */
protected static $_whitelist = []; protected static $_whitelist = [];
/** /**
* Add a prefix to the iframe whitelist. * Add a prefix to the iframe whitelist.
* *
* @param string $prefix * @param string $prefix
* @parsm bool $permanently * @parsm bool $permanently
* @return void * @return void
@ -27,13 +27,13 @@ class MediaFilter
{ {
self::_loadWhitelists(); self::_loadWhitelists();
} }
$prefix = self::formatPrefix($prefix); $prefix = self::formatPrefix($prefix);
if (!in_array($prefix, self::$_whitelist)) if (!in_array($prefix, self::$_whitelist))
{ {
self::$_whitelist[] = $prefix; self::$_whitelist[] = $prefix;
natcasesort(self::$_whitelist); natcasesort(self::$_whitelist);
if ($permanently) if ($permanently)
{ {
Config::set('mediafilter.whitelist', self::$_whitelist); Config::set('mediafilter.whitelist', self::$_whitelist);
@ -43,30 +43,30 @@ class MediaFilter
} }
} }
} }
/** /**
* Add a prefix to the object whitelist. * Add a prefix to the object whitelist.
* *
* @deprecated * @deprecated
*/ */
public static function addIframePrefix($prefix, $permanently = false) public static function addIframePrefix($prefix, $permanently = false)
{ {
self::addPrefix($prefix, $permanently); self::addPrefix($prefix, $permanently);
} }
/** /**
* Add a prefix to the object whitelist. * Add a prefix to the object whitelist.
* *
* @deprecated * @deprecated
*/ */
public static function addObjectPrefix() public static function addObjectPrefix()
{ {
} }
/** /**
* Format a prefix for standardization. * Format a prefix for standardization.
* *
* @param string $prefix * @param string $prefix
* @return string * @return string
*/ */
@ -79,10 +79,10 @@ class MediaFilter
} }
return $prefix; return $prefix;
} }
/** /**
* Get the iframe whitelist. * Get the iframe whitelist.
* *
* @return array * @return array
*/ */
public static function getWhitelist() public static function getWhitelist()
@ -93,10 +93,10 @@ class MediaFilter
} }
return self::$_whitelist; return self::$_whitelist;
} }
/** /**
* Get the iframe whitelist as a regular expression. * Get the iframe whitelist as a regular expression.
* *
* @return string * @return string
*/ */
public static function getWhitelistRegex() public static function getWhitelistRegex()
@ -112,10 +112,10 @@ class MediaFilter
} }
return '%^(?:https?:)?//(' . implode('|', $result) . ')%'; return '%^(?:https?:)?//(' . implode('|', $result) . ')%';
} }
/** /**
* Check if a URL matches the iframe whitelist. * Check if a URL matches the iframe whitelist.
* *
* @param string $url * @param string $url
* @return bool * @return bool
*/ */
@ -123,10 +123,10 @@ class MediaFilter
{ {
return preg_match(self::getWhitelistRegex(), $url) ? true : false; return preg_match(self::getWhitelistRegex(), $url) ? true : false;
} }
/** /**
* Remove embedded media from HTML content. * Remove embedded media from HTML content.
* *
* @param string $input * @param string $input
* @param string $replacement * @param string $replacement
* @return string * @return string
@ -138,10 +138,10 @@ class MediaFilter
$input = preg_replace('!<img[^>]*editor_component="multimedia_link"[^>]*>(.*?</img>)?!is', $replacement, $input); $input = preg_replace('!<img[^>]*editor_component="multimedia_link"[^>]*>(.*?</img>)?!is', $replacement, $input);
return $input; return $input;
} }
/** /**
* Load whitelists. * Load whitelists.
* *
* @param array $custom_whitelist * @param array $custom_whitelist
* @return void * @return void
*/ */
@ -149,7 +149,7 @@ class MediaFilter
{ {
$default_whitelist = (include \RX_BASEDIR . 'common/defaults/whitelist.php'); $default_whitelist = (include \RX_BASEDIR . 'common/defaults/whitelist.php');
self::$_whitelist = []; self::$_whitelist = [];
if($custom_whitelist) if($custom_whitelist)
{ {
if(!is_array($custom_whitelist) || !isset($custom_whitelist['iframe']) || !isset($custom_whitelist['object'])) if(!is_array($custom_whitelist) || !isset($custom_whitelist['iframe']) || !isset($custom_whitelist['object']))
@ -199,19 +199,19 @@ class MediaFilter
} }
} }
} }
self::$_whitelist = array_unique(self::$_whitelist); self::$_whitelist = array_unique(self::$_whitelist);
natcasesort(self::$_whitelist); natcasesort(self::$_whitelist);
} }
/** /**
* ========================== DEPRECATED METHODS ========================== * ========================== DEPRECATED METHODS ==========================
* ============== KEPT FOR COMPATIBILITY WITH OLDER VERSIONS ============== * ============== KEPT FOR COMPATIBILITY WITH OLDER VERSIONS ==============
*/ */
/** /**
* Get the iframe whitelist. * Get the iframe whitelist.
* *
* @deprecated * @deprecated
* @return array * @return array
*/ */
@ -219,10 +219,10 @@ class MediaFilter
{ {
return self::getWhitelist(); return self::getWhitelist();
} }
/** /**
* Get the iframe whitelist as a regular expression. * Get the iframe whitelist as a regular expression.
* *
* @deprecated * @deprecated
* @return string * @return string
*/ */
@ -230,10 +230,10 @@ class MediaFilter
{ {
return self::getWhitelistRegex(); return self::getWhitelistRegex();
} }
/** /**
* Check if a URL matches the iframe whitelist. * Check if a URL matches the iframe whitelist.
* *
* @deprecated * @deprecated
* @param string $url * @param string $url
* @return bool * @return bool
@ -242,10 +242,10 @@ class MediaFilter
{ {
return self::matchWhitelist($url); return self::matchWhitelist($url);
} }
/** /**
* Get the object whitelist. * Get the object whitelist.
* *
* @deprecated * @deprecated
* @return array * @return array
*/ */
@ -253,10 +253,10 @@ class MediaFilter
{ {
return self::getWhitelist(); return self::getWhitelist();
} }
/** /**
* Get the object whitelist as a regular expression. * Get the object whitelist as a regular expression.
* *
* @deprecated * @deprecated
* @return string * @return string
*/ */
@ -264,10 +264,10 @@ class MediaFilter
{ {
return self::getWhitelistRegex(); return self::getWhitelistRegex();
} }
/** /**
* Check if a URL matches the iframe whitelist. * Check if a URL matches the iframe whitelist.
* *
* @deprecated * @deprecated
* @param string $url * @param string $url
* @return bool * @return bool

View file

@ -14,10 +14,10 @@ class ConfigHelper
* Cache plugin configuration during consolidation. * Cache plugin configuration during consolidation.
*/ */
protected static $_config_cache = array(); protected static $_config_cache = array();
/** /**
* Consolidate configuration from multiple sources. * Consolidate configuration from multiple sources.
* *
* @param array $format * @param array $format
* @return array * @return array
*/ */
@ -25,19 +25,19 @@ class ConfigHelper
{ {
self::$_config_cache = array(); self::$_config_cache = array();
$result = array(); $result = array();
foreach ($format as $key => $value) foreach ($format as $key => $value)
{ {
$result[$key] = self::_parseConfigValue((array)$value); $result[$key] = self::_parseConfigValue((array)$value);
} }
self::$_config_cache = array(); self::$_config_cache = array();
return $result; return $result;
} }
/** /**
* Parse and get a configuration value. * Parse and get a configuration value.
* *
* @param array $value * @param array $value
* @return mixed * @return mixed
*/ */
@ -45,7 +45,7 @@ class ConfigHelper
{ {
$filters = array(); $filters = array();
$result = null; $result = null;
foreach ($value as $option) foreach ($value as $option)
{ {
$option = array_map('trim', explode(':', $option, 2)); $option = array_map('trim', explode(':', $option, 2));
@ -90,12 +90,12 @@ class ConfigHelper
$result = $temp; $result = $temp;
} }
} }
foreach ($filters as $filter) foreach ($filters as $filter)
{ {
$result = $filter($result); $result = $filter($result);
} }
return $result; return $result;
} }
} }

View file

@ -8,7 +8,7 @@ use Rhymix\Framework\Exceptions\DBError;
/** /**
* DB helper class. * DB helper class.
* *
* We use instances of this class instead of raw PDO in order to provide * We use instances of this class instead of raw PDO in order to provide
* better logging and error handling while keeping backward compatibility. * better logging and error handling while keeping backward compatibility.
*/ */
@ -18,7 +18,7 @@ class DBHelper extends \PDO
* Store the database type (e.g. master) here. * Store the database type (e.g. master) here.
*/ */
protected $_type = 'master'; protected $_type = 'master';
/** /**
* Set the database type. * Set the database type.
*/ */
@ -26,10 +26,10 @@ class DBHelper extends \PDO
{ {
$this->_type = $type; $this->_type = $type;
} }
/** /**
* Create a prepared statement. * Create a prepared statement.
* *
* @param string $statement * @param string $statement
* @param array $options * @param array $options
* @return DBStmtHelper * @return DBStmtHelper
@ -39,7 +39,7 @@ class DBHelper extends \PDO
{ {
$start_time = microtime(true); $start_time = microtime(true);
$db_class = DB::getInstance($this->_type); $db_class = DB::getInstance($this->_type);
try try
{ {
/** /**
@ -66,24 +66,24 @@ class DBHelper extends \PDO
{ {
Debug::addQuery($db_class->getQueryLog($statement, $elapsed_time)); Debug::addQuery($db_class->getQueryLog($statement, $elapsed_time));
} }
/** /**
* This is a new feature in Rhymix 2.0 so we don't have to mess * This is a new feature in Rhymix 2.0 so we don't have to mess
* with status objects. We just throw an exception. Catch it! * with status objects. We just throw an exception. Catch it!
*/ */
throw new DBError($e->getMessage(), 0, $e); throw new DBError($e->getMessage(), 0, $e);
} }
return $stmt; return $stmt;
} }
/** /**
* Execute a query. * Execute a query.
* *
* This method accepts additional parameters, but they are not for creating * This method accepts additional parameters, but they are not for creating
* prepared statements. They exist because PDO's own query() method accepts * prepared statements. They exist because PDO's own query() method accepts
* various kinds of additional parameters, and we don't want to touch them. * various kinds of additional parameters, and we don't want to touch them.
* *
* @param string $statement * @param string $statement
* @param int $fetch_mode * @param int $fetch_mode
* @return DBStmtHelper|false * @return DBStmtHelper|false
@ -95,7 +95,7 @@ class DBHelper extends \PDO
$db_class = DB::getInstance($this->_type); $db_class = DB::getInstance($this->_type);
$args = func_get_args(); $args = func_get_args();
array_shift($args); array_shift($args);
try try
{ {
/** /**
@ -122,13 +122,13 @@ class DBHelper extends \PDO
Debug::addQuery($db_class->getQueryLog($statement, $elapsed_time)); Debug::addQuery($db_class->getQueryLog($statement, $elapsed_time));
} }
} }
return $stmt; return $stmt;
} }
/** /**
* Execute a query and return the number of affected rows. * Execute a query and return the number of affected rows.
* *
* @param string $statement * @param string $statement
* @return int|false * @return int|false
*/ */
@ -137,7 +137,7 @@ class DBHelper extends \PDO
{ {
$start_time = microtime(true); $start_time = microtime(true);
$db_class = DB::getInstance($this->_type); $db_class = DB::getInstance($this->_type);
try try
{ {
$result = parent::exec($statement); $result = parent::exec($statement);
@ -156,7 +156,7 @@ class DBHelper extends \PDO
Debug::addQuery($db_class->getQueryLog($statement, $elapsed_time)); Debug::addQuery($db_class->getQueryLog($statement, $elapsed_time));
} }
} }
return $result; return $result;
} }
} }

View file

@ -4,7 +4,7 @@ namespace Rhymix\Framework\Helpers;
/** /**
* DB result helper class. * DB result helper class.
* *
* Instances of this class will be returned from DB queries. * Instances of this class will be returned from DB queries.
*/ */
class DBResultHelper extends \BaseObject class DBResultHelper extends \BaseObject

View file

@ -8,7 +8,7 @@ use Rhymix\Framework\Exceptions\DBError;
/** /**
* DB Statement helper class. * DB Statement helper class.
* *
* We use instances of this class instead of raw PDOStatement in order to log * We use instances of this class instead of raw PDOStatement in order to log
* individual execute() calls of prepared statements. This is controlled by * individual execute() calls of prepared statements. This is controlled by
* the PDO::ATTR_STATEMENT_CLASS attribute set in the DB class. * the PDO::ATTR_STATEMENT_CLASS attribute set in the DB class.
@ -19,7 +19,7 @@ class DBStmtHelper extends \PDOStatement
* Store the database type (e.g. master) here. * Store the database type (e.g. master) here.
*/ */
protected $_type = 'master'; protected $_type = 'master';
/** /**
* Set the database type. * Set the database type.
*/ */
@ -27,10 +27,10 @@ class DBStmtHelper extends \PDOStatement
{ {
$this->_type = $type; $this->_type = $type;
} }
/** /**
* Execute a prepared statement. * Execute a prepared statement.
* *
* @param array $params * @param array $params
* @return bool * @return bool
*/ */
@ -38,7 +38,7 @@ class DBStmtHelper extends \PDOStatement
{ {
$start_time = microtime(true); $start_time = microtime(true);
$db_class = DB::getInstance($this->_type); $db_class = DB::getInstance($this->_type);
try try
{ {
$result = parent::execute($params); $result = parent::execute($params);
@ -58,7 +58,7 @@ class DBStmtHelper extends \PDOStatement
Debug::addQuery($db_class->getQueryLog($this->queryString, $elapsed_time)); Debug::addQuery($db_class->getQueryLog($this->queryString, $elapsed_time));
} }
} }
return $result; return $result;
} }
} }

View file

@ -15,10 +15,10 @@ class SessionHelper
public $is_admin = 'N'; public $is_admin = 'N';
public $group_list = array(); public $group_list = array();
public $menu_list = array(); public $menu_list = array();
/** /**
* Constructor. * Constructor.
* *
* @param int $member_srl (optional) * @param int $member_srl (optional)
* @return void * @return void
*/ */
@ -40,30 +40,30 @@ class SessionHelper
} }
} }
} }
/** /**
* Check if this user is a member. * Check if this user is a member.
* *
* @return bool * @return bool
*/ */
public function isMember() public function isMember()
{ {
return $this->member_srl > 0; return $this->member_srl > 0;
} }
/** /**
* Check if this user is an administrator. * Check if this user is an administrator.
* *
* @return bool * @return bool
*/ */
public function isAdmin() public function isAdmin()
{ {
return $this->is_admin === 'Y'; return $this->is_admin === 'Y';
} }
/** /**
* Check if this user is an administrator of a module. * Check if this user is an administrator of a module.
* *
* @param int $module_srl (optional) * @param int $module_srl (optional)
* @return bool * @return bool
*/ */
@ -71,10 +71,10 @@ class SessionHelper
{ {
return $this->is_admin === 'Y' || \ModuleModel::isModuleAdmin($this, $module_srl); return $this->is_admin === 'Y' || \ModuleModel::isModuleAdmin($this, $module_srl);
} }
/** /**
* Check if this user is valid (not denied or limited). * Check if this user is valid (not denied or limited).
* *
* @return bool * @return bool
*/ */
public function isValid() public function isValid()
@ -88,10 +88,10 @@ class SessionHelper
return false; return false;
} }
} }
/** /**
* Get the list of groups that this user belongs to. * Get the list of groups that this user belongs to.
* *
* @return array * @return array
*/ */
public function getGroups() public function getGroups()

View file

@ -17,15 +17,15 @@ class i18n
const SORT_NAME_ENGLISH = 6; const SORT_NAME_ENGLISH = 6;
const SORT_NAME_KOREAN = 7; const SORT_NAME_KOREAN = 7;
const SORT_NAME_NATIVE = 8; const SORT_NAME_NATIVE = 8;
/** /**
* Local cache. * Local cache.
*/ */
protected static $_countries = array(); protected static $_countries = array();
/** /**
* Get the list of all countries. * Get the list of all countries.
* *
* @param int $sort_by * @param int $sort_by
* @return array * @return array
*/ */
@ -35,15 +35,15 @@ class i18n
{ {
return self::$_countries[$sort_by]; return self::$_countries[$sort_by];
} }
$countries = (include \RX_BASEDIR . 'common/defaults/countries.php'); $countries = (include \RX_BASEDIR . 'common/defaults/countries.php');
$result = array(); $result = array();
foreach ($countries as $country) foreach ($countries as $country)
{ {
$result[$country['iso_3166_1_alpha3']] = (object)$country; $result[$country['iso_3166_1_alpha3']] = (object)$country;
} }
switch ($sort_by) switch ($sort_by)
{ {
case self::SORT_CODE_2: case self::SORT_CODE_2:
@ -82,16 +82,16 @@ class i18n
}); });
break; break;
} }
self::$_countries[$sort_by] = $result; self::$_countries[$sort_by] = $result;
return $result; return $result;
} }
/** /**
* Get the calling code from a country code (either ISO-3166-1 alpha2 or alpha3). * Get the calling code from a country code (either ISO-3166-1 alpha2 or alpha3).
* *
* This function returns null if a matching country is not found. * This function returns null if a matching country is not found.
* *
* @param $code Country code * @param $code Country code
* @return string|null * @return string|null
*/ */
@ -112,16 +112,16 @@ class i18n
} }
} }
} }
return null; return null;
} }
/** /**
* Get the country code (either ISO-3166-1 alpha2 or alpha3) from a calling code. * Get the country code (either ISO-3166-1 alpha2 or alpha3) from a calling code.
* *
* This function may return the wrong country if two or more countries share a calling code. * This function may return the wrong country if two or more countries share a calling code.
* This function returns null if a matching country is not found. * This function returns null if a matching country is not found.
* *
* @param $code Calling code * @param $code Calling code
* @return string|null * @return string|null
*/ */
@ -136,12 +136,12 @@ class i18n
return $type == 3 ? $country->iso_3166_1_alpha3 : $country->iso_3166_1_alpha2; return $type == 3 ? $country->iso_3166_1_alpha3 : $country->iso_3166_1_alpha2;
} }
} }
return null; return null;
} }
/** /**
* Format a phone number with country code. * Format a phone number with country code.
* *
* @param string $phone_number * @param string $phone_number
* @param string $phone_country * @param string $phone_country
* @param bool $pretty (optional) * @param bool $pretty (optional)
@ -153,7 +153,7 @@ class i18n
{ {
$phone_country = self::getCallingCodeByCountryCode($phone_country); $phone_country = self::getCallingCodeByCountryCode($phone_country);
} }
if ($pretty) if ($pretty)
{ {
if ($phone_country == 82) if ($phone_country == 82)

View file

@ -9,7 +9,7 @@ abstract class BaseParser
{ {
/** /**
* Get all attributes of an element as an associative array. * Get all attributes of an element as an associative array.
* *
* @param SimpleXMLElement $element * @param SimpleXMLElement $element
* @param bool $normalize * @param bool $normalize
* @return array * @return array
@ -27,10 +27,10 @@ abstract class BaseParser
} }
return $result; return $result;
} }
/** /**
* Get the contents of child elements that match a language. * Get the contents of child elements that match a language.
* *
* @param SimpleXMLElement $parent * @param SimpleXMLElement $parent
* @param string $tag_name * @param string $tag_name
* @param string $lang * @param string $lang
@ -47,20 +47,20 @@ abstract class BaseParser
return trim($child); return trim($child);
} }
} }
// Otherwise, return the first child element. // Otherwise, return the first child element.
foreach ($parent->{$tag_name} as $child) foreach ($parent->{$tag_name} as $child)
{ {
return trim($child); return trim($child);
} }
// If there are no child elements, return an empty string. // If there are no child elements, return an empty string.
return ''; return '';
} }
/** /**
* Parse extra_vars. * Parse extra_vars.
* *
* @param SimpleXMLElement $extra_vars * @param SimpleXMLElement $extra_vars
* @param string $lang * @param string $lang
* @return object * @return object
@ -98,7 +98,7 @@ abstract class BaseParser
$item->options[$option_item->value] = $option_item; $item->options[$option_item->value] = $option_item;
} }
} }
$result->{$item->name} = $item; $result->{$item->name} = $item;
} }
return $result; return $result;

View file

@ -14,7 +14,7 @@ class ConfigParser
{ {
/** /**
* Convert previous configuration files to the current format and return it. * Convert previous configuration files to the current format and return it.
* *
* @return array * @return array
*/ */
public static function convert() public static function convert()
@ -30,7 +30,7 @@ class ConfigParser
{ {
return array(); return array();
} }
// Load FTP info file. // Load FTP info file.
if (file_exists(\RX_BASEDIR . Config::$old_ftp_config_filename)) if (file_exists(\RX_BASEDIR . Config::$old_ftp_config_filename))
{ {
@ -38,7 +38,7 @@ class ConfigParser
include \RX_BASEDIR . Config::$old_ftp_config_filename; include \RX_BASEDIR . Config::$old_ftp_config_filename;
ob_end_clean(); ob_end_clean();
} }
// Load selected language file. // Load selected language file.
if (file_exists(\RX_BASEDIR . Config::$old_lang_config_filename)) if (file_exists(\RX_BASEDIR . Config::$old_lang_config_filename))
{ {
@ -62,10 +62,10 @@ class ConfigParser
$lang_selected = \Context::getLangType() === 'jp' ? 'ja' : \Context::getLangType(); $lang_selected = \Context::getLangType() === 'jp' ? 'ja' : \Context::getLangType();
$lang_selected = array($lang_selected); $lang_selected = array($lang_selected);
} }
// Load defaults for the new configuration. // Load defaults for the new configuration.
$config = (include \RX_BASEDIR . Config::$default_config_filename); $config = (include \RX_BASEDIR . Config::$default_config_filename);
// Convert database configuration. // Convert database configuration.
if (!isset($db_info->master_db)) if (!isset($db_info->master_db))
{ {
@ -78,7 +78,7 @@ class ConfigParser
$db_info->master_db['db_database'] = $db_info->db_database; $db_info->master_db['db_database'] = $db_info->db_database;
$db_info->master_db['db_table_prefix'] = $db_info->db_table_prefix; $db_info->master_db['db_table_prefix'] = $db_info->db_table_prefix;
} }
$config['db']['master']['type'] = strtolower($db_info->master_db['db_type']); $config['db']['master']['type'] = strtolower($db_info->master_db['db_type']);
$config['db']['master']['host'] = $db_info->master_db['db_hostname']; $config['db']['master']['host'] = $db_info->master_db['db_hostname'];
$config['db']['master']['port'] = $db_info->master_db['db_port']; $config['db']['master']['port'] = $db_info->master_db['db_port'];
@ -86,14 +86,14 @@ class ConfigParser
$config['db']['master']['pass'] = $db_info->master_db['db_password']; $config['db']['master']['pass'] = $db_info->master_db['db_password'];
$config['db']['master']['database'] = $db_info->master_db['db_database']; $config['db']['master']['database'] = $db_info->master_db['db_database'];
$config['db']['master']['prefix'] = $db_info->master_db['db_table_prefix']; $config['db']['master']['prefix'] = $db_info->master_db['db_table_prefix'];
if (substr($config['db']['master']['prefix'], -1) !== '_') if (substr($config['db']['master']['prefix'], -1) !== '_')
{ {
$config['db']['master']['prefix'] .= '_'; $config['db']['master']['prefix'] .= '_';
} }
$config['db']['master']['charset'] = $db_info->master_db['db_charset'] ?: 'utf8'; $config['db']['master']['charset'] = $db_info->master_db['db_charset'] ?: 'utf8';
if (strpos($config['db']['master']['type'], 'innodb') !== false) if (strpos($config['db']['master']['type'], 'innodb') !== false)
{ {
$config['db']['master']['type'] = str_replace('_innodb', '', $config['db']['master']['type']); $config['db']['master']['type'] = str_replace('_innodb', '', $config['db']['master']['type']);
@ -103,7 +103,7 @@ class ConfigParser
{ {
$config['db']['master']['engine'] = 'myisam'; $config['db']['master']['engine'] = 'myisam';
} }
if (isset($db_info->slave_db) && is_array($db_info->slave_db) && count($db_info->slave_db)) if (isset($db_info->slave_db) && is_array($db_info->slave_db) && count($db_info->slave_db))
{ {
foreach ($db_info->slave_db as $slave_id => $slave_db) foreach ($db_info->slave_db as $slave_id => $slave_db)
@ -118,14 +118,14 @@ class ConfigParser
$config['db'][$slave_id]['pass'] = $slave_db['db_password']; $config['db'][$slave_id]['pass'] = $slave_db['db_password'];
$config['db'][$slave_id]['database'] = $slave_db['db_database']; $config['db'][$slave_id]['database'] = $slave_db['db_database'];
$config['db'][$slave_id]['prefix'] = $slave_db['db_table_prefix']; $config['db'][$slave_id]['prefix'] = $slave_db['db_table_prefix'];
if (substr($config['db'][$slave_id]['prefix'], -1) !== '_') if (substr($config['db'][$slave_id]['prefix'], -1) !== '_')
{ {
$config['db'][$slave_id]['prefix'] .= '_'; $config['db'][$slave_id]['prefix'] .= '_';
} }
$config['db'][$slave_id]['charset'] = $slave_db['db_charset'] ?: 'utf8'; $config['db'][$slave_id]['charset'] = $slave_db['db_charset'] ?: 'utf8';
if (strpos($config['db'][$slave_id]['type'], 'innodb') !== false) if (strpos($config['db'][$slave_id]['type'], 'innodb') !== false)
{ {
$config['db'][$slave_id]['type'] = str_replace('_innodb', '', $config['db'][$slave_id]['type']); $config['db'][$slave_id]['type'] = str_replace('_innodb', '', $config['db'][$slave_id]['type']);
@ -138,7 +138,7 @@ class ConfigParser
} }
} }
} }
// Convert cache configuration. // Convert cache configuration.
if (isset($db_info->use_object_cache)) if (isset($db_info->use_object_cache))
{ {
@ -150,7 +150,7 @@ class ConfigParser
$config['cache']['ttl'] = 86400; $config['cache']['ttl'] = 86400;
$config['cache']['servers'] = in_array($config['cache']['type'], array('memcached', 'redis')) ? $db_info->use_object_cache : array(); $config['cache']['servers'] = in_array($config['cache']['type'], array('memcached', 'redis')) ? $db_info->use_object_cache : array();
} }
// Convert FTP configuration. // Convert FTP configuration.
if (isset($ftp_info)) if (isset($ftp_info))
{ {
@ -161,12 +161,12 @@ class ConfigParser
$config['ftp']['pasv'] = $ftp_info->ftp_pasv; $config['ftp']['pasv'] = $ftp_info->ftp_pasv;
$config['ftp']['sftp'] = $ftp_info->sftp === 'Y' ? true : false; $config['ftp']['sftp'] = $ftp_info->sftp === 'Y' ? true : false;
} }
// Create new crypto keys. // Create new crypto keys.
$config['crypto']['encryption_key'] = Security::getRandom(64, 'alnum'); $config['crypto']['encryption_key'] = Security::getRandom(64, 'alnum');
$config['crypto']['authentication_key'] = $db_info->secret_key ?: Security::getRandom(64, 'alnum'); $config['crypto']['authentication_key'] = $db_info->secret_key ?: Security::getRandom(64, 'alnum');
$config['crypto']['session_key'] = Security::getRandom(64, 'alnum'); $config['crypto']['session_key'] = Security::getRandom(64, 'alnum');
// Convert language configuration. // Convert language configuration.
if (isset($db_info->lang_type)) if (isset($db_info->lang_type))
{ {
@ -177,7 +177,7 @@ class ConfigParser
$config['locale']['default_lang'] = array_first($lang_selected); $config['locale']['default_lang'] = array_first($lang_selected);
} }
$config['locale']['enabled_lang'] = array_values($lang_selected); $config['locale']['enabled_lang'] = array_values($lang_selected);
// Convert timezone configuration. // Convert timezone configuration.
$old_timezone = DateTime::getTimezoneOffsetByLegacyFormat($db_info->time_zone ?: '+0900'); $old_timezone = DateTime::getTimezoneOffsetByLegacyFormat($db_info->time_zone ?: '+0900');
switch ($old_timezone) switch ($old_timezone)
@ -188,7 +188,7 @@ class ConfigParser
$config['locale']['default_timezone'] = DateTime::getTimezoneNameByOffset($old_timezone); $config['locale']['default_timezone'] = DateTime::getTimezoneNameByOffset($old_timezone);
} }
$config['locale']['internal_timezone'] = intval(date('Z')); $config['locale']['internal_timezone'] = intval(date('Z'));
// Convert URL configuration. // Convert URL configuration.
$default_url = $db_info->default_url; $default_url = $db_info->default_url;
if (strpos($default_url, 'xn--') !== false) if (strpos($default_url, 'xn--') !== false)
@ -199,21 +199,21 @@ class ConfigParser
$config['url']['http_port'] = $db_info->http_port ?: null; $config['url']['http_port'] = $db_info->http_port ?: null;
$config['url']['https_port'] = $db_info->https_port ?: null; $config['url']['https_port'] = $db_info->https_port ?: null;
$config['url']['ssl'] = ($db_info->use_ssl === 'none') ? 'none' : 'always'; $config['url']['ssl'] = ($db_info->use_ssl === 'none') ? 'none' : 'always';
// Convert session configuration. // Convert session configuration.
$config['session']['delay'] = $db_info->delay_session === 'Y' ? true : false; $config['session']['delay'] = $db_info->delay_session === 'Y' ? true : false;
$config['session']['use_db'] = $db_info->use_db_session === 'Y' ? true : false; $config['session']['use_db'] = $db_info->use_db_session === 'Y' ? true : false;
// Convert view configuration. // Convert view configuration.
$config['view']['minify_scripts'] = $db_info->minify_scripts ?: 'common'; $config['view']['minify_scripts'] = $db_info->minify_scripts ?: 'common';
$config['view']['use_gzip'] = (defined('__OB_GZHANDLER_ENABLE__') && constant('__OB_GZHANDLER_ENABLE__')); $config['view']['use_gzip'] = (defined('__OB_GZHANDLER_ENABLE__') && constant('__OB_GZHANDLER_ENABLE__'));
// Convert admin IP whitelist. // Convert admin IP whitelist.
if (isset($db_info->admin_ip_list) && is_array($db_info->admin_ip_list) && count($db_info->admin_ip_list)) if (isset($db_info->admin_ip_list) && is_array($db_info->admin_ip_list) && count($db_info->admin_ip_list))
{ {
$config['admin']['allow'] = array_values($db_info->admin_ip_list); $config['admin']['allow'] = array_values($db_info->admin_ip_list);
} }
// Convert sitelock configuration. // Convert sitelock configuration.
$config['lock']['locked'] = $db_info->use_sitelock === 'Y' ? true : false; $config['lock']['locked'] = $db_info->use_sitelock === 'Y' ? true : false;
$config['lock']['title'] = strval($db_info->sitelock_title); $config['lock']['title'] = strval($db_info->sitelock_title);
@ -227,7 +227,7 @@ class ConfigParser
$db_info->sitelock_whitelist[] = '127.0.0.1'; $db_info->sitelock_whitelist[] = '127.0.0.1';
} }
$config['lock']['allow'] = array_values($db_info->sitelock_whitelist); $config['lock']['allow'] = array_values($db_info->sitelock_whitelist);
// Convert media filter configuration. // Convert media filter configuration.
if (is_array($db_info->embed_white_iframe)) if (is_array($db_info->embed_white_iframe))
{ {
@ -245,14 +245,14 @@ class ConfigParser
natcasesort($whitelist); natcasesort($whitelist);
$config['mediafilter']['object'] = $whitelist; $config['mediafilter']['object'] = $whitelist;
} }
// Convert miscellaneous configuration. // Convert miscellaneous configuration.
$config['file']['folder_structure'] = 1; $config['file']['folder_structure'] = 1;
$config['file']['umask'] = Storage::recommendUmask(); $config['file']['umask'] = Storage::recommendUmask();
$config['mobile']['enabled'] = $db_info->use_mobile_view === 'N' ? false : true; $config['mobile']['enabled'] = $db_info->use_mobile_view === 'N' ? false : true;
$config['use_rewrite'] = $db_info->use_rewrite === 'Y' ? true : false; $config['use_rewrite'] = $db_info->use_rewrite === 'Y' ? true : false;
$config['use_sso'] = $db_info->use_sso === 'Y' ? true : false; $config['use_sso'] = $db_info->use_sso === 'Y' ? true : false;
// Copy other configuration. // Copy other configuration.
unset($db_info->master_db, $db_info->slave_db); unset($db_info->master_db, $db_info->slave_db);
unset($db_info->lang_type, $db_info->time_zone); unset($db_info->lang_type, $db_info->time_zone);
@ -267,7 +267,7 @@ class ConfigParser
{ {
$config['other'][$key] = $value; $config['other'][$key] = $value;
} }
// Return the new configuration. // Return the new configuration.
return $config; return $config;
} }

View file

@ -9,7 +9,7 @@ class DBQueryParser extends BaseParser
{ {
/** /**
* Load a query XML file. * Load a query XML file.
* *
* @param string $filename * @param string $filename
* @return object|false * @return object|false
*/ */
@ -21,16 +21,16 @@ class DBQueryParser extends BaseParser
{ {
return false; return false;
} }
// Parse the query. // Parse the query.
$query_name = preg_replace('/\.xml$/', '', basename($filename)); $query_name = preg_replace('/\.xml$/', '', basename($filename));
$query = self::_parseQuery($xml, $query_name); $query = self::_parseQuery($xml, $query_name);
return $query; return $query;
} }
/** /**
* Parse a query. * Parse a query.
* *
* @param SimpleXMLElement $xml * @param SimpleXMLElement $xml
* @param string $name * @param string $name
* @return object * @return object
@ -47,12 +47,12 @@ class DBQueryParser extends BaseParser
{ {
$query->name = $query->alias; $query->name = $query->alias;
} }
// Load attributes that only apply to subqueries in the <conditions> block. // Load attributes that only apply to subqueries in the <conditions> block.
$query->operation = $attribs['operation'] ?? null; $query->operation = $attribs['operation'] ?? null;
$query->column = preg_replace('/[^a-z0-9_\.]/i', '', $attribs['column'] ?? '') ?: null; $query->column = preg_replace('/[^a-z0-9_\.]/i', '', $attribs['column'] ?? '') ?: null;
$query->pipe = strtoupper($attribs['pipe'] ?? '') ?: 'AND'; $query->pipe = strtoupper($attribs['pipe'] ?? '') ?: 'AND';
// Load tables. // Load tables.
foreach ($xml->tables ? $xml->tables->children() : [] as $tag) foreach ($xml->tables ? $xml->tables->children() : [] as $tag)
{ {
@ -68,7 +68,7 @@ class DBQueryParser extends BaseParser
$table->alias = trim($tag['alias'] ?? '') ?: null; $table->alias = trim($tag['alias'] ?? '') ?: null;
$table->ifvar = trim($tag['if'] ?? '') ?: null; $table->ifvar = trim($tag['if'] ?? '') ?: null;
} }
$table_type = trim($tag['type'] ?? ''); $table_type = trim($tag['type'] ?? '');
if (stripos($table_type, 'join') !== false) if (stripos($table_type, 'join') !== false)
{ {
@ -80,7 +80,7 @@ class DBQueryParser extends BaseParser
} }
$query->tables[$table->alias ?: $table->name] = $table; $query->tables[$table->alias ?: $table->name] = $table;
} }
// Load index hints. // Load index hints.
foreach ($xml->index_hint ?: [] as $index_hint_group) foreach ($xml->index_hint ?: [] as $index_hint_group)
{ {
@ -94,7 +94,7 @@ class DBQueryParser extends BaseParser
{ {
$index_hint_target_db = []; $index_hint_target_db = [];
} }
foreach ($index_hint_group->children() ?: [] as $tag) foreach ($index_hint_group->children() ?: [] as $tag)
{ {
$index_hint = new DBQuery\IndexHint; $index_hint = new DBQuery\IndexHint;
@ -117,7 +117,7 @@ class DBQueryParser extends BaseParser
} }
} }
} }
// Load columns. // Load columns.
foreach ($xml->columns ? $xml->columns->children() : [] as $tag) foreach ($xml->columns ? $xml->columns->children() : [] as $tag)
{ {
@ -158,13 +158,13 @@ class DBQueryParser extends BaseParser
$query->columns[] = $column; $query->columns[] = $column;
} }
} }
// Load conditions. // Load conditions.
if ($xml->conditions) if ($xml->conditions)
{ {
$query->conditions = self::_parseConditions($xml->conditions); $query->conditions = self::_parseConditions($xml->conditions);
} }
// Load groups. // Load groups.
if ($xml->groups) if ($xml->groups)
{ {
@ -183,7 +183,7 @@ class DBQueryParser extends BaseParser
} }
} }
} }
// Load navigation settings. // Load navigation settings.
if ($xml->navigation) if ($xml->navigation)
{ {
@ -208,7 +208,7 @@ class DBQueryParser extends BaseParser
} }
} }
} }
// If a SELECT query has no columns, use * by default. // If a SELECT query has no columns, use * by default.
if ($query->type === 'SELECT' && !count($query->columns)) if ($query->type === 'SELECT' && !count($query->columns))
{ {
@ -218,7 +218,7 @@ class DBQueryParser extends BaseParser
$column->is_expression = true; $column->is_expression = true;
$query->columns[] = $column; $query->columns[] = $column;
} }
// Check the SELECT DISTINCT flag. // Check the SELECT DISTINCT flag.
if ($xml->columns && $select_distinct = trim($xml->columns['distinct'] ?? '')) if ($xml->columns && $select_distinct = trim($xml->columns['distinct'] ?? ''))
{ {
@ -227,7 +227,7 @@ class DBQueryParser extends BaseParser
$query->select_distinct = true; $query->select_distinct = true;
} }
} }
// Check the ON DUPLICATE KEY UPDATE (upsert) flag. // Check the ON DUPLICATE KEY UPDATE (upsert) flag.
if ($query->type === 'INSERT' && $update_duplicate = self::_getAttributes($xml)['updateduplicate'] ?? false) if ($query->type === 'INSERT' && $update_duplicate = self::_getAttributes($xml)['updateduplicate'] ?? false)
{ {
@ -236,14 +236,14 @@ class DBQueryParser extends BaseParser
$query->update_duplicate = true; $query->update_duplicate = true;
} }
} }
// Return the complete query definition. // Return the complete query definition.
return $query; return $query;
} }
/** /**
* Parse conditions. * Parse conditions.
* *
* @param SimpleXMLElement $parent * @param SimpleXMLElement $parent
* @return array * @return array
*/ */
@ -291,7 +291,7 @@ class DBQueryParser extends BaseParser
$result[] = $subquery; $result[] = $subquery;
} }
} }
return $result; return $result;
} }
} }

View file

@ -16,7 +16,7 @@ class DBTableParser extends BaseParser
'bigtext' => 'longtext', 'bigtext' => 'longtext',
'date' => 'char(14)', 'date' => 'char(14)',
); );
/** /**
* List of types for which the size attribute will be ignored. * List of types for which the size attribute will be ignored.
*/ */
@ -25,10 +25,10 @@ class DBTableParser extends BaseParser
'int' => true, 'int' => true,
'integer' => true, 'integer' => true,
); );
/** /**
* Load a table definition XML file. * Load a table definition XML file.
* *
* @param string $filename * @param string $filename
* @param string $content * @param string $content
* @return object|false * @return object|false
@ -44,12 +44,12 @@ class DBTableParser extends BaseParser
{ {
$xml = simplexml_load_string(file_get_contents($filename)); $xml = simplexml_load_string(file_get_contents($filename));
} }
if ($xml === false) if ($xml === false)
{ {
return false; return false;
} }
// Initialize table definition. // Initialize table definition.
$table = new DBTable\Table; $table = new DBTable\Table;
if ($filename) if ($filename)
@ -60,13 +60,13 @@ class DBTableParser extends BaseParser
{ {
$table->name = strval($xml['name']); $table->name = strval($xml['name']);
} }
$deleted = strval($xml['deleted']); $deleted = strval($xml['deleted']);
if ($deleted !== '') if ($deleted !== '')
{ {
$table->deleted = toBool($deleted); $table->deleted = toBool($deleted);
} }
// Load columns. // Load columns.
foreach ($xml->column as $column_info) foreach ($xml->column as $column_info)
{ {
@ -74,10 +74,10 @@ class DBTableParser extends BaseParser
$column = new DBTable\Column; $column = new DBTable\Column;
$column->name = strval($column_info['name']); $column->name = strval($column_info['name']);
list($column->type, $column->xetype, $column->size) = self::getTypeAndSize(strval($column_info['type']), strval($column_info['size'])); list($column->type, $column->xetype, $column->size) = self::getTypeAndSize(strval($column_info['type']), strval($column_info['size']));
// Get all attributes. // Get all attributes.
$attribs = self::_getAttributes($column_info); $attribs = self::_getAttributes($column_info);
// Get the charset/utf8mb4 attribute. // Get the charset/utf8mb4 attribute.
if (isset($attribs['charset'])) if (isset($attribs['charset']))
{ {
@ -91,19 +91,19 @@ class DBTableParser extends BaseParser
{ {
$column->charset = 'latin1'; $column->charset = 'latin1';
} }
// Get the default value. // Get the default value.
if (isset($attribs['default'])) if (isset($attribs['default']))
{ {
$column->default_value = $attribs['default']; $column->default_value = $attribs['default'];
} }
// Get the NOT NULL attribute. // Get the NOT NULL attribute.
if (isset($attribs['notnull'])) if (isset($attribs['notnull']))
{ {
$column->not_null = true; $column->not_null = true;
} }
// Get index information. // Get index information.
if (isset($attribs['index'])) if (isset($attribs['index']))
{ {
@ -129,7 +129,7 @@ class DBTableParser extends BaseParser
$column->is_indexed = true; $column->is_indexed = true;
$column->is_unique = true; $column->is_unique = true;
} }
// Get primary key information. // Get primary key information.
if (isset($attribs['primarykey']) && toBool($attribs['primarykey'])) if (isset($attribs['primarykey']) && toBool($attribs['primarykey']))
{ {
@ -138,17 +138,17 @@ class DBTableParser extends BaseParser
$column->is_unique = true; $column->is_unique = true;
$column->is_primary_key = true; $column->is_primary_key = true;
} }
// Get auto-increment information. // Get auto-increment information.
if (isset($attribs['autoincrement']) && toBool($attribs['autoincrement'])) if (isset($attribs['autoincrement']) && toBool($attribs['autoincrement']))
{ {
$column->auto_increment = true; $column->auto_increment = true;
} }
// Add the column to the table definition. // Add the column to the table definition.
$table->columns[$column->name] = $column; $table->columns[$column->name] = $column;
} }
// Load indexes. // Load indexes.
foreach ($xml->index as $index_info) foreach ($xml->index as $index_info)
{ {
@ -169,7 +169,7 @@ class DBTableParser extends BaseParser
$index->columns[$idxcolumn] = 0; $index->columns[$idxcolumn] = 0;
} }
} }
// Get the index type. // Get the index type.
if (isset($index_info['type']) && $index_info['type']) if (isset($index_info['type']) && $index_info['type'])
{ {
@ -179,24 +179,24 @@ class DBTableParser extends BaseParser
{ {
$index->type = 'UNIQUE'; $index->type = 'UNIQUE';
} }
// Set attributes on indexed columns. // Set attributes on indexed columns.
if (isset($table->columns[$idxcolumn]) && is_object($table->columns[$idxcolumn])) if (isset($table->columns[$idxcolumn]) && is_object($table->columns[$idxcolumn]))
{ {
$table->columns[$idxcolumn]->is_indexed = true; $table->columns[$idxcolumn]->is_indexed = true;
$table->columns[$idxcolumn]->is_unique = $index->type === 'UNIQUE' ? true : $table->columns[$idxcolumn]->is_unique; $table->columns[$idxcolumn]->is_unique = $index->type === 'UNIQUE' ? true : $table->columns[$idxcolumn]->is_unique;
} }
// If any index options are given, also store them in the index class. // If any index options are given, also store them in the index class.
if (isset($index_info['options']) && $index_info['options']) if (isset($index_info['options']) && $index_info['options'])
{ {
$index->options = $index_info['options']; $index->options = $index_info['options'];
} }
// Add the index to the column definition. // Add the index to the column definition.
$table->indexes[$index->name] = $index; $table->indexes[$index->name] = $index;
} }
// Load other constraints (foreign keys). // Load other constraints (foreign keys).
foreach ($xml->constraint as $const_info) foreach ($xml->constraint as $const_info)
{ {
@ -210,14 +210,14 @@ class DBTableParser extends BaseParser
$constraint->on_update = ($const_info['onupdate'] ?? null) ?: $constraint->on_update; $constraint->on_update = ($const_info['onupdate'] ?? null) ?: $constraint->on_update;
$table->constraints[] = $constraint; $table->constraints[] = $constraint;
} }
// Return the complete table definition. // Return the complete table definition.
return $table; return $table;
} }
/** /**
* Get column type and size. * Get column type and size.
* *
* @param string $type * @param string $type
* @param string $size * @param string $size
* @return array * @return array
@ -235,7 +235,7 @@ class DBTableParser extends BaseParser
$xetype = 'none'; $xetype = 'none';
$type = ltrim($type, '\\'); $type = ltrim($type, '\\');
} }
// Extract and normalize the size. // Extract and normalize the size.
if (preg_match('/^([a-z0-9_]+)\(([0-9,\s]+)\)$/i', $type, $matches)) if (preg_match('/^([a-z0-9_]+)\(([0-9,\s]+)\)$/i', $type, $matches))
{ {
@ -247,14 +247,14 @@ class DBTableParser extends BaseParser
{ {
$size = null; $size = null;
} }
// Return a complete array. // Return a complete array.
return [$type, $xetype, $size]; return [$type, $xetype, $size];
} }
/** /**
* Get the XE-compatible type from a real database type. * Get the XE-compatible type from a real database type.
* *
* @param string $type * @param string $type
* @param string $size * @param string $size
* @return string * @return string
@ -281,10 +281,10 @@ class DBTableParser extends BaseParser
return $type; return $type;
} }
} }
/** /**
* Order tables according to foreign key relations. * Order tables according to foreign key relations.
* *
* @param array $tables [$table_name => $filename] * @param array $tables [$table_name => $filename]
* @return array * @return array
*/ */
@ -310,7 +310,7 @@ class DBTableParser extends BaseParser
$ref_list[$table_name] = $info; $ref_list[$table_name] = $info;
} }
} }
// Sort each table after the ones they are dependent on. // Sort each table after the ones they are dependent on.
for ($j = 0; $j < count($ref_list); $j++) for ($j = 0; $j < count($ref_list); $j++)
{ {
@ -335,11 +335,11 @@ class DBTableParser extends BaseParser
break; break;
} }
} }
uasort($ref_list, function($a, $b) { uasort($ref_list, function($a, $b) {
return $a->index - $b->index; return $a->index - $b->index;
}); });
// Produce a result in the same format as the input. // Produce a result in the same format as the input.
$result = []; $result = [];
foreach ($ref_list as $table_name => $info) foreach ($ref_list as $table_name => $info)

View file

@ -9,7 +9,7 @@ class EditorComponentParser extends BaseParser
{ {
/** /**
* Load an XML file. * Load an XML file.
* *
* @param string $filename * @param string $filename
* @param string $component_name * @param string $component_name
* @param string $lang * @param string $lang
@ -23,14 +23,14 @@ class EditorComponentParser extends BaseParser
{ {
return false; return false;
} }
// Get the current language. // Get the current language.
$lang = $lang ?: (\Context::getLangType() ?: 'en'); $lang = $lang ?: (\Context::getLangType() ?: 'en');
// Initialize the module definition. // Initialize the module definition.
$info = new \stdClass; $info = new \stdClass;
$info->component_name = $component_name; $info->component_name = $component_name;
// Get basic information. // Get basic information.
$info->title = self::_getChildrenByLang($xml, 'title', $lang); $info->title = self::_getChildrenByLang($xml, 'title', $lang);
$info->description = self::_getChildrenByLang($xml, 'description', $lang); $info->description = self::_getChildrenByLang($xml, 'description', $lang);
@ -40,7 +40,7 @@ class EditorComponentParser extends BaseParser
$info->license = trim($xml->license ?? ''); $info->license = trim($xml->license ?? '');
$info->license_link = trim($xml->license['link'] ?? ''); $info->license_link = trim($xml->license['link'] ?? '');
$info->author = array(); $info->author = array();
foreach ($xml->author as $author) foreach ($xml->author as $author)
{ {
$author_info = new \stdClass; $author_info = new \stdClass;
@ -49,13 +49,13 @@ class EditorComponentParser extends BaseParser
$author_info->homepage = trim($author['link'] ?? ''); $author_info->homepage = trim($author['link'] ?? '');
$info->author[] = $author_info; $info->author[] = $author_info;
} }
// Get extra_vars. // Get extra_vars.
if ($xml->extra_vars) if ($xml->extra_vars)
{ {
$info->extra_vars = self::_getExtraVars($xml->extra_vars, $lang); $info->extra_vars = self::_getExtraVars($xml->extra_vars, $lang);
} }
// Return the complete result. // Return the complete result.
return $info; return $info;
} }

View file

@ -12,7 +12,7 @@ class LangParser
{ {
/** /**
* Convert a directory of old language files to the Rhymix format. * Convert a directory of old language files to the Rhymix format.
* *
* @param string $dir * @param string $dir
* @param array $xml_langs When converting XML to PHP, only convert these languages. (Optional) * @param array $xml_langs When converting XML to PHP, only convert these languages. (Optional)
* @return void * @return void
@ -37,10 +37,10 @@ class LangParser
} }
} }
} }
/** /**
* Compile XE-compatible XML lang files into PHP. * Compile XE-compatible XML lang files into PHP.
* *
* @param string $filename * @param string $filename
* @param string $language * @param string $language
* @return string|false * @return string|false
@ -56,7 +56,7 @@ class LangParser
return $output_filename; return $output_filename;
} }
} }
// Load the XML lang file. // Load the XML lang file.
$xml = simplexml_load_string(Storage::read($filename)); $xml = simplexml_load_string(Storage::read($filename));
if ($xml === false) if ($xml === false)
@ -64,12 +64,12 @@ class LangParser
Storage::write($output_filename, ''); Storage::write($output_filename, '');
return false; return false;
} }
// Convert XML to a PHP array. // Convert XML to a PHP array.
$lang = array(); $lang = array();
self::_toArray($xml, $lang, $language); self::_toArray($xml, $lang, $language);
unset($xml); unset($xml);
// Save the array as a cache file. // Save the array as a cache file.
$buff = "<?php\n// $filename\n"; $buff = "<?php\n// $filename\n";
foreach ($lang as $key => $value) foreach ($lang as $key => $value)
@ -99,10 +99,10 @@ class LangParser
Storage::write($output_filename, $buff); Storage::write($output_filename, $buff);
return $output_filename; return $output_filename;
} }
/** /**
* XML to array conversion callback. * XML to array conversion callback.
* *
* @param array $items * @param array $items
* @return void * @return void
*/ */

View file

@ -20,10 +20,10 @@ class ModuleActionParser extends BaseParser
'any' => '[^/]+', 'any' => '[^/]+',
'delete' => '[^/]+', 'delete' => '[^/]+',
); );
/** /**
* Load an XML file. * Load an XML file.
* *
* @param string $filename * @param string $filename
* @return object|false * @return object|false
*/ */
@ -35,10 +35,10 @@ class ModuleActionParser extends BaseParser
{ {
return false; return false;
} }
// Get the current language. // Get the current language.
$lang = \Context::getLangType() ?: 'en'; $lang = \Context::getLangType() ?: 'en';
// Initialize the module definition. // Initialize the module definition.
$info = new \stdClass; $info = new \stdClass;
$info->admin_index_act = ''; $info->admin_index_act = '';
@ -52,7 +52,7 @@ class ModuleActionParser extends BaseParser
$info->grant = new \stdClass; $info->grant = new \stdClass;
$info->menu = new \stdClass; $info->menu = new \stdClass;
$info->error_handlers = []; $info->error_handlers = [];
// Parse grants. // Parse grants.
foreach ($xml->grants->grant ?: [] as $grant) foreach ($xml->grants->grant ?: [] as $grant)
{ {
@ -62,7 +62,7 @@ class ModuleActionParser extends BaseParser
$grant_name = trim($grant['name']); $grant_name = trim($grant['name']);
$info->grant->{$grant_name} = $grant_info; $info->grant->{$grant_name} = $grant_info;
} }
// Parse menus. // Parse menus.
foreach ($xml->menus->menu ?: [] as $menu) foreach ($xml->menus->menu ?: [] as $menu)
{ {
@ -74,7 +74,7 @@ class ModuleActionParser extends BaseParser
$menu_name = trim($menu['name'] ?? ''); $menu_name = trim($menu['name'] ?? '');
$info->menu->{$menu_name} = $menu_info; $info->menu->{$menu_name} = $menu_info;
} }
// Parse actions. // Parse actions.
foreach ($xml->actions->action ?: [] as $action) foreach ($xml->actions->action ?: [] as $action)
{ {
@ -90,7 +90,7 @@ class ModuleActionParser extends BaseParser
$permission_info->check_var = trim($action['check_var'] ?? '') ?: trim($action['check-var'] ?? ''); $permission_info->check_var = trim($action['check_var'] ?? '') ?: trim($action['check-var'] ?? '');
$permission_info->check_type = trim($action['check_type'] ?? '') ?: trim($action['check-type'] ?? ''); $permission_info->check_type = trim($action['check_type'] ?? '') ?: trim($action['check-type'] ?? '');
} }
// Parse the list of allowed HTTP methods. // Parse the list of allowed HTTP methods.
$method_attr = trim($action['method'] ?? ''); $method_attr = trim($action['method'] ?? '');
if ($method_attr) if ($method_attr)
@ -109,7 +109,7 @@ class ModuleActionParser extends BaseParser
{ {
$methods = ['GET', 'POST']; $methods = ['GET', 'POST'];
} }
// Parse routes. // Parse routes.
$global_route = (trim($action['global_route'] ?? '') ?: trim($action['global-route'] ?? '')) === 'true' ? 'true' : 'false'; $global_route = (trim($action['global_route'] ?? '') ?: trim($action['global-route'] ?? '')) === 'true' ? 'true' : 'false';
$route_attr = trim($action['route'] ?? ''); $route_attr = trim($action['route'] ?? '');
@ -134,7 +134,7 @@ class ModuleActionParser extends BaseParser
} }
} }
} }
// Parse the standalone attribute. // Parse the standalone attribute.
if ($global_route === 'true') if ($global_route === 'true')
{ {
@ -173,7 +173,7 @@ class ModuleActionParser extends BaseParser
$action_type = 'auto'; $action_type = 'auto';
} }
} }
// Parse other information about this action. // Parse other information about this action.
$action_info = new \stdClass; $action_info = new \stdClass;
$action_info->type = $action_type; $action_info->type = $action_type;
@ -188,7 +188,7 @@ class ModuleActionParser extends BaseParser
$action_info->meta_noindex = (trim($action['meta_noindex'] ?? '') ?: trim($action['meta-noindex'] ?? '')) === 'true' ? 'true' : 'false'; $action_info->meta_noindex = (trim($action['meta_noindex'] ?? '') ?: trim($action['meta-noindex'] ?? '')) === 'true' ? 'true' : 'false';
$action_info->global_route = $global_route; $action_info->global_route = $global_route;
$info->action->{$action_name} = $action_info; $info->action->{$action_name} = $action_info;
// Set the menu name and index settings. // Set the menu name and index settings.
$menu_name = trim($action['menu_name'] ?? ''); $menu_name = trim($action['menu_name'] ?? '');
if ($menu_name && isset($info->menu->{$menu_name})) if ($menu_name && isset($info->menu->{$menu_name}))
@ -215,7 +215,7 @@ class ModuleActionParser extends BaseParser
{ {
$info->simple_setup_index_act = $action_name; $info->simple_setup_index_act = $action_name;
} }
// Set error handler settings. // Set error handler settings.
$error_handlers = explode(',', trim($action['error_handlers'] ?? '') ?: trim($action['error-handlers'] ?? '')); $error_handlers = explode(',', trim($action['error_handlers'] ?? '') ?: trim($action['error-handlers'] ?? ''));
foreach ($error_handlers as $error_handler) foreach ($error_handlers as $error_handler)
@ -226,7 +226,7 @@ class ModuleActionParser extends BaseParser
} }
} }
} }
// Parse permissions not defined in the <actions> section. // Parse permissions not defined in the <actions> section.
foreach ($xml->permissions->permission ?: [] as $permission) foreach ($xml->permissions->permission ?: [] as $permission)
{ {
@ -238,14 +238,14 @@ class ModuleActionParser extends BaseParser
$info->action->{$action_name}->permission->check_type = trim($permission['check_type'] ?? '') ?: trim($permission['check-type'] ?? ''); $info->action->{$action_name}->permission->check_type = trim($permission['check_type'] ?? '') ?: trim($permission['check-type'] ?? '');
} }
} }
// Return the complete result. // Return the complete result.
return $info; return $info;
} }
/** /**
* Convert route definition into a regular expression. * Convert route definition into a regular expression.
* *
* @param array $route * @param array $route
* @return object * @return object
*/ */
@ -269,10 +269,10 @@ class ModuleActionParser extends BaseParser
$vars[$match[1]] = $var_type; $vars[$match[1]] = $var_type;
return $named_group; return $named_group;
}, $route['route']); }, $route['route']);
// Anchor the regexp at both ends. // Anchor the regexp at both ends.
$regexp = '#^' . strtr($regexp, ['#' => '\\#']) . '$#u'; $regexp = '#^' . strtr($regexp, ['#' => '\\#']) . '$#u';
// Return the regexp and variable list. // Return the regexp and variable list.
$result = new \stdClass; $result = new \stdClass;
$result->route = preg_replace_callback($var_regexp, function($match) { $result->route = preg_replace_callback($var_regexp, function($match) {

View file

@ -9,7 +9,7 @@ class ModuleInfoParser extends BaseParser
{ {
/** /**
* Load an XML file. * Load an XML file.
* *
* @param string $filename * @param string $filename
* @return object|false * @return object|false
*/ */
@ -21,16 +21,16 @@ class ModuleInfoParser extends BaseParser
{ {
return false; return false;
} }
// Get the current language. // Get the current language.
$lang = \Context::getLangType() ?: 'en'; $lang = \Context::getLangType() ?: 'en';
// Initialize the module definition. // Initialize the module definition.
$info = new \stdClass; $info = new \stdClass;
// Get the XML schema version. // Get the XML schema version.
$version = strval($xml['version']) ?: '0.1'; $version = strval($xml['version']) ?: '0.1';
// Parse version 0.2 // Parse version 0.2
if ($version === '0.2') if ($version === '0.2')
{ {
@ -43,7 +43,7 @@ class ModuleInfoParser extends BaseParser
$info->license = trim($xml->license); $info->license = trim($xml->license);
$info->license_link = trim($xml->license['link'] ?? ''); $info->license_link = trim($xml->license['link'] ?? '');
$info->author = array(); $info->author = array();
foreach ($xml->author as $author) foreach ($xml->author as $author)
{ {
$author_info = new \stdClass; $author_info = new \stdClass;
@ -53,7 +53,7 @@ class ModuleInfoParser extends BaseParser
$info->author[] = $author_info; $info->author[] = $author_info;
} }
} }
// Parse version 0.1 // Parse version 0.1
else else
{ {
@ -66,7 +66,7 @@ class ModuleInfoParser extends BaseParser
$info->license = trim($xml->license); $info->license = trim($xml->license);
$info->license_link = trim($xml->license['link'] ?? ''); $info->license_link = trim($xml->license['link'] ?? '');
$info->author = array(); $info->author = array();
foreach ($xml->author as $author) foreach ($xml->author as $author)
{ {
$author_info = new \stdClass; $author_info = new \stdClass;
@ -88,7 +88,7 @@ class ModuleInfoParser extends BaseParser
$info->simple_setup_index_act = $action_info->simple_setup_index_act; $info->simple_setup_index_act = $action_info->simple_setup_index_act;
$info->error_handlers = $action_info->error_handlers ?: []; $info->error_handlers = $action_info->error_handlers ?: [];
} }
// Return the complete result. // Return the complete result.
return $info; return $info;
} }

View file

@ -9,7 +9,7 @@ class XMLRPCParser
{ {
/** /**
* Load an XML file. * Load an XML file.
* *
* @param string $content * @param string $content
* @return object|false * @return object|false
*/ */
@ -21,17 +21,17 @@ class XMLRPCParser
{ {
return false; return false;
} }
// Loop over the list of parameters. // Loop over the list of parameters.
$result = self::_parseArray($xml->params); $result = self::_parseArray($xml->params);
// Return the complete result. // Return the complete result.
return $result; return $result;
} }
/** /**
* Process an array of parameters. * Process an array of parameters.
* *
* @param \SimpleXMLElement $parent * @param \SimpleXMLElement $parent
* @return array * @return array
*/ */

View file

@ -21,21 +21,21 @@ class Query extends VariableBase
public $select_distinct = false; public $select_distinct = false;
public $update_duplicate = false; public $update_duplicate = false;
public $requires_pagination = false; public $requires_pagination = false;
/** /**
* Attributes for subqueries in the <tables> or <columns> section. * Attributes for subqueries in the <tables> or <columns> section.
*/ */
public $alias; public $alias;
public $join_type; public $join_type;
public $join_conditions = array(); public $join_conditions = array();
/** /**
* Attributes for subqueries in the <conditions> section. * Attributes for subqueries in the <conditions> section.
*/ */
public $operation; public $operation;
public $column; public $column;
public $pipe; public $pipe;
/** /**
* Attributes used during query string generation. * Attributes used during query string generation.
*/ */
@ -43,17 +43,17 @@ class Query extends VariableBase
protected $_args = array(); protected $_args = array();
protected $_column_list = array(); protected $_column_list = array();
protected $_params = array(); protected $_params = array();
/** /**
* Constants for alias handling. * Constants for alias handling.
*/ */
const ALIAS_NONE = 0; const ALIAS_NONE = 0;
const ALIAS_SPECIFIED = 1; const ALIAS_SPECIFIED = 1;
const ALIAS_ALWAYS = 2; const ALIAS_ALWAYS = 2;
/** /**
* Generate the query string for this query. * Generate the query string for this query.
* *
* @param string $prefix * @param string $prefix
* @param array $args * @param array $args
* @param array $column_list * @param array $column_list
@ -67,7 +67,7 @@ class Query extends VariableBase
$this->_args = $args; $this->_args = $args;
$this->_column_list = $column_list; $this->_column_list = $column_list;
$this->_params = array(); $this->_params = array();
// Call different internal methods depending on the query type. // Call different internal methods depending on the query type.
switch ($this->type) switch ($this->type)
{ {
@ -86,37 +86,37 @@ class Query extends VariableBase
default: default:
$result = ''; $result = '';
} }
// Reset state and return the result. // Reset state and return the result.
$this->_prefix = ''; $this->_prefix = '';
$this->_args = array(); $this->_args = array();
$this->_column_list = array(); $this->_column_list = array();
return $result; return $result;
} }
/** /**
* Get the query parameters to use with the query string generated above. * Get the query parameters to use with the query string generated above.
* *
* @return array * @return array
*/ */
public function getQueryParams() public function getQueryParams()
{ {
return $this->_params; return $this->_params;
} }
/** /**
* Check if this query requires pagination. * Check if this query requires pagination.
* *
* @return bool * @return bool
*/ */
public function requiresPagination(): bool public function requiresPagination(): bool
{ {
return $this->requires_pagination; return $this->requires_pagination;
} }
/** /**
* Generate a SELECT query string. * Generate a SELECT query string.
* *
* @param int $count_only * @param int $count_only
* @return string * @return string
*/ */
@ -125,7 +125,7 @@ class Query extends VariableBase
// Initialize the query string. // Initialize the query string.
$result = 'SELECT'; $result = 'SELECT';
$has_subquery_columns = false; $has_subquery_columns = false;
// Compose the column list. // Compose the column list.
if ($this->_column_list) if ($this->_column_list)
{ {
@ -168,7 +168,7 @@ class Query extends VariableBase
} }
$column_list = implode(', ', $columns); $column_list = implode(', ', $columns);
} }
// Replace the column list if this is a count-only query. // Replace the column list if this is a count-only query.
if ($count_only == 1) if ($count_only == 1)
{ {
@ -187,7 +187,7 @@ class Query extends VariableBase
$count_wrap = false; $count_wrap = false;
$result .= ($this->select_distinct ? ' DISTINCT ' : ' ') . $column_list; $result .= ($this->select_distinct ? ' DISTINCT ' : ' ') . $column_list;
} }
// Compose the FROM clause. // Compose the FROM clause.
if (count($this->tables)) if (count($this->tables))
{ {
@ -205,7 +205,7 @@ class Query extends VariableBase
$result .= ' ' . $index_hints; $result .= ' ' . $index_hints;
} }
} }
// Compose the WHERE clause. // Compose the WHERE clause.
if (count($this->conditions)) if (count($this->conditions))
{ {
@ -215,7 +215,7 @@ class Query extends VariableBase
$result .= ' WHERE ' . $where; $result .= ' WHERE ' . $where;
} }
} }
// Compose the GROUP BY clause. // Compose the GROUP BY clause.
if ($this->groupby && count($this->groupby->columns) && (!$this->groupby->ifvar || isset($this->_args[$this->groupby->ifvar]))) if ($this->groupby && count($this->groupby->columns) && (!$this->groupby->ifvar || isset($this->_args[$this->groupby->ifvar])))
{ {
@ -241,13 +241,13 @@ class Query extends VariableBase
$result .= ' HAVING ' . $having; $result .= ' HAVING ' . $having;
} }
} }
// Compose the ORDER BY clause. // Compose the ORDER BY clause.
if ($this->navigation && count($this->navigation->orderby) && !$count_only) if ($this->navigation && count($this->navigation->orderby) && !$count_only)
{ {
$result .= ' ORDER BY ' . $this->_arrangeOrderBy($this->navigation); $result .= ' ORDER BY ' . $this->_arrangeOrderBy($this->navigation);
} }
// Compose the LIMIT/OFFSET clause. // Compose the LIMIT/OFFSET clause.
if ($this->navigation && $this->navigation->list_count && !$count_only) if ($this->navigation && $this->navigation->list_count && !$count_only)
{ {
@ -257,27 +257,27 @@ class Query extends VariableBase
$result .= ' LIMIT ' . $limit_offset; $result .= ' LIMIT ' . $limit_offset;
} }
} }
// Wrap in a subquery if necesary. // Wrap in a subquery if necesary.
if ($count_wrap) if ($count_wrap)
{ {
$result = 'SELECT COUNT(*) AS `count` FROM (' . $result . ') AS `subquery`'; $result = 'SELECT COUNT(*) AS `count` FROM (' . $result . ') AS `subquery`';
} }
// Return the final query string. // Return the final query string.
return $result; return $result;
} }
/** /**
* Generate a INSERT query string. * Generate a INSERT query string.
* *
* @return string * @return string
*/ */
protected function _getInsertQueryString(): string protected function _getInsertQueryString(): string
{ {
// Initialize the query string. // Initialize the query string.
$result = 'INSERT'; $result = 'INSERT';
// Compose the INTO clause. // Compose the INTO clause.
if (count($this->tables)) if (count($this->tables))
{ {
@ -287,7 +287,7 @@ class Query extends VariableBase
$result .= ' INTO ' . $tables; $result .= ' INTO ' . $tables;
} }
} }
// Process the SET clause with new values. // Process the SET clause with new values.
$columns = array(); $columns = array();
foreach ($this->columns as $column) foreach ($this->columns as $column)
@ -296,7 +296,7 @@ class Query extends VariableBase
{ {
continue; continue;
} }
$setval_string = $this->_parseCondition($column); $setval_string = $this->_parseCondition($column);
if ($setval_string !== '') if ($setval_string !== '')
{ {
@ -304,7 +304,7 @@ class Query extends VariableBase
} }
} }
$result .= ' SET ' . implode(', ', $columns); $result .= ' SET ' . implode(', ', $columns);
// Process the ON DUPLICATE KEY UPDATE (upsert) clause. // Process the ON DUPLICATE KEY UPDATE (upsert) clause.
if ($this->update_duplicate && count($columns)) if ($this->update_duplicate && count($columns))
{ {
@ -315,21 +315,21 @@ class Query extends VariableBase
$this->_params[] = $param; $this->_params[] = $param;
} }
} }
// Return the final query string. // Return the final query string.
return $result; return $result;
} }
/** /**
* Generate a UPDATE query string. * Generate a UPDATE query string.
* *
* @return string * @return string
*/ */
protected function _getUpdateQueryString(): string protected function _getUpdateQueryString(): string
{ {
// Initialize the query string. // Initialize the query string.
$result = 'UPDATE '; $result = 'UPDATE ';
// Compose the INTO clause. // Compose the INTO clause.
if (count($this->tables)) if (count($this->tables))
{ {
@ -339,7 +339,7 @@ class Query extends VariableBase
$result .= $tables; $result .= $tables;
} }
} }
// Compose the SET clause with updated values. // Compose the SET clause with updated values.
$columns = array(); $columns = array();
foreach ($this->columns as $column) foreach ($this->columns as $column)
@ -348,7 +348,7 @@ class Query extends VariableBase
{ {
continue; continue;
} }
$setval_string = $this->_parseCondition($column); $setval_string = $this->_parseCondition($column);
if ($setval_string !== '') if ($setval_string !== '')
{ {
@ -356,7 +356,7 @@ class Query extends VariableBase
} }
} }
$result .= ' SET ' . implode(', ', $columns); $result .= ' SET ' . implode(', ', $columns);
// Compose the WHERE clause. // Compose the WHERE clause.
if (count($this->conditions)) if (count($this->conditions))
{ {
@ -366,21 +366,21 @@ class Query extends VariableBase
$result .= ' WHERE ' . $where; $result .= ' WHERE ' . $where;
} }
} }
// Return the final query string. // Return the final query string.
return $result; return $result;
} }
/** /**
* Generate a DELETE query string. * Generate a DELETE query string.
* *
* @return string * @return string
*/ */
protected function _getDeleteQueryString(): string protected function _getDeleteQueryString(): string
{ {
// Initialize the query string. // Initialize the query string.
$result = 'DELETE'; $result = 'DELETE';
// Compose the FROM clause. // Compose the FROM clause.
if (count($this->tables)) if (count($this->tables))
{ {
@ -390,7 +390,7 @@ class Query extends VariableBase
$result .= ' FROM ' . $tables; $result .= ' FROM ' . $tables;
} }
} }
// Compose the WHERE clause. // Compose the WHERE clause.
if (count($this->conditions)) if (count($this->conditions))
{ {
@ -400,13 +400,13 @@ class Query extends VariableBase
$result .= ' WHERE ' . $where; $result .= ' WHERE ' . $where;
} }
} }
// Compose the ORDER BY clause. // Compose the ORDER BY clause.
if ($this->navigation && count($this->navigation->orderby)) if ($this->navigation && count($this->navigation->orderby))
{ {
$result .= ' ORDER BY ' . $this->_arrangeOrderBy($this->navigation); $result .= ' ORDER BY ' . $this->_arrangeOrderBy($this->navigation);
} }
// Compose the LIMIT/OFFSET clause. // Compose the LIMIT/OFFSET clause.
if ($this->navigation && $this->navigation->list_count) if ($this->navigation && $this->navigation->list_count)
{ {
@ -416,14 +416,14 @@ class Query extends VariableBase
$result .= ' LIMIT ' . $limit_offset; $result .= ' LIMIT ' . $limit_offset;
} }
} }
// Return the final query string. // Return the final query string.
return $result; return $result;
} }
/** /**
* Generate a FROM clause from a list of tables. * Generate a FROM clause from a list of tables.
* *
* @param array $tables * @param array $tables
* @param int $use_aliases * @param int $use_aliases
* @return string * @return string
@ -432,7 +432,7 @@ class Query extends VariableBase
{ {
// Initialize the result. // Initialize the result.
$result = array(); $result = array();
// Process each table definition. // Process each table definition.
foreach ($tables as $table) foreach ($tables as $table)
{ {
@ -441,7 +441,7 @@ class Query extends VariableBase
{ {
continue; continue;
} }
// Subquery // Subquery
if ($table instanceof self) if ($table instanceof self)
{ {
@ -456,7 +456,7 @@ class Query extends VariableBase
$this->_params[] = $param; $this->_params[] = $param;
} }
} }
// Regular table // Regular table
else else
{ {
@ -470,7 +470,7 @@ class Query extends VariableBase
$tabledef .= ' AS `' . $table->alias . '`'; $tabledef .= ' AS `' . $table->alias . '`';
} }
} }
// Add join conditions // Add join conditions
if ($table->join_type) if ($table->join_type)
{ {
@ -486,14 +486,14 @@ class Query extends VariableBase
$result[] = (count($result) ? ', ' : '') . $tabledef; $result[] = (count($result) ? ', ' : '') . $tabledef;
} }
} }
// Combine the result and return as a string. // Combine the result and return as a string.
return implode('', $result); return implode('', $result);
} }
/** /**
* Generate index hints. * Generate index hints.
* *
* @param array $index_hints * @param array $index_hints
* @return string * @return string
*/ */
@ -501,7 +501,7 @@ class Query extends VariableBase
{ {
// Initialize the index list by type. // Initialize the index list by type.
$index_list = []; $index_list = [];
// Group each index hint by type. // Group each index hint by type.
foreach ($index_hints as $index_hint) foreach ($index_hints as $index_hint)
{ {
@ -510,7 +510,7 @@ class Query extends VariableBase
{ {
continue; continue;
} }
if (!count($index_hint->target_db) || isset($index_hint->target_db['mysql'])) if (!count($index_hint->target_db) || isset($index_hint->target_db['mysql']))
{ {
$key = $index_hint->hint_type ?: 'USE'; $key = $index_hint->hint_type ?: 'USE';
@ -525,7 +525,7 @@ class Query extends VariableBase
} }
} }
} }
// Generate a list of indexes for each group. // Generate a list of indexes for each group.
$result = []; $result = [];
foreach ($index_list as $key => $val) foreach ($index_list as $key => $val)
@ -537,10 +537,10 @@ class Query extends VariableBase
} }
return implode(' ', $result); return implode(' ', $result);
} }
/** /**
* Generate a WHERE clause from a list of conditions. * Generate a WHERE clause from a list of conditions.
* *
* @param array $conditions * @param array $conditions
* @return string * @return string
*/ */
@ -548,7 +548,7 @@ class Query extends VariableBase
{ {
// Initialize the result. // Initialize the result.
$result = ''; $result = '';
// Process each condition. // Process each condition.
foreach ($conditions as $condition) foreach ($conditions as $condition)
{ {
@ -557,7 +557,7 @@ class Query extends VariableBase
{ {
continue; continue;
} }
// Subquery // Subquery
if ($condition instanceof self) if ($condition instanceof self)
{ {
@ -567,7 +567,7 @@ class Query extends VariableBase
$result .= ($result === '' ? '' : (' ' . $condition->pipe . ' ')) . $condition_string; $result .= ($result === '' ? '' : (' ' . $condition->pipe . ' ')) . $condition_string;
} }
} }
// Condition group // Condition group
elseif ($condition instanceof ConditionGroup) elseif ($condition instanceof ConditionGroup)
{ {
@ -577,7 +577,7 @@ class Query extends VariableBase
$result .= ($result === '' ? '' : (' ' . $condition->pipe . ' ')) . '(' . $condition_string . ')'; $result .= ($result === '' ? '' : (' ' . $condition->pipe . ' ')) . '(' . $condition_string . ')';
} }
} }
// Simple condition // Simple condition
else else
{ {
@ -588,14 +588,14 @@ class Query extends VariableBase
} }
} }
} }
// Return the WHERE clause. // Return the WHERE clause.
return $result; return $result;
} }
/** /**
* Generate a ORDER BY clause from navigation settings. * Generate a ORDER BY clause from navigation settings.
* *
* @param object $navigation * @param object $navigation
* @return string * @return string
*/ */
@ -603,7 +603,7 @@ class Query extends VariableBase
{ {
// Initialize the result. // Initialize the result.
$result = array(); $result = array();
// Process each column definition. // Process each column definition.
foreach ($navigation->orderby as $orderby) foreach ($navigation->orderby as $orderby)
{ {
@ -618,7 +618,7 @@ class Query extends VariableBase
{ {
$column_name = self::quoteName($column_name); $column_name = self::quoteName($column_name);
} }
// Get the ordering (ASC or DESC). // Get the ordering (ASC or DESC).
if (preg_match('/^(ASC|DESC)$/i', $orderby->order_var, $matches)) if (preg_match('/^(ASC|DESC)$/i', $orderby->order_var, $matches))
{ {
@ -632,17 +632,17 @@ class Query extends VariableBase
{ {
$column_order = preg_replace('/[^A-Z]/', '', strtoupper($orderby->order_default)); $column_order = preg_replace('/[^A-Z]/', '', strtoupper($orderby->order_default));
} }
$result[] = $column_name . ' ' . $column_order; $result[] = $column_name . ' ' . $column_order;
} }
// Return the ORDER BY clause. // Return the ORDER BY clause.
return implode(', ', $result); return implode(', ', $result);
} }
/** /**
* Generate a LIMIT/OFFSET clause from navigation settings. * Generate a LIMIT/OFFSET clause from navigation settings.
* *
* @param object $navigation * @param object $navigation
* @return string * @return string
*/ */
@ -656,7 +656,7 @@ class Query extends VariableBase
} }
$page = 0; $page = 0;
$offset = 0; $offset = 0;
// Get the offset from the page or offset variable. // Get the offset from the page or offset variable.
if ($navigation->page) if ($navigation->page)
{ {
@ -666,7 +666,7 @@ class Query extends VariableBase
{ {
list($is_expression, $offset) = $navigation->offset->getValue($this->_args); list($is_expression, $offset) = $navigation->offset->getValue($this->_args);
} }
// If page is available, set the offset and require pagination for this query. // If page is available, set the offset and require pagination for this query.
if ($page > 0) if ($page > 0)
{ {
@ -680,14 +680,14 @@ class Query extends VariableBase
{ {
$page = 1; $page = 1;
} }
// Return the LIMIT/OFFSET clause. // Return the LIMIT/OFFSET clause.
return ($offset > 0 ? (intval($offset) . ', ') : '') . intval($list_count); return ($offset > 0 ? (intval($offset) . ', ') : '') . intval($list_count);
} }
/** /**
* Generate each condition in a WHERE clause. * Generate each condition in a WHERE clause.
* *
* @param object $condition * @param object $condition
* @return string * @return string
*/ */
@ -700,10 +700,10 @@ class Query extends VariableBase
} }
return $where; return $where;
} }
/** /**
* Quote a column name. * Quote a column name.
* *
* @param string $column_name * @param string $column_name
* @return string * @return string
*/ */
@ -717,10 +717,10 @@ class Query extends VariableBase
return implode('.', $columns); return implode('.', $columns);
}, $column_name); }, $column_name);
} }
/** /**
* Check if a column name is valid. * Check if a column name is valid.
* *
* @param string $column_name * @param string $column_name
* @return bool * @return bool
*/ */
@ -728,10 +728,10 @@ class Query extends VariableBase
{ {
return preg_match('/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/i', $column_name) ? true : false; return preg_match('/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/i', $column_name) ? true : false;
} }
/** /**
* Check if a variable is considered valid for XE compatibility. * Check if a variable is considered valid for XE compatibility.
* *
* @param mixed $var * @param mixed $var
* @param bool $allow_empty_string * @param bool $allow_empty_string
* @return bool * @return bool
@ -742,7 +742,7 @@ class Query extends VariableBase
{ {
return false; return false;
} }
if (is_array($var)) if (is_array($var))
{ {
$count = count($var); $count = count($var);
@ -751,7 +751,7 @@ class Query extends VariableBase
return false; return false;
} }
} }
return true; return true;
} }
} }

View file

@ -13,10 +13,10 @@ class VariableBase
public $var; public $var;
public $ifvar; public $ifvar;
public $default; public $default;
/** /**
* Convert an operator into real SQL. * Convert an operator into real SQL.
* *
* @param array $args * @param array $args
* @param string $prefix * @param string $prefix
* @return array * @return array
@ -28,11 +28,11 @@ class VariableBase
{ {
throw new \Rhymix\Framework\Exceptions\QueryError('Invalid invocation of getQueryStringAndParams()'); throw new \Rhymix\Framework\Exceptions\QueryError('Invalid invocation of getQueryStringAndParams()');
} }
// Initialze the return values. // Initialze the return values.
$where = ''; $where = '';
$params = array(); $params = array();
// Process the variable or default value. // Process the variable or default value.
if ($this->ifvar && !isset($args[$this->ifvar])) if ($this->ifvar && !isset($args[$this->ifvar]))
{ {
@ -95,23 +95,23 @@ class VariableBase
{ {
return [$where, $params]; return [$where, $params];
} }
// Quote the column name. // Quote the column name.
$column = Query::quoteName(isset($this->column) ? $this->column : $this->name); $column = Query::quoteName(isset($this->column) ? $this->column : $this->name);
// Prepare the target value. // Prepare the target value.
$list_ops = array('in' => true, 'notin' => true, 'not_in' => true, 'between' => true); $list_ops = array('in' => true, 'notin' => true, 'not_in' => true, 'between' => true);
if (isset($list_ops[$this->operation]) && !$is_expression && !is_array($value) && $value !== '') if (isset($list_ops[$this->operation]) && !$is_expression && !is_array($value) && $value !== '')
{ {
$value = explode(',', preg_replace('/[\s\']/', '', $value)); $value = explode(',', preg_replace('/[\s\']/', '', $value));
} }
// Restrict operators for write queries. // Restrict operators for write queries.
if ($this instanceof ColumnWrite && $this->operation && !in_array($this->operation, ['equal', 'plus', 'minus', 'multiply'])) if ($this instanceof ColumnWrite && $this->operation && !in_array($this->operation, ['equal', 'plus', 'minus', 'multiply']))
{ {
throw new \Rhymix\Framework\Exceptions\QueryError('Operation ' . $this->operation . ' is not valid for column in an INSERT or UPDATE query'); throw new \Rhymix\Framework\Exceptions\QueryError('Operation ' . $this->operation . ' is not valid for column in an INSERT or UPDATE query');
} }
// Apply the operator. // Apply the operator.
switch ($this->operation) switch ($this->operation)
{ {
@ -273,14 +273,14 @@ class VariableBase
$where = sprintf('%s = ?', $column); $where = sprintf('%s = ?', $column);
$params[] = $value; $params[] = $value;
} }
// Return the complete condition and parameters. // Return the complete condition and parameters.
return [$where, $params]; return [$where, $params];
} }
/** /**
* Get the current value, falling back to the default value if necessary. * Get the current value, falling back to the default value if necessary.
* *
* @param array $args * @param array $args
* @return array * @return array
*/ */
@ -315,20 +315,20 @@ class VariableBase
$is_expression = null; $is_expression = null;
$value = null; $value = null;
} }
return [$is_expression, $value]; return [$is_expression, $value];
} }
/** /**
* Get the default value of this variable. * Get the default value of this variable.
* *
* @return array * @return array
*/ */
public function getDefaultValue() public function getDefaultValue()
{ {
// Get the current column name. // Get the current column name.
$column = $this instanceof ColumnWrite ? $this->name : ($this->column ?? null); $column = $this instanceof ColumnWrite ? $this->name : ($this->column ?? null);
// If the default value is a column name, escape it. // If the default value is a column name, escape it.
if (strpos($this->default, '.') !== false && Query::isValidColumnName($this->default)) if (strpos($this->default, '.') !== false && Query::isValidColumnName($this->default))
{ {
@ -338,7 +338,7 @@ class VariableBase
{ {
return [true, Query::quoteName($this->default)]; return [true, Query::quoteName($this->default)];
} }
// If the default value is a function shortcut, return an appropriate value. // If the default value is a function shortcut, return an appropriate value.
switch ($this->default) switch ($this->default)
{ {
@ -363,7 +363,7 @@ class VariableBase
case 'null': case 'null':
return [true, 'NULL']; return [true, 'NULL'];
} }
// If the default value is a calculation based on the current value, return a query string. // If the default value is a calculation based on the current value, return a query string.
if (isset($column) && preg_match('/^(plus|minus|multiply|divide|timestamp)\(([^)]+)\)$/', $this->default, $matches)) if (isset($column) && preg_match('/^(plus|minus|multiply|divide|timestamp)\(([^)]+)\)$/', $this->default, $matches))
{ {
@ -379,14 +379,14 @@ class VariableBase
return [false, date($matches[2])]; return [false, date($matches[2])];
} }
} }
// Otherwise, just return the literal value. // Otherwise, just return the literal value.
return [false, $this->default]; return [false, $this->default];
} }
/** /**
* Filter a value. * Filter a value.
* *
* @param mixed $value * @param mixed $value
* @return void * @return void
*/ */
@ -399,7 +399,7 @@ class VariableBase
{ {
$filter = ''; $filter = '';
} }
// Apply filters. // Apply filters.
switch ($filter) switch ($filter)
{ {
@ -445,7 +445,7 @@ class VariableBase
} }
break; break;
} }
// Check minimum and maximum lengths. // Check minimum and maximum lengths.
$length = is_scalar($value) ? iconv_strlen($value, 'UTF-8') : (is_countable($value) ? count($value) : 1); $length = is_scalar($value) ? iconv_strlen($value, 'UTF-8') : (is_countable($value) ? count($value) : 1);
if (isset($this->minlength) && $this->minlength > 0 && $length < $this->minlength) if (isset($this->minlength) && $this->minlength > 0 && $length < $this->minlength)
@ -457,10 +457,10 @@ class VariableBase
throw new \Rhymix\Framework\Exceptions\QueryError('Variable ' . $this->var . ' for column ' . $column . ' must contain no more than ' . $this->maxlength . ' characters'); throw new \Rhymix\Framework\Exceptions\QueryError('Variable ' . $this->var . ' for column ' . $column . ' must contain no more than ' . $this->maxlength . ' characters');
} }
} }
/** /**
* Parse the search text. * Parse the search text.
* *
* @param string $column * @param string $column
* @param string $value * @param string $value
* @return array * @return array
@ -470,13 +470,13 @@ class VariableBase
// Initialze the return values. // Initialze the return values.
$where = ''; $where = '';
$params = array(); $params = array();
// parse the value (text); // parse the value (text);
$value = str_replace('&quot;', '"', $value); $value = str_replace('&quot;', '"', $value);
$keywords = preg_split('/(\([^\)]*?\))|(\-?\"[^\"]*?\")|[\s,]+/', trim($value), 10, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); $keywords = preg_split('/(\([^\)]*?\))|(\-?\"[^\"]*?\")|[\s,]+/', trim($value), 10, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
$conditions = array(); $conditions = array();
$operators = array('AND' => 'AND', 'OR' => 'OR', '|' => 'OR'); $operators = array('AND' => 'AND', 'OR' => 'OR', '|' => 'OR');
// loop the parsed keywords or operators // loop the parsed keywords or operators
foreach ($keywords as $item) foreach ($keywords as $item)
{ {
@ -486,7 +486,7 @@ class VariableBase
{ {
continue; continue;
} }
// treat parenthesis // treat parenthesis
if (substr($item, 0, 1) === '(' && substr($item, -1) === ')') if (substr($item, 0, 1) === '(' && substr($item, -1) === ')')
{ {
@ -500,7 +500,7 @@ class VariableBase
} }
continue; continue;
} }
// process 'AND' or 'OR' operator // process 'AND' or 'OR' operator
if (isset($operators[$item])) if (isset($operators[$item]))
{ {
@ -519,26 +519,26 @@ class VariableBase
{ {
$conditions[] = sprintf('%s LIKE ?', $column); $conditions[] = sprintf('%s LIKE ?', $column);
} }
// trim quotation mark // trim quotation mark
if (preg_match('/^"(.*)"$/', $item, $matches)) if (preg_match('/^"(.*)"$/', $item, $matches))
{ {
$item = $matches[1]; $item = $matches[1];
} }
// Escape and add to parameter list // Escape and add to parameter list
$params[] = '%' . str_replace(['"', '\\', '_', '%'], ['&quot;', '\\\\', '\_', '\%'], $item) . '%'; $params[] = '%' . str_replace(['"', '\\', '_', '%'], ['&quot;', '\\\\', '\_', '\%'], $item) . '%';
// if there is no operator, assume 'AND' // if there is no operator, assume 'AND'
$conditions[] = 'AND'; $conditions[] = 'AND';
} }
} }
// remove the last point (would be an operator) // remove the last point (would be an operator)
array_pop($conditions); array_pop($conditions);
$conditions = implode(' ', $conditions); $conditions = implode(' ', $conditions);
$where = count($keywords) === 1 ? $conditions : "($conditions)"; $where = count($keywords) === 1 ? $conditions : "($conditions)";
return [$where, $params]; return [$where, $params];
} }
} }

View file

@ -13,10 +13,10 @@ class Table
public $primary_key = array(); public $primary_key = array();
public $constraints = array(); public $constraints = array();
public $deleted = false; public $deleted = false;
/** /**
* Generate the CREATE TABLE query for this table. * Generate the CREATE TABLE query for this table.
* *
* @param string $prefix * @param string $prefix
* @param string $charset * @param string $charset
* @param string $engine * @param string $engine
@ -26,7 +26,7 @@ class Table
{ {
// Initialize the query. // Initialize the query.
$result = 'CREATE TABLE `' . $prefix . $this->name . '` ('; $result = 'CREATE TABLE `' . $prefix . $this->name . '` (';
// Add columns. // Add columns.
$columns = array(); $columns = array();
$adjusted_sizes = array(); $adjusted_sizes = array();
@ -74,7 +74,7 @@ class Table
} }
$columns[] = $columndef; $columns[] = $columndef;
} }
// Add indexes. // Add indexes.
if (count($this->primary_key)) if (count($this->primary_key))
{ {
@ -106,7 +106,7 @@ class Table
} }
$columns[] = $idxdef; $columns[] = $idxdef;
} }
// Add constraints. // Add constraints.
foreach ($this->constraints as $constraint) foreach ($this->constraints as $constraint)
{ {
@ -125,7 +125,7 @@ class Table
} }
$columns[] = $condef; $columns[] = $condef;
} }
// Finish the query. // Finish the query.
$footer = ''; $footer = '';
if ($engine) if ($engine)
@ -138,7 +138,7 @@ class Table
} }
$result .= "\n" . implode(",\n", $columns); $result .= "\n" . implode(",\n", $columns);
$result .= "\n" . ') ' . $footer . ';'; $result .= "\n" . ') ' . $footer . ';';
return $result; return $result;
} }
} }

View file

@ -2,13 +2,13 @@
/** /**
* Function library for Rhymix * Function library for Rhymix
* *
* Copyright (c) Rhymix Developers and Contributors * Copyright (c) Rhymix Developers and Contributors
*/ */
/** /**
* Get or set system configuration. * Get or set system configuration.
* *
* @param string $key * @param string $key
* @param string $value (optional) * @param string $value (optional)
* @return mixed * @return mixed
@ -39,7 +39,7 @@ function lang($code, $value = null)
$GLOBALS['lang'] = Rhymix\Framework\Lang::getInstance(Context::getLangType() ?: config('locale.default_lang') ?: 'ko'); $GLOBALS['lang'] = Rhymix\Framework\Lang::getInstance(Context::getLangType() ?: config('locale.default_lang') ?: 'ko');
$GLOBALS['lang']->loadDirectory(RX_BASEDIR . 'common/lang', 'common'); $GLOBALS['lang']->loadDirectory(RX_BASEDIR . 'common/lang', 'common');
} }
if ($value === null) if ($value === null)
{ {
return $GLOBALS['lang']->get($code); return $GLOBALS['lang']->get($code);
@ -52,7 +52,7 @@ function lang($code, $value = null)
/** /**
* Get the first value of an array. * Get the first value of an array.
* *
* @param array $array The input array * @param array $array The input array
* @return mixed * @return mixed
*/ */
@ -63,7 +63,7 @@ function array_first(array $array)
/** /**
* Get the first key of an array. * Get the first key of an array.
* *
* @param array $array The input array * @param array $array The input array
* @return mixed * @return mixed
*/ */
@ -75,7 +75,7 @@ function array_first_key(array $array)
/** /**
* Get the last value of an array. * Get the last value of an array.
* *
* @param array $array The input array * @param array $array The input array
* @return mixed * @return mixed
*/ */
@ -86,7 +86,7 @@ function array_last(array $array)
/** /**
* Get the last key of an array. * Get the last key of an array.
* *
* @param array $array The input array * @param array $array The input array
* @return mixed * @return mixed
*/ */
@ -98,7 +98,7 @@ function array_last_key(array $array)
/** /**
* Escape all keys and values in a multi-dimensional array. * Escape all keys and values in a multi-dimensional array.
* *
* @param array $array The array to escape * @param array $array The array to escape
* @param bool $double_escape Set this to false to skip symbols that are already escaped (default: true) * @param bool $double_escape Set this to false to skip symbols that are already escaped (default: true)
* @return array * @return array
@ -153,7 +153,7 @@ function array_flatten(array $array, $preserve_keys = true)
/** /**
* Get the base name of a class name (without namespaces). * Get the base name of a class name (without namespaces).
* Based on Laravel helper function <http://laravel.com/docs/5.0/helpers> * Based on Laravel helper function <http://laravel.com/docs/5.0/helpers>
* *
* @param string|object $class The class name * @param string|object $class The class name
* @return string * @return string
*/ */
@ -164,9 +164,9 @@ function class_basename($class)
/** /**
* Clean a path to remove ./, ../, trailing slashes, etc. * Clean a path to remove ./, ../, trailing slashes, etc.
* *
* This function is an alias to Rhymix\Framework\Filters\FilenameFilter::cleanPath(). * This function is an alias to Rhymix\Framework\Filters\FilenameFilter::cleanPath().
* *
* @param string $path * @param string $path
* @return string * @return string
*/ */
@ -177,7 +177,7 @@ function clean_path($path)
/** /**
* This function is a shortcut to htmlspecialchars(). * This function is a shortcut to htmlspecialchars().
* *
* @param string $str The string to escape * @param string $str The string to escape
* @param bool $double_escape Set this to false to skip symbols that are already escaped (default: true) * @param bool $double_escape Set this to false to skip symbols that are already escaped (default: true)
* @param bool $except_lang_code Set this to true to skip user lang codes (default: false) * @param bool $except_lang_code Set this to true to skip user lang codes (default: false)
@ -199,7 +199,7 @@ function escape($str, $double_escape = true, $except_lang_code = false)
/** /**
* This function escapes a string to be used in a CSS property. * This function escapes a string to be used in a CSS property.
* *
* @param string $str The string to escape * @param string $str The string to escape
* @return string * @return string
*/ */
@ -210,7 +210,7 @@ function escape_css($str)
/** /**
* This function escapes a string to be used in a JavaScript string literal. * This function escapes a string to be used in a JavaScript string literal.
* *
* @param string $str The string to escape * @param string $str The string to escape
* @return string * @return string
*/ */
@ -224,7 +224,7 @@ function escape_js($str)
/** /**
* This function escapes a string to be used in a 'single-quoted' PHP string literal. * This function escapes a string to be used in a 'single-quoted' PHP string literal.
* Null bytes are removed. * Null bytes are removed.
* *
* @param string $str The string to escape * @param string $str The string to escape
* @return string * @return string
*/ */
@ -236,7 +236,7 @@ function escape_sqstr($str)
/** /**
* This function escapes a string to be used in a "double-quoted" PHP string literal. * This function escapes a string to be used in a "double-quoted" PHP string literal.
* Null bytes are removed. * Null bytes are removed.
* *
* @param string $str The string to escape * @param string $str The string to escape
* @return string * @return string
*/ */
@ -249,7 +249,7 @@ function escape_dqstr($str)
* This function splits a string into an array, but allows the delimter to be escaped. * This function splits a string into an array, but allows the delimter to be escaped.
* For example, 'A|B\|C|D' will be split into 'A', 'B|C', and 'D' * For example, 'A|B\|C|D' will be split into 'A', 'B|C', and 'D'
* because the bar between B and C is escaped. * because the bar between B and C is escaped.
* *
* @param string $delimiter The delimiter * @param string $delimiter The delimiter
* @param string $str The string to split * @param string $str The string to split
* @param int $limit The maximum number of items to return, 0 for unlimited (default: 0) * @param int $limit The maximum number of items to return, 0 for unlimited (default: 0)
@ -274,7 +274,7 @@ function explode_with_escape($delimiter, $str, $limit = 0, $escape_char = '\\')
/** /**
* This function returns true if $haystack starts with $needle, and false otherwise. * This function returns true if $haystack starts with $needle, and false otherwise.
* *
* @param string $needle The needle * @param string $needle The needle
* @param string $haystack The haystack * @param string $haystack The haystack
* @param bool $case_sensitive Whether the search should be case-sensitive (default: true) * @param bool $case_sensitive Whether the search should be case-sensitive (default: true)
@ -298,7 +298,7 @@ function starts_with($needle, $haystack, $case_sensitive = true)
/** /**
* This function returns true if $haystack ends with $needle, and false otherwise. * This function returns true if $haystack ends with $needle, and false otherwise.
* *
* @param string $needle The needle * @param string $needle The needle
* @param string $haystack The haystack * @param string $haystack The haystack
* @param bool $case_sensitive Whether the search should be case-sensitive (default: true) * @param bool $case_sensitive Whether the search should be case-sensitive (default: true)
@ -322,7 +322,7 @@ function ends_with($needle, $haystack, $case_sensitive = true)
/** /**
* This function returns true if $haystack contains $needle, and false otherwise. * This function returns true if $haystack contains $needle, and false otherwise.
* *
* @param string $needle The needle * @param string $needle The needle
* @param string $haystack The haystack * @param string $haystack The haystack
* @param bool $case_sensitive Whether the search should be case-sensitive (default: true) * @param bool $case_sensitive Whether the search should be case-sensitive (default: true)
@ -347,7 +347,7 @@ function contains($needle, $haystack, $case_sensitive = true)
/** /**
* This function returns true if $needle is between $min and $max, and false otherwise. * This function returns true if $needle is between $min and $max, and false otherwise.
* Non-numeric values are compared according to PHP defaults. * Non-numeric values are compared according to PHP defaults.
* *
* @param mixed $needle The needle * @param mixed $needle The needle
* @param mixed $min The minimum value * @param mixed $min The minimum value
* @param mixed $max The maximum value * @param mixed $max The maximum value
@ -370,7 +370,7 @@ function is_between($needle, $min, $max, $exclusive = false)
* This function restricts $input to be between $min and $max. * This function restricts $input to be between $min and $max.
* All values less than $min are converted to $min, and all values greater than $max are converted to $max. * All values less than $min are converted to $min, and all values greater than $max are converted to $max.
* Non-numeric values are compared according to PHP defaults. * Non-numeric values are compared according to PHP defaults.
* *
* @param mixed $input The value to convert * @param mixed $input The value to convert
* @param mixed $min The minimum value * @param mixed $min The minimum value
* @param mixed $max The maximum value * @param mixed $max The maximum value
@ -385,10 +385,10 @@ function force_range($input, $min, $max)
/** /**
* This function encodes a string with base64, using a URL-safe character set. * This function encodes a string with base64, using a URL-safe character set.
* *
* The choice of alternative characters is defined in RFC 4648 Section 5. * The choice of alternative characters is defined in RFC 4648 Section 5.
* Do not use substitute other characters such as the dot (.) or the tilde (~). * Do not use substitute other characters such as the dot (.) or the tilde (~).
* *
* @param string $str The string to encode * @param string $str The string to encode
* @return string * @return string
*/ */
@ -399,7 +399,7 @@ function base64_encode_urlsafe($str)
/** /**
* This function decodes a string with base64, using a URL-safe character set. * This function decodes a string with base64, using a URL-safe character set.
* *
* @param string $str The string to decode * @param string $str The string to decode
* @return string * @return string
*/ */
@ -439,10 +439,10 @@ function number_shorten($number, $significant_digits = 2)
/** /**
* Convert a server-side path to a URL. * Convert a server-side path to a URL.
* *
* This function is an alias to Rhymix\Framework\URL::fromServerPath(). * This function is an alias to Rhymix\Framework\URL::fromServerPath().
* It returns false if the path cannot be converted. * It returns false if the path cannot be converted.
* *
* @param string $path * @param string $path
* @return string|false * @return string|false
*/ */
@ -453,10 +453,10 @@ function path2url($path)
/** /**
* Convert a URL to a server-side path. * Convert a URL to a server-side path.
* *
* This function is an alias to Rhymix\Framework\URL::toServerPath(). * This function is an alias to Rhymix\Framework\URL::toServerPath().
* It returns false if the URL cannot be converted. * It returns false if the URL cannot be converted.
* *
* @param string $url * @param string $url
* @return string|false * @return string|false
*/ */
@ -469,7 +469,7 @@ function url2path($url)
* Convert hexadecimal color codes to an array of R, G, B values. * Convert hexadecimal color codes to an array of R, G, B values.
* This function can handle both 6-digit and 3-digit notations, optionally prefixed with '#'. * This function can handle both 6-digit and 3-digit notations, optionally prefixed with '#'.
* If the color code is illegal, this function will return all nulls. * If the color code is illegal, this function will return all nulls.
* *
* @param string $hex The color to convert * @param string $hex The color to convert
* @return array * @return array
*/ */
@ -498,7 +498,7 @@ function hex2rgb($hex)
/** /**
* Convert an array of R, G, B values to hexadecimal color codes. * Convert an array of R, G, B values to hexadecimal color codes.
* If the RGB values are illegal, this function will return #000000. * If the RGB values are illegal, this function will return #000000.
* *
* @param array $rgb The color to convert * @param array $rgb The color to convert
* @param bool $hash_prefix Whether or not to prefix the result with '#' (default: true) * @param bool $hash_prefix Whether or not to prefix the result with '#' (default: true)
* @return string * @return string
@ -519,7 +519,7 @@ function rgb2hex(array $rgb, $hash_prefix = true)
/** /**
* This function includes another file in a clean scope. * This function includes another file in a clean scope.
* This is useful if the included file tries to define global variables. * This is useful if the included file tries to define global variables.
* *
* @param string $filename The name of the file to include * @param string $filename The name of the file to include
* @return mixed * @return mixed
*/ */
@ -530,7 +530,7 @@ function include_in_clean_scope($filename)
/** /**
* This function includes another file while ignoring all errors inside of it. * This function includes another file while ignoring all errors inside of it.
* *
* @param string $filename The name of the file to include * @param string $filename The name of the file to include
* @return mixed * @return mixed
*/ */
@ -544,7 +544,7 @@ function include_and_ignore_errors($filename)
/** /**
* This function includes another file while ignoring all output. * This function includes another file while ignoring all output.
* *
* @param string $filename The name of the file to include * @param string $filename The name of the file to include
* @return mixed * @return mixed
*/ */
@ -559,7 +559,7 @@ function include_and_ignore_output($filename)
/** /**
* Converts any value to either true or false. * Converts any value to either true or false.
* Based on util.php <https://github.com/brandonwamboldt/utilphp> * Based on util.php <https://github.com/brandonwamboldt/utilphp>
* *
* @param string $input The input value * @param string $input The input value
* @return bool * @return bool
*/ */
@ -575,7 +575,7 @@ function tobool($input)
/** /**
* Counts members of an array or an object. * Counts members of an array or an object.
* *
* @deprecated * @deprecated
* @param mixed $array_or_object * @param mixed $array_or_object
* @return int * @return int
@ -598,7 +598,7 @@ function countobj($array_or_object)
/** /**
* Checks if the given string contains valid UTF-8. * Checks if the given string contains valid UTF-8.
* *
* @param string $str The input string * @param string $str The input string
* @return bool * @return bool
*/ */
@ -616,7 +616,7 @@ function utf8_check($str)
/** /**
* Remove BOM and invalid UTF-8 sequences from text content. * Remove BOM and invalid UTF-8 sequences from text content.
* *
* @param string $str * @param string $str
* @return string * @return string
*/ */
@ -627,29 +627,29 @@ function utf8_clean($str)
{ {
$str = @iconv('UTF-8', 'UTF-8//IGNORE', $str); $str = @iconv('UTF-8', 'UTF-8//IGNORE', $str);
} }
// Normalize the text content. // Normalize the text content.
if (class_exists('Normalizer')) if (class_exists('Normalizer'))
{ {
$str = Normalizer::normalize($str, Normalizer::FORM_C); $str = Normalizer::normalize($str, Normalizer::FORM_C);
} }
// Remove BOM. // Remove BOM.
$str = preg_replace('/\xEF\xBB\xBF/', '', $str); $str = preg_replace('/\xEF\xBB\xBF/', '', $str);
// Remove Hangul Filler and RLO character. // Remove Hangul Filler and RLO character.
$str = preg_replace('/(?:&#(?:8238|x202e|12644|x3164);|\xE3\x85\xA4|\xE2\x80\xAE)/i', '', $str); $str = preg_replace('/(?:&#(?:8238|x202e|12644|x3164);|\xE3\x85\xA4|\xE2\x80\xAE)/i', '', $str);
// Remove excessively long sequences (more than 3) of combining diacritical marks. // Remove excessively long sequences (more than 3) of combining diacritical marks.
$str = preg_replace('/(\pM{3})\pM+/u', '$1', $str); $str = preg_replace('/(\pM{3})\pM+/u', '$1', $str);
return $str; return $str;
} }
/** /**
* Encode UTF-8 characters outside of the Basic Multilingual Plane in the &#xxxxxx format. * Encode UTF-8 characters outside of the Basic Multilingual Plane in the &#xxxxxx format.
* This allows emoticons and other characters to be stored in MySQL without utf8mb4 support. * This allows emoticons and other characters to be stored in MySQL without utf8mb4 support.
* *
* @param $str The string to encode * @param $str The string to encode
* @return string * @return string
*/ */
@ -665,7 +665,7 @@ function utf8_mbencode($str)
/** /**
* This function replaces all whitespace characters with a single regular space (0x20). * This function replaces all whitespace characters with a single regular space (0x20).
* Unicode whitespace characters are also replaced. * Unicode whitespace characters are also replaced.
* *
* @param string $str The input string * @param string $str The input string
* @param bool $multiline Set this to true to permit newlines inside the string (default: false) * @param bool $multiline Set this to true to permit newlines inside the string (default: false)
* @return string * @return string
@ -678,7 +678,7 @@ function utf8_normalize_spaces($str, $multiline = false)
/** /**
* This function trims all space from the beginning and end of a string. * This function trims all space from the beginning and end of a string.
* Unicode whitespace characters are also trimmed. * Unicode whitespace characters are also trimmed.
* *
* @param string $str The input string * @param string $str The input string
* @return string * @return string
*/ */
@ -691,7 +691,7 @@ function utf8_trim($str)
* Check if a string contains HTML content. * Check if a string contains HTML content.
* This function checks whether a string seems to contain HTML. * This function checks whether a string seems to contain HTML.
* It checks for tags like <p>, <div>, <br> at the beginning and end of lines. * It checks for tags like <p>, <div>, <br> at the beginning and end of lines.
* *
* @param string $str The input string * @param string $str The input string
* @return bool * @return bool
*/ */
@ -721,7 +721,7 @@ function is_html_content($str)
* Check if HTML content is empty. * Check if HTML content is empty.
* This function checks whether any printable characters remain * This function checks whether any printable characters remain
* after removing all tags except images, videos, iframes, etc. * after removing all tags except images, videos, iframes, etc.
* *
* @param string $str The input string * @param string $str The input string
* @return bool * @return bool
*/ */
@ -734,7 +734,7 @@ function is_empty_html_content($str)
/** /**
* Polyfill for is_countable() in PHP < 7.3 * Polyfill for is_countable() in PHP < 7.3
* *
* @param mixed $var * @param mixed $var
* @return bool * @return bool
**/ **/
@ -748,7 +748,7 @@ if (!function_exists('is_countable'))
/** /**
* Polyfill for str_starts_with() in PHP < 8.0 * Polyfill for str_starts_with() in PHP < 8.0
* *
* @param string $haystack * @param string $haystack
* @param string $needle * @param string $needle
* @return bool * @return bool
@ -763,7 +763,7 @@ if (!function_exists('str_starts_with'))
/** /**
* Polyfill for str_starts_with() in PHP < 8.0 * Polyfill for str_starts_with() in PHP < 8.0
* *
* @param string $haystack * @param string $haystack
* @param string $needle * @param string $needle
* @return bool * @return bool
@ -778,7 +778,7 @@ if (!function_exists('str_ends_with'))
/** /**
* Polyfill for str_starts_with() in PHP < 8.0 * Polyfill for str_starts_with() in PHP < 8.0
* *
* @param string $haystack * @param string $haystack
* @param string $needle * @param string $needle
* @return bool * @return bool

View file

@ -331,7 +331,7 @@ function getNotEncodedFullUrl()
/** /**
* getSiteUrl() returns the URL by transforming the given argument value of domain * getSiteUrl() returns the URL by transforming the given argument value of domain
* The first argument should consist of domain("http://" not included) and path * The first argument should consist of domain("http://" not included) and path
* *
* @return string * @return string
*/ */
function getSiteUrl() function getSiteUrl()
@ -353,7 +353,7 @@ function getSiteUrl()
/** /**
* getSiteUrl() returns the not encoded URL by transforming the given argument value of domain * getSiteUrl() returns the not encoded URL by transforming the given argument value of domain
* The first argument should consist of domain("http://" not included) and path * The first argument should consist of domain("http://" not included) and path
* *
* @return string * @return string
*/ */
function getNotEncodedSiteUrl() function getNotEncodedSiteUrl()
@ -483,7 +483,7 @@ function cut_str($string, $cut_size = 0, $tail = '...')
/** /**
* Convert XE legacy time zone format into UTC offset. * Convert XE legacy time zone format into UTC offset.
* *
* @param string $time_zone Time zone in '+0900' format * @param string $time_zone Time zone in '+0900' format
* @return int * @return int
*/ */
@ -506,13 +506,13 @@ function zgap($timestamp = null)
/** /**
* Convert timestamp string to Unix timestamp. * Convert timestamp string to Unix timestamp.
* This function assumes the internal timezone. * This function assumes the internal timezone.
* *
* Supported formats: * Supported formats:
* - YYYYMMDDHHMMSS * - YYYYMMDDHHMMSS
* - YYYYMMDD * - YYYYMMDD
* - YYYY-MM-DD HH:MM:SS * - YYYY-MM-DD HH:MM:SS
* - YYYY-MM-DDTHH:MM:SS+xx:xx (ISO 8601) * - YYYY-MM-DDTHH:MM:SS+xx:xx (ISO 8601)
* *
* @param string $str Timestamp in one of the supported formats * @param string $str Timestamp in one of the supported formats
* @return int * @return int
*/ */
@ -570,7 +570,7 @@ function ztime($str)
{ {
return null; return null;
} }
$timestamp = gmmktime($hour, $min, $sec, $month, $day, $year); $timestamp = gmmktime($hour, $min, $sec, $month, $day, $year);
if (!$has_offset) if (!$has_offset)
{ {
@ -602,7 +602,7 @@ function zdate($str, $format = 'Y-m-d H:i:s', $conversion = false)
{ {
return null; return null;
} }
// convert the date format according to the language // convert the date format according to the language
if($conversion && $format !== 'relative') if($conversion && $format !== 'relative')
{ {
@ -625,7 +625,7 @@ function zdate($str, $format = 'Y-m-d H:i:s', $conversion = false)
'Y-m-d H:i' => 'H:i d-m-Y', 'Y-m-d H:i' => 'H:i d-m-Y',
), ),
); );
$lang_type = Context::getLangType(); $lang_type = Context::getLangType();
if(isset($convtable[$lang_type])) if(isset($convtable[$lang_type]))
{ {
@ -639,10 +639,10 @@ function zdate($str, $format = 'Y-m-d H:i:s', $conversion = false)
} }
} }
} }
// get unixtime by using ztime() for date() function's argument. // get unixtime by using ztime() for date() function's argument.
$result = Rhymix\Framework\DateTime::formatTimestampForCurrentUser($format, ztime($str)); $result = Rhymix\Framework\DateTime::formatTimestampForCurrentUser($format, ztime($str));
// change day and am/pm for each language // change day and am/pm for each language
if(preg_match('/[MFAa]/', $format)) if(preg_match('/[MFAa]/', $format))
{ {
@ -657,7 +657,7 @@ function zdate($str, $format = 'Y-m-d H:i:s', $conversion = false)
/** /**
* Convert a Unix timestamp to YYYYMMDDHHIISS format, using the internal time zone. * Convert a Unix timestamp to YYYYMMDDHHIISS format, using the internal time zone.
* If the timestamp is not given, the current time is used. * If the timestamp is not given, the current time is used.
* *
* @param int $timestamp Unix timestamp * @param int $timestamp Unix timestamp
* @return string * @return string
*/ */
@ -670,7 +670,7 @@ function getInternalDateTime($timestamp = null, $format = 'YmdHis')
/** /**
* Convert a Unix timestamp to YYYYMMDDHHIISS format, using the internal time zone. * Convert a Unix timestamp to YYYYMMDDHHIISS format, using the internal time zone.
* If the timestamp is not given, the current time is used. * If the timestamp is not given, the current time is used.
* *
* @param int $timestamp Unix timestamp * @param int $timestamp Unix timestamp
* @return string * @return string
*/ */
@ -691,7 +691,7 @@ function getTimeGap($date, $format = 'Y.m.d')
{ {
$timestamp = ztime($date); $timestamp = ztime($date);
$gap = RX_TIME - $timestamp; $gap = RX_TIME - $timestamp;
if ($gap < 60 * 60 * 24) if ($gap < 60 * 60 * 24)
{ {
return Rhymix\Framework\DateTime::getRelativeTimestamp(($gap >= 60) ? $timestamp : (RX_TIME - 60)); return Rhymix\Framework\DateTime::getRelativeTimestamp(($gap >= 60) ? $timestamp : (RX_TIME - 60));
@ -942,7 +942,7 @@ if(!function_exists('hexrgb'))
/** /**
* Php function for mysql old_password() * Php function for mysql old_password()
* provides backward compatibility for zero board4 which uses old_password() of mysql 4.1 earlier versions. * provides backward compatibility for zero board4 which uses old_password() of mysql 4.1 earlier versions.
* the function implemented by referring to the source codes of password.c file in mysql * the function implemented by referring to the source codes of password.c file in mysql
* *
* @deprecated * @deprecated
@ -1018,7 +1018,7 @@ function detectUTF8($string, $return_convert = FALSE, $urldecode = TRUE)
{ {
$string = urldecode($string); $string = urldecode($string);
} }
if(function_exists('mb_check_encoding')) if(function_exists('mb_check_encoding'))
{ {
$is_utf8 = mb_check_encoding($string, 'UTF-8'); $is_utf8 = mb_check_encoding($string, 'UTF-8');
@ -1067,14 +1067,14 @@ function stripEmbedTagForAdmin(&$content, $writer_member_srl)
{ {
return; return;
} }
$logged_info = Context::get('logged_info'); $logged_info = Context::get('logged_info');
$writer_member_srl = abs($writer_member_srl); $writer_member_srl = abs($writer_member_srl);
if ($logged_info->member_srl == $writer_member_srl) if ($logged_info->member_srl == $writer_member_srl)
{ {
return; return;
} }
if ($logged_info->is_admin === 'Y' || getModel('module')->isSiteAdmin($logged_info)) if ($logged_info->is_admin === 'Y' || getModel('module')->isSiteAdmin($logged_info))
{ {
if ($writer_member_srl) if ($writer_member_srl)
@ -1085,7 +1085,7 @@ function stripEmbedTagForAdmin(&$content, $writer_member_srl)
return; return;
} }
} }
$security_msg = '<div style="border: 1px solid #DDD; background: #FAFAFA; text-align:center; margin: 1em 0;">' . $security_msg = '<div style="border: 1px solid #DDD; background: #FAFAFA; text-align:center; margin: 1em 0;">' .
'<p style="margin: 1em;">' . lang('security_warning_embed') . '</p></div>'; '<p style="margin: 1em;">' . lang('security_warning_embed') . '</p></div>';
$content = Rhymix\Framework\Filters\MediaFilter::removeEmbeddedMedia($content, $security_msg); $content = Rhymix\Framework\Filters\MediaFilter::removeEmbeddedMedia($content, $security_msg);
@ -1102,12 +1102,12 @@ function stripEmbedTagForAdmin(&$content, $writer_member_srl)
*/ */
function requirePear() function requirePear()
{ {
} }
/** /**
* Check for CSRF attacks * Check for CSRF attacks
* *
* @return bool * @return bool
*/ */
function checkCSRF() function checkCSRF()