/** * Sets the payment processing fields. * The driver will translate these into the specific format for the provider. * Standard fields are (Providers may have additional or different fields): * * card_num * exp_date * cvv * description * amount * tax * shipping * first_name * last_name * company * address * city * state * zip * email * phone * fax * ship_to_first_name * ship_to_last_name * ship_to_company * ship_to_address * ship_to_city * ship_to_state * ship_to_zip * * @param array the driver string */ public function __construct($config = array()) { if (empty($config)) { // Load the default group $config = Eight::config('payment.default'); } elseif (is_string($config)) { $this->config['driver'] = $config; } // Merge the default config with the passed config is_array($config) and $this->config = array_merge($this->config, $config); // Set driver name $driver = 'Payment_Driver_' . ucfirst($this->config['driver']); // Load the driver if (!Eight::auto_load($driver)) { throw new Eight_Exception('core.driver_not_found', $this->config['driver'], get_class($this)); } // Get the driver specific settings $this->config = array_merge($this->config, Eight::config('payment.' . $this->config['driver'])); // Initialize the driver $this->driver = new $driver($this->config); // Validate the driver if (!$this->driver instanceof Payment_Driver) { throw new Eight_Exception('core.driver_implements', $this->config['driver'], get_class($this), 'Payment_Driver'); } }
/** * Render the profiler. Output is added to the bottom of the page by default. * * @param boolean return the output if YES * @return void|string */ public function render($return = NO) { $start = microtime(YES); $get = isset($_GET['profiler']) ? explode(',', $_GET['profiler']) : array(); $this->show = empty($get) ? Eight::config('profiler.show') : $get; Event::run('profiler.run', $this); $styles = ''; foreach ($this->profiles as $profile) { $styles .= $profile->styles(); } // Don't display if there's no profiles if (empty($this->profiles)) { return; } // Load the profiler view $data = array('profiles' => $this->profiles, 'styles' => $styles, 'execution_time' => microtime(YES) - $start); $view = new View('profiler/profiler', $data); // Return rendered view if $return is YES if ($return == YES) { return $view->render(); } // Add profiler data to the output if (stripos(Eight::$output, '</body>') !== NO) { // Closing body tag was found, insert the profiler data before it Eight::$output = str_ireplace('</body>', $view->render() . '</body>', Eight::$output); } else { // Append the profiler data to the output Eight::$output .= $view->render(); } }
/** * Loads the configured driver and validates it. * * @param array|string custom configuration or config group name * @return void */ public function __construct($config = NO) { if (is_string($config)) { $name = $config; // Test the config group name if (($config = Eight::config('cache.' . $config)) === NULL) { throw new Cache_Exception('The :group: group is not defined in your configuration.', array(':group:' => $name)); } } if (is_array($config)) { // Append the default configuration options $config += Eight::config('cache.default'); } else { // Load the default group $config = Eight::config('cache.default'); } // Cache the config in the object $this->config = $config; // Set driver name $driver = 'Cache_Driver_' . ucfirst($this->config['driver']); // Load the driver if (!Eight::auto_load($driver)) { throw new Cache_Exception('The :driver: driver for the :class: library could not be found', array(':driver:' => $this->config['driver'], ':class:' => get_class($this))); } // Initialize the driver $this->driver = new $driver($this->config['params']); // Validate the driver if (!$this->driver instanceof Cache_Driver) { throw new Cache_Exception('The :driver: driver for the :library: library must implement the :interface: interface', array(':driver:' => $this->config['driver'], ':library:' => get_class($this), ':interface:' => 'Cache_Driver')); } Eight::log('debug', 'Cache Library initialized'); }
/** * Loads encryption configuration and validates the data. * * @param array|string custom configuration or config group name * @throws Eight_Exception */ public function __construct($config = NO) { if (!defined('MCRYPT_ENCRYPT')) { throw new Eight_Exception('encrypt.requires_mcrypt'); } if (is_string($config)) { $name = $config; // Test the config group name if (($config = Eight::config('encryption.' . $config)) === nil) { throw new Eight_Exception('encrypt.undefined_group', $name); } } if (is_array($config)) { // Append the default configuration options $config += Eight::config('encryption.default'); } else { // Load the default group $config = Eight::config('encryption.default'); } if (empty($config['key'])) { throw new Eight_Exception('encrypt.no_encryption_key'); } // Find the max length of the key, based on cipher and mode $size = mcrypt_get_key_size($config['cipher'], $config['mode']); if (strlen($config['key']) > $size) { // Shorten the key to the maximum size $config['key'] = substr($config['key'], 0, $size); } // Find the initialization vector size $config['iv_size'] = mcrypt_get_iv_size($config['cipher'], $config['mode']); // Cache the config in the object $this->config = $config; Eight::log('debug', 'Encrypt Library initialized'); }
/** * Returns an array of the names of the days, using the current locale. * * @param integer left of day names * @return array */ public static function days($length = YES) { // strftime day format $format = $length > 3 ? '%A' : '%a'; // Days of the week $days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); if (Calendar::$start_monday === YES) { // Push Sunday to the end of the days array_push($days, array_shift($days)); } if (strpos(Eight::config('locale.language.0'), 'en') !== 0) { // This is a bit awkward, but it works properly and is reliable foreach ($days as $i => $day) { // Convert the English names to i18n names $days[$i] = strftime($format, strtotime($day)); } } if (is_int($length) or ctype_digit($length)) { foreach ($days as $i => $day) { // Shorten the days to the expected length $days[$i] = mb_substr($day, 0, $length); } } return $days; }
/** * Loads Session and configuration options. * * @return void */ public function __construct($config = array()) { // Load Session $this->session = Session::instance(); // Append default auth configuration $config += Eight::config('auth'); // Save the config in the object $this->config = $config; // Init Bcrypt if we're using it if ($this->config['hash_method'] == 'bcrypt') { $this->bcrypt = new Bcrypt(12); } // Set the driver class name $driver = 'Auth_Driver_' . $config['driver']; if (!Eight::auto_load($driver)) { throw new Eight_Exception('core.driver_not_found', $config['driver'], get_class($this)); } // Load the driver $driver = new $driver($config); if (!$driver instanceof Auth_Driver) { throw new Eight_Exception('core.driver_implements', $config['driver'], get_class($this), 'Auth_Driver'); } // Load the driver for access $this->driver = $driver; Eight::log('debug', 'Auth Library loaded'); }
/** * Constructs a new Captcha object. * * @throws Eight_Exception * @param string config group name * @return void */ public function __construct($group = nil) { // Create a singleton instance once empty(self::$instances[$group]) and self::$instances[$group] = $this; // No config group name given if (!is_string($group)) { $group = 'default'; } // Load and validate config group if (!is_array($config = Eight::config('captcha.' . $group))) { throw new Eight_Exception('captcha.undefined_group', $group); } // All captcha config groups inherit default config group if ($group !== 'default') { // Load and validate default config group if (!is_array($default = Eight::config('captcha.default'))) { throw new Eight_Exception('captcha.undefined_group', 'default'); } // Merge config group with default config group $config += $default; } // Assign config values to the object foreach ($config as $key => $value) { if (array_key_exists($key, self::$config)) { self::$config[$key] = $value; } } // Store the config group name as well, so the drivers can access it self::$config['group'] = $group; // If using a background image, check if it exists if (!empty($config['background'])) { self::$config['background'] = str_replace('\\', '/', realpath($config['background'])); if (!is_file(self::$config['background'])) { throw new Eight_Exception('captcha.file_not_found', self::$config['background']); } } // If using any fonts, check if they exist if (!empty($config['fonts'])) { self::$config['fontpath'] = str_replace('\\', '/', realpath($config['fontpath'])) . '/'; foreach ($config['fonts'] as $font) { if (!is_file(self::$config['fontpath'] . $font)) { throw new Eight_Exception('captcha.file_not_found', self::$config['fontpath'] . $font); } } } // Set driver name $driver = 'Captcha_Driver_' . ucfirst($config['style']); // Load the driver if (!Eight::auto_load($driver)) { throw new Eight_Exception('core.driver_not_found', $config['style'], get_class($this)); } // Initialize the driver $this->driver = new $driver(); // Validate the driver if (!$this->driver instanceof Captcha_Driver) { throw new Eight_Exception('core.driver_implements', $config['style'], get_class($this), 'Captcha_Driver'); } Eight::log('debug', 'Captcha Library initialized'); }
public function write($id, $data) { $data = empty($this->encrypt) ? base64_encode($data) : $this->encrypt->encode($data); if (strlen($data) > 4048) { Eight::log('error', 'Session (' . $id . ') data exceeds the 4KB limit, ignoring write.'); return NO; } return cookie::set($this->cookie_name, $data, Eight::config('session.expiration')); }
/** * Throws a new 404 exception. * * @throws Eight_Exception_404 * @return void */ public static function trigger($page = NULL) { // Silence 404 errors (as matched within the ignore array) and die quietly if (in_array(Router::$complete_uri, arr::c(Eight::config('core.ignore_page_not_found')))) { Eight::shutdown(); exit; } throw new Eight_Exception_404($page); }
public static function logged_in() { if (str::e($_COOKIE[Eight::config('facebook.api_key') . '_user'])) { return FALSE; } else { if (intval(Eight::instance()->fb->user) > 0) { return TRUE; } else { return FALSE; } } }
/** * Sets the view filename. * * @chainable * @param string view filename * @param string view file type * @return object */ public function set_filename($name, $type = nil) { if ($type === nil) { // Load the filename and set the content type $this->eight_filename = Eight::find_file('views', $name, YES); $this->eight_filetype = EXT; } else { // Load the filename and set the content type $this->eight_filename = Eight::find_file('views', $name, YES, $type); $this->eight_filetype = Eight::config('mimes.' . $type); if ($this->eight_filetype === nil) { // Use the specified type $this->eight_filetype = $type; } } return $this; }
/** * Fetches an absolute site URL based on a URI segment. * * @param string site URI to convert * @param string non-default protocol * @return string */ public static function site($uri = '', $protocol = NO) { if ($path = trim(parse_url($uri, PHP_URL_PATH), '/')) { // Add path suffix $path .= Eight::config('core.url_suffix'); } if ($query = parse_url($uri, PHP_URL_QUERY)) { // ?query=string $query = '?' . $query; } if ($fragment = parse_url($uri, PHP_URL_FRAGMENT)) { // #fragment $fragment = '#' . $fragment; } // Concat the URL return url::base(YES, $protocol) . $path . $query . $fragment; }
/** * Sets a cookie with the given parameters. * * @param string cookie name or array of config options * @param string cookie value * @param integer number of seconds before the cookie expires * @param string URL path to allow * @param string URL domain to allow * @param boolean HTTPS only * @param boolean HTTP only (requires PHP 5.2 or higher) * @return boolean */ public static function set($name, $value = nil, $expire = nil, $path = nil, $domain = nil, $secure = nil, $httponly = nil) { if (headers_sent()) { return NO; } // If the name param is an array, we import it is_array($name) and extract($name, EXTR_OVERWRITE); // Fetch default options $config = Eight::config('cookie'); foreach (array('value', 'expire', 'domain', 'path', 'secure', 'httponly') as $item) { if (${$item} === nil and isset($config[$item])) { ${$item} = $config[$item]; } } // Expiration timestamp $expire = $expire == 0 ? 0 : time() + (int) $expire; return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly); }
/** * Creates a new image editor instance. * * @throws Eight_Exception * @param string filename of image * @param array non-default configurations * @return void */ public function __construct($image, $config = nil) { static $check; // Make the check exactly once $check === nil and $check = function_exists('getimagesize'); if ($check === NO) { throw new Eight_Exception('image.getimagesize_missing'); } // Check to make sure the image exists if (!is_file($image)) { throw new Eight_Exception('image.file_not_found', $image); } // Disable error reporting, to prevent PHP warnings $ER = error_reporting(0); // Fetch the image size and mime type $image_info = getimagesize($image); // Turn on error reporting again error_reporting($ER); // Make sure that the image is readable and valid if (!is_array($image_info) or count($image_info) < 3) { throw new Eight_Exception('image.file_unreadable', $image); } // Check to make sure the image type is allowed if (!isset(Image::$allowed_types[$image_info[2]])) { throw new Eight_Exception('image.type_not_allowed', $image); } // Image has been validated, load it $this->image = array('file' => str_replace('\\', '/', realpath($image)), 'width' => $image_info[0], 'height' => $image_info[1], 'type' => $image_info[2], 'ext' => Image::$allowed_types[$image_info[2]], 'mime' => $image_info['mime']); // Load configuration $this->config = (array) $config + Eight::config('image'); // Set driver class name $driver = 'Image_Driver_' . ucfirst($this->config['driver']); // Load the driver if (!Eight::auto_load($driver)) { throw new Eight_Exception('core.driver_not_found', $this->config['driver'], get_class($this)); } // Initialize the driver $this->driver = new $driver($this->config['params']); // Validate the driver if (!$this->driver instanceof Image_Driver) { throw new Eight_Exception('core.driver_implements', $this->config['driver'], get_class($this), 'Image_Driver'); } }
/** * Loads Session and configuration options. * * @return void */ public function __construct($config = array()) { // Load Session $this->session = Session::instance(); // Append default auth configuration $config += Eight::config('auth'); // Clean up the salt pattern and split it into an array $config['salt_pattern'] = preg_split('/,\\s*/', Eight::config('auth.salt_pattern')); // Save the config in the object $this->config = $config; // Set the driver class name $driver = 'Auth_Driver_' . $config['driver']; if (!Eight::auto_load($driver)) { throw new Eight_Exception('core.driver_not_found', $config['driver'], get_class($this)); } // Load the driver $driver = new $driver($config); if (!$driver instanceof Auth_Driver) { throw new Eight_Exception('core.driver_implements', $config['driver'], get_class($this), 'Auth_Driver'); } // Load the driver for access $this->driver = $driver; Eight::log('debug', 'Auth Library loaded'); }
public function __construct() { // Load configuration $config = Eight::config('session'); if (!empty($config['encryption'])) { // Load encryption $this->encrypt = new Encrypt(); } if (is_array($config['storage'])) { if (!empty($config['storage']['group'])) { // Set the group name $this->db = $config['storage']['group']; } if (!empty($config['storage']['table'])) { // Set the table name $this->table = $config['storage']['table']; } } // Load database $this->db = Database::instance($this->db); // Force PHP to write the session on shutdown. register_shutdown_function('session_write_close'); Eight::log('debug', 'Session Database Driver Initialized'); }
/** * Sets up the database configuration, loads the <Database_Driver>. * * @param array|string Config array or DSN String * * @throws <Database_Exception> if there is no database group, an invalid DSN is supplied, or the requested driver doesn't exist. */ public function __construct($config = array()) { if (empty($config)) { // Load the default group $config = Eight::config('database.default'); } elseif (is_string($config)) { // The config is a DSN string if (strpos($config, '://') !== FALSE) { $config = array('connection' => $config); } else { $name = $config; // Test the config group name if (($config = Eight::config('database.' . $config)) === NULL) { throw new Database_Exception('database.undefined_group', $name); } $this->connection_group = $name; } } // Merge the default config with the passed config $this->config = array_merge($this->config, $config); // Make sure the connection is valid if (strpos($this->config['connection'], '://') === FALSE) { throw new Database_Exception('database.invalid_dsn', $this->config['connection']); } // Parse the DSN, creating an array to hold the connection parameters $db = array('type' => FALSE, 'user' => FALSE, 'pass' => FALSE, 'host' => FALSE, 'port' => FALSE, 'socket' => FALSE, 'database' => FALSE); // Get the protocol and arguments list($db['type'], $connection) = explode('://', $this->config['connection'], 2); // Set driver name $driver = 'Database_Driver_' . ucfirst($db['type']); // Load the driver if (!Eight::auto_load($driver)) { throw new Database_Exception('database.driver_not_supported', $this->config['connection']['type']); } // Reset the connection array to the database config $this->config['connection'] = call_user_func(array($driver, 'parse_connection'), $db['type'], $connection); $this->name = $this->config['connection']['database']; // Check to see if we use a separate database for updates if (!str::e($this->config['connection_master'])) { // Get the protocol and arguments list($db['type'], $connection) = explode('://', $this->config['connection_master'], 2); // Reset the connection array to the database config $this->config['connection_master'] = call_user_func(array($driver, 'parse_connection'), $db['type'], $connection); } // Initialize the driver $this->type = $db['type']; $this->driver = new $driver($this->config); // Validate the driver if (!$this->driver instanceof Database_Driver) { throw new Database_Exception('database.driver_not_supported', 'Database drivers must use the Database_Driver interface.'); } Eight::log('debug', 'Database Library initialized'); }
/** * Fetches SQL type information about a field, in a generic format. * * @param string $str * @return array */ protected function sql_type($str) { static $sql_types; if ($sql_types === NULL) { // Load SQL data types $sql_types = Eight::config('sql_types'); } $str = strtolower(trim($str)); if (($open = strpos($str, '(')) !== FALSE) { // Find closing bracket $close = strpos($str, ')', $open) - 1; // Find the type without the size $type = substr($str, 0, $open); } else { // No length $type = $str; } empty($sql_types[$type]) and exit('Unknown field type: ' . $type . '. ' . 'Please report this: http://trac.Eightphp.com/newticket'); // Fetch the field definition $field = $sql_types[$type]; switch ($field['type']) { case 'string': case 'float': if (isset($close)) { // Add the length to the field info $field['length'] = substr($str, $open + 1, $close - $open); } break; case 'int': // Add unsigned value $field['unsigned'] = strpos($str, 'unsigned') !== FALSE; break; } return $field; }
/** * Creates a meta tag. * * @param string|array tag name, or an array of tags * @param string tag "content" value * @return string */ public static function meta($tag, $value = nil) { if (is_array($tag)) { $tags = array(); foreach ($tag as $t => $v) { // Build each tag and add it to the array $tags[] = html::meta($t, $v); } // Return all of the tags as a string return implode("\n", $tags); } // Set the meta attribute value $attr = in_array(strtolower($tag), Eight::config('http.meta_equiv')) ? 'http-equiv' : 'name'; return '<meta ' . $attr . '="' . $tag . '" content="' . $value . '" />'; }
/** * Get a Mongo_Database instance. Configuration options are: * * <pre> * server A server connection string. See Mongo::__construct() * options The additional options for the connection ("connect" and "persist") * database *required* The database name to use for this instance * profiling Enable/disable profiling * </pre> * * @param string $name The configuration name * @param array $config Pass a configuration array to bypass the Kohana config * @return Mongo_Database * @static */ public static function instance($name = 'default', array $config = NULL) { if (!isset(self::$instances[$name])) { if ($config === NULL) { // Load the configuration for this database $config = Eight::config('mongodb.' . $name); } new self($name, $config); } return self::$instances[$name]; }
/** * Generates nice test results. * * @param boolean hide passed tests from the report * @return string rendered test results html */ public function report($hide_passed = nil) { // No tests found if (empty($this->results)) { return Eight::lang('unittest.no_tests_found'); } // Hide passed tests from the report? $hide_passed = (bool) ($hide_passed !== nil ? $hide_passed : Eight::config('unittest.hide_passed', NO, NO)); // Render unittest report return View::factory('eight/unittest', array('results' => $this->results, 'stats' => $this->stats, 'hide_passed' => $hide_passed))->render(); }
/** * exception handler, displays the error message, source of the * exception, and the stack trace of the error. * * @uses Eight::lang() * @uses Eight_Exception::text() * @param object exception object * @return void */ public static function handle(Exception $e) { try { // Get the exception information $type = get_class($e); $code = $e->getCode(); $message = $e->getMessage(); // Create a text version of the exception $error = Eight_Exception::text($e); // Add this exception to the log Eight::log('error', $error); // Manually save logs after exceptions Eight::log_save(); if (Eight::config('core.display_errors') === FALSE && Eight::$force_show_errors !== YES) { // Do not show the details $file = $line = NULL; $trace = array(); $template = '_disabled'; } else { $file = $e->getFile(); $line = $e->getLine(); $trace = $e->getTrace(); $template = Eight::$server_api == 'cli' ? '_cli' : ''; } if (Eight::$server_api != 'cli') { header("Content-Type: text/html;charset=utf-8"); } if ($e instanceof Eight_Exception) { $template = $e->getTemplate() . $template; if (!headers_sent()) { $e->sendHeaders(); } // Use the human-readable error name $code = Eight::lang('4' . $code); } else { $template = Eight_Exception::$template . $template; if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if ($e instanceof ErrorException) { // Use the human-readable error name $code = Eight::lang('4' . $e->getSeverity()); if (version_compare(PHP_VERSION, '5.3', '<')) { // Workaround for a bug in ErrorException::getTrace() that exists in // all PHP 5.2 versions. @see http://bugs.php.net/45895 for ($i = count($trace) - 1; $i > 0; --$i) { if (isset($trace[$i - 1]['args'])) { // Re-position the arguments $trace[$i]['args'] = $trace[$i - 1]['args']; unset($trace[$i - 1]['args']); } } } } } // Clean the output buffer if one exists ob_get_level() and ob_clean(); if ($template = Eight::find_file('views', $template)) { include $template; } } catch (Exception $e) { // Clean the output buffer if one exists ob_get_level() and ob_clean(); // Display the exception text echo Eight_Exception::text($e), "\n"; // Exit with an error code exit(1); } }
/** * Method: create * Create a new session. */ public function create($vars = NULL) { // Destroy the session $this->destroy(); // Set the session name after having checked it if (!ctype_alnum(self::$config['name']) or ctype_digit(self::$config['name'])) { throw new Eight_Exception('session.invalid_session_name', self::$config['name']); } session_name(self::$config['name']); // Set garbage collection probability ini_set('session.gc_probability', (int) self::$config['gc_probability']); ini_set('session.gc_divisor', 100); // Set expiration time for native sessions if (self::$config['driver'] == 'native') { ini_set('session.gc_maxlifetime', self::$config['expiration'] == 0 ? 86400 : self::$config['expiration']); } // Set the session cookie parameters // Note: the httponly parameter was added in PHP 5.2.0 if (version_compare(PHP_VERSION, '5.2', '>=')) { session_set_cookie_params(self::$config['expiration'], Eight::config('cookie.path'), Eight::config('cookie.domain'), Eight::config('cookie.secure'), Eight::config('cookie.httponly')); } else { session_set_cookie_params(self::$config['expiration'], Eight::config('cookie.path'), Eight::config('cookie.domain'), Eight::config('cookie.secure')); } // Register non-native driver as the session handler if (self::$config['driver'] != 'native') { session_set_save_handler(array(self::$driver, 'open'), array(self::$driver, 'close'), array(self::$driver, 'read'), array(self::$driver, 'write'), array(self::$driver, 'destroy'), array(self::$driver, 'gc')); } // Start the session! session_start(); // Put session_id in the session variable if (self::$config['driver'] != 'native') { $_SESSION['session_id'] = self::$driver->identify(); } // Set defaults if (!isset($_SESSION['_e_flash'])) { $_SESSION['user_agent'] = Eight::$user_agent; $_SESSION['ip_address'] = $this->input->ip_address(); $_SESSION['_e_flash'] = array(); $_SESSION['total_hits'] = 0; } // Set up flash variables self::$flash =& $_SESSION['_e_flash']; // Update constant session variables $_SESSION['last_activity'] = time(); $_SESSION['total_hits'] += 1; // Validate data only on hits after one if ($_SESSION['total_hits'] > 1) { // Validate the session foreach ((array) self::$config['validate'] as $valid) { switch ($valid) { case 'user_agent': if ($_SESSION[$valid] !== Eight::$user_agent) { return $this->create(); } break; case 'ip_address': if ($_SESSION[$valid] !== $this->input->{$valid}()) { return $this->create(); } break; } } // Remove old flash data if (!empty(self::$flash)) { foreach (self::$flash as $key => $state) { if ($state == 'old') { self::del($key); unset(self::$flash[$key]); } else { self::$flash[$key] = 'old'; } } } } // Set the new data self::set($vars); }
/** * Loops through the mimes config array and finds the extension for a given mime type. * Might be able to speed this one up a bit...not sure. * * @param string mime type * @return string extension for given mime type */ public static function mime_to_ext($mime) { $mimes = Eight::config('mimes'); foreach ($mimes as $k => $m) { foreach ($m as $v) { if ($mime == $v) { return $k; } } } }
/** * Makes a singular word plural. * * @param string word to pluralize * @return string */ public static function plural($str, $count = nil) { // Remove garbage $str = strtolower(trim($str)); if (is_string($count)) { // Convert to integer when using a digit string $count = (int) $count; } // Do nothing with singular if ($count === 1) { return $str; } // Cache key name $key = 'plural_' . $str . $count; if (isset(self::$cache[$key])) { return self::$cache[$key]; } if (inflector::uncountable($str)) { return self::$cache[$key] = $str; } if (empty(self::$irregular)) { // Cache irregular words self::$irregular = Eight::config('inflector.irregular'); } if (isset(self::$irregular[$str])) { $str = self::$irregular[$str]; } elseif (preg_match('/[sxz]$/', $str) or preg_match('/[^aeioudgkprt]h$/', $str)) { $str .= 'es'; } elseif (preg_match('/[^aeiou]y$/', $str)) { // Change "y" to "ies" $str = substr_replace($str, 'ies', -1); } else { $str .= 's'; } // Set the cache and return return self::$cache[$key] = $str; }
public function __construct() { parent::__construct(Eight::config('facebook.api_key'), Eight::config('facebook.secret')); }
public function rule_allow() { if (empty($this->upload['tmp_name']) or count($types = func_get_args()) == 0) { return; } if (($mime = file::mime($this->upload['tmp_name'])) === NO) { // Trust the browser $mime = $this->upload['type']; } // Clean up charset garbage $mime = arr::get(explode(';', $mime), 0); // Allow nothing by default $allow = NO; foreach ($types as $type) { // Load the mime types $type = Eight::config('mimes.' . $type); if (is_array($type) and in_array($mime, $type)) { // Type is valid $allow = YES; break; } } if ($allow === NO) { $this->errors['invalid_type'] = YES; } }
/** * Sets config values. * * @throws Eight_Exception * @param array configuration settings * @return void */ public function initialize($config = array()) { // Load config group if (isset($config['group'])) { // Load and validate config group if (!is_array($group_config = Eight::config('pagination.' . $config['group']))) { throw new Eight_Exception('pagination.undefined_group', $config['group']); } // All pagination config groups inherit default config group if ($config['group'] !== 'default') { // Load and validate default config group if (!is_array($default_config = Eight::config('pagination.default'))) { throw new Eight_Exception('pagination.undefined_group', 'default'); } // Merge config group with default config group $group_config += $default_config; } // Merge custom config items with config group $config += $group_config; } // Assign config values to the object foreach ($config as $key => $value) { if (property_exists($this, $key)) { $this->{$key} = $value; } } // Clean view directory $this->directory = trim($this->directory, '/') . '/'; // Build generic URL with page in query string if ($this->query_string !== '') { // Extract current page $this->current_page = isset($_GET[$this->query_string]) ? (int) $_GET[$this->query_string] : 1; // Insert {page} placeholder $_GET[$this->query_string] = '{page}'; // Create full URL $this->url = url::site(Router::$current_uri) . '?' . str_replace('%7Bpage%7D', '{page}', http_build_query($_GET)); // Reset page number $_GET[$this->query_string] = $this->current_page; } else { // Use current URI if no base_url set $this->url = $this->base_url === '' ? URI::instance()->segments() : explode('/', trim($this->base_url, '/')); // Convert uri 'label' to corresponding integer if needed if (is_string($this->uri_segment)) { if (($key = array_search($this->uri_segment, $this->url)) === NO) { // If uri 'label' is not found, auto add it to base_url $this->url[] = $this->uri_segment; $this->uri_segment = count($this->url) + 1; } else { $this->uri_segment = $key + 1; } } // Insert {page} placeholder if (!empty($this->base_url)) { $this->url[$this->uri_segment - 1] = '{page}'; } else { $this->url[$this->uri_segment] = '{page}'; } // Create full URL $this->url = url::site(implode('/', $this->url)) . Router::$query_string; // Extract current page $this->current_page = URI::instance()->segment($this->uri_segment); } // Core pagination values $this->total_items = (int) max(0, $this->total_items); $this->items_per_page = (int) max(1, $this->items_per_page); $this->total_pages = (int) ceil($this->total_items / $this->items_per_page); $this->current_page = (int) min(max(1, $this->current_page), max(1, $this->total_pages)); $this->current_first_item = (int) min(($this->current_page - 1) * $this->items_per_page + 1, $this->total_items); $this->current_last_item = (int) min($this->current_first_item + $this->items_per_page - 1, $this->total_items); // If there is no first/last/previous/next page, relative to the // current page, value is set to NO. Valid page number otherwise. $this->first_page = $this->current_page === 1 ? NO : 1; $this->last_page = $this->current_page >= $this->total_pages ? NO : $this->total_pages; $this->previous_page = $this->current_page > 1 ? $this->current_page - 1 : NO; $this->next_page = $this->current_page < $this->total_pages ? $this->current_page + 1 : NO; // SQL values $this->sql_offset = (int) ($this->current_page - 1) * $this->items_per_page; $this->sql_limit = sprintf(' LIMIT %d OFFSET %d ', $this->items_per_page, $this->sql_offset); }
<?php /** * @package System * @subpackage Libraries.Cache * * Cache settings, defined as arrays, or "groups". If no group name is * used when loading the cache library, the group named "default" will be used. * Each group can be used independently, and multiple groups can be used at once. * * driver * : Eight comes with [apc][ref-apc], [eaccelerator][ref-eac], [file][ref-fil], * [memcache][ref-mem], [sqlite][ref-sql], and [xcache][ref-xca] drivers. * * params * : Driver-specific configuration options. * * lifetime * : Default lifetime of caches in seconds. By default caches are stored for * thirty minutes. Specific lifetime can also be set when creating a new cache. * Setting this to 0 will never automatically delete caches. * * requests * : Average number of cache requests that will processed before all expired * caches are deleted (garbage collection). Setting this to 0 will disable * automatic garbage collection. */ $config['default'] = array('driver' => 'file', 'params' => array('directory' => Eight::config('core.internal_cache_path')), 'lifetime' => 1800, 'requests' => 1000);
/** * Validates a credit card number using the Luhn (mod10) formula. * @see http://en.wikipedia.org/wiki/Luhn_algorithm * * @param integer credit card number * @param string|array card type, or an array of card types * @return boolean */ public static function credit_card($number, $type = nil) { // Remove all non-digit characters from the number if (($number = preg_replace('/\\D+/', '', $number)) === '') { return NO; } if ($type == nil) { // Use the default type $type = 'default'; } elseif (is_array($type)) { foreach ($type as $t) { // Test each type for validity if (valid::credit_card($number, $t)) { return YES; } } return NO; } $cards = Eight::config('credit_cards'); // Check card type $type = strtolower($type); if (!isset($cards[$type])) { return NO; } // Check card number length $length = strlen($number); // Validate the card length by the card type if (!in_array($length, preg_split('/\\D+/', $cards[$type]['length']))) { return NO; } // Check card number prefix if (!preg_match('/^' . $cards[$type]['prefix'] . '/', $number)) { return NO; } // No Luhn check required if ($cards[$type]['luhn'] == NO) { return YES; } // Checksum of the card number $checksum = 0; for ($i = $length - 1; $i >= 0; $i -= 2) { // Add up every 2nd digit, starting from the right $checksum += substr($number, $i, 1); } for ($i = $length - 2; $i >= 0; $i -= 2) { // Add up every 2nd digit doubled, starting from the right $double = substr($number, $i, 1) * 2; // Subtract 9 from the double where value is greater than 10 $checksum += $double >= 10 ? $double - 9 : $double; } // If the checksum is a multiple of 10, the number is valid return $checksum % 10 === 0; }