Example #1
1
 function convert_uudecode($string)
 {
     // Sanity check
     if (!is_scalar($string)) {
         user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
         return false;
     }
     if (strlen($string) < 8) {
         user_error('convert_uuencode() The given parameter is not a valid uuencoded string', E_USER_WARNING);
         return false;
     }
     $decoded = '';
     foreach (explode("\n", $string) as $line) {
         $c = count($bytes = unpack('c*', substr(trim($line), 1)));
         while ($c % 4) {
             $bytes[++$c] = 0;
         }
         foreach (array_chunk($bytes, 4) as $b) {
             $b0 = $b[0] == 0x60 ? 0 : $b[0] - 0x20;
             $b1 = $b[1] == 0x60 ? 0 : $b[1] - 0x20;
             $b2 = $b[2] == 0x60 ? 0 : $b[2] - 0x20;
             $b3 = $b[3] == 0x60 ? 0 : $b[3] - 0x20;
             $b0 <<= 2;
             $b0 |= $b1 >> 4 & 0x3;
             $b1 <<= 4;
             $b1 |= $b2 >> 2 & 0xf;
             $b2 <<= 6;
             $b2 |= $b3 & 0x3f;
             $decoded .= pack('c*', $b0, $b1, $b2);
         }
     }
     return rtrim($decoded, "");
 }
 function republish($original)
 {
     if (self::$disable_realtime) {
         return;
     }
     $urls = array();
     if ($this->owner->hasMethod('pagesAffectedByChanges')) {
         $urls = $this->owner->pagesAffectedByChanges($original);
     } else {
         $pages = Versioned::get_by_stage('SiteTree', 'Live', '', '', '', 10);
         if ($pages) {
             foreach ($pages as $page) {
                 $urls[] = $page->AbsoluteLink();
             }
         }
     }
     // Note: Similiar to RebuildStaticCacheTask->rebuildCache()
     foreach ($urls as $i => $url) {
         if (!is_string($url)) {
             user_error("Bad URL: " . var_export($url, true), E_USER_WARNING);
             continue;
         }
         // Remove leading slashes from all URLs (apart from the homepage)
         if (substr($url, -1) == '/' && $url != '/') {
             $url = substr($url, 0, -1);
         }
         $urls[$i] = $url;
     }
     $urls = array_unique($urls);
     $this->publishPages($urls);
 }
Example #3
0
 function convert_uuencode($string)
 {
     // Sanity check
     if (!is_scalar($string)) {
         user_error('convert_uuencode() expects parameter 1 to be string, ' . gettype($string) . ' given', E_USER_WARNING);
         return false;
     }
     $u = 0;
     $encoded = '';
     while ($c = count($bytes = unpack('c*', substr($string, $u, 45)))) {
         $u += 45;
         $encoded .= pack('c', $c + 0x20);
         while ($c % 3) {
             $bytes[++$c] = 0;
         }
         foreach (array_chunk($bytes, 3) as $b) {
             $b0 = ($b[0] & 0xfc) >> 2;
             $b1 = (($b[0] & 0x3) << 4) + (($b[1] & 0xf0) >> 4);
             $b2 = (($b[1] & 0xf) << 2) + (($b[2] & 0xc0) >> 6);
             $b3 = $b[2] & 0x3f;
             $b0 = $b0 ? $b0 + 0x20 : 0x60;
             $b1 = $b1 ? $b1 + 0x20 : 0x60;
             $b2 = $b2 ? $b2 + 0x20 : 0x60;
             $b3 = $b3 ? $b3 + 0x20 : 0x60;
             $encoded .= pack('c*', $b0, $b1, $b2, $b3);
         }
         $encoded .= "\n";
     }
     // Add termination characters
     $encoded .= "`\n";
     return $encoded;
 }
Example #4
0
 function str_word_count($string, $format = null)
 {
     if ($format !== 1 && $format !== 2 && $format !== null) {
         user_error('str_word_count() The specified format parameter, "' . $format . '" is invalid', E_USER_WARNING);
         return false;
     }
     $word_string = preg_replace('/[0-9]+/', '', $string);
     $word_array = preg_split('/[^A-Za-z0-9_\']+/', $word_string, -1, PREG_SPLIT_NO_EMPTY);
     switch ($format) {
         case null:
             $result = count($word_array);
             break;
         case 1:
             $result = $word_array;
             break;
         case 2:
             $lastmatch = 0;
             $word_assoc = array();
             foreach ($word_array as $word) {
                 $word_assoc[$lastmatch = strpos($string, $word, $lastmatch)] = $word;
                 $lastmatch += strlen($word);
             }
             $result = $word_assoc;
             break;
     }
     return $result;
 }
 /**
  * @uses ModelAsController::getNestedController()
  * @param SS_HTTPRequest $request
  * @param DataModel $model
  * @return SS_HTTPResponse
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     $this->setRequest($request);
     $this->setDataModel($model);
     $this->pushCurrent();
     // Create a response just in case init() decides to redirect
     $this->response = new SS_HTTPResponse();
     $this->init();
     // If we had a redirection or something, halt processing.
     if ($this->response->isFinished()) {
         $this->popCurrent();
         return $this->response;
     }
     // If the database has not yet been created, redirect to the build page.
     if (!DB::is_active() || !ClassInfo::hasTable('SiteTree')) {
         $this->response->redirect(Director::absoluteBaseURL() . 'dev/build?returnURL=' . (isset($_GET['url']) ? urlencode($_GET['url']) : null));
         $this->popCurrent();
         return $this->response;
     }
     try {
         $result = $this->getNestedController();
         if ($result instanceof RequestHandler) {
             $result = $result->handleRequest($this->getRequest(), $model);
         } else {
             if (!$result instanceof SS_HTTPResponse) {
                 user_error("ModelAsController::getNestedController() returned bad object type '" . get_class($result) . "'", E_USER_WARNING);
             }
         }
     } catch (SS_HTTPResponse_Exception $responseException) {
         $result = $responseException->getResponse();
     }
     $this->popCurrent();
     return $result;
 }
Example #6
0
 function read($pref_name, $user_id = false, $die_on_error = false)
 {
     $pref_name = db_escape_string($pref_name);
     $profile = false;
     if (!$user_id) {
         $user_id = $_SESSION["uid"];
         @($profile = $_SESSION["profile"]);
     } else {
         $user_id = sprintf("%d", $user_id);
     }
     if (isset($this->cache[$pref_name])) {
         $tuple = $this->cache[$pref_name];
         return $this->convert($tuple["value"], $tuple["type"]);
     }
     if ($profile) {
         $profile_qpart = "profile = '{$profile}' AND";
     } else {
         $profile_qpart = "profile IS NULL AND";
     }
     if (get_schema_version() < 63) {
         $profile_qpart = "";
     }
     $result = db_query("SELECT value,ttrss_prefs_types.type_name as type_name\n            FROM\n                ttrss_user_prefs,ttrss_prefs,ttrss_prefs_types\n            WHERE\n                {$profile_qpart}\n                ttrss_user_prefs.pref_name = '{$pref_name}' AND\n                ttrss_prefs_types.id = type_id AND\n                owner_uid = '{$user_id}' AND\n                ttrss_user_prefs.pref_name = ttrss_prefs.pref_name");
     if (db_num_rows($result) > 0) {
         $value = db_fetch_result($result, 0, "value");
         $type_name = db_fetch_result($result, 0, "type_name");
         if ($user_id == $_SESSION["uid"]) {
             $this->cache[$pref_name]["type"] = $type_name;
             $this->cache[$pref_name]["value"] = $value;
         }
         return $this->convert($value, $type_name);
     }
     user_error("Fatal error, unknown preferences key: {$pref_name} (owner: {$user_id})", $die_on_error ? E_USER_ERROR : E_USER_WARNING);
     return null;
 }
Example #7
0
 public static function Factory(&$source, $conf_file = NULL, $conf_section = NULL, $strict = TRUE)
 {
     if (!is_array($source)) {
         user_error('$source ' . $source . ' is not an array', E_USER_NOTICE);
     }
     $cage = new Inspekt_Cage_Session();
     $cage->_setSource($source);
     $cage->_parseAndApplyAutoFilters($conf_file);
     if (ini_get('session.use_cookies') || ini_get('session.use_only_cookies')) {
         if (isset($_COOKIE) && isset($_COOKIE[session_name()])) {
             session_id($_COOKIE[session_name()]);
         } elseif ($cookie = Inspekt::makeSessionCage()) {
             session_id($cookie->getAlnum(session_name()));
         }
     } else {
         // we're using session ids passed via GET
         if (isset($_GET) && isset($_GET[session_name()])) {
             session_id($_GET[session_name()]);
         } elseif ($cookie = Inspekt::makeSessionCage()) {
             session_id($cookie->getAlnum(session_name()));
         }
     }
     if ($strict) {
         $source = NULL;
     }
     return $cage;
     register_shutdown_function();
     register_shutdown_function(array($this, '_repopulateSession'));
 }
Example #8
0
 function __construct($agentData, $sessionLink = '', $POST = true, $formVarname = 'form')
 {
     if ($agentData) {
         if ($formVarname) {
             if (isset($agentData->{$formVarname})) {
                 user_error(__CLASS__ . ": Overwriting existing \$agentData->{$formVarname}! If this is the intended behavior, unset(\$agentData->{$formVarname}) to remove this warning.");
             }
             $agentData->{$formVarname} = $this;
         }
         $this->agentData = $agentData;
     } else {
         $this->agentData = false;
     }
     $this->POST = (bool) $POST;
     if ($this->POST) {
         p::canPost();
         if (isset($_POST['_POST_BACKUP'])) {
             // This should only be used for field persistence, not as valid input
             $this->rawValues =& $GLOBALS['_POST_BACKUP'];
             //              $this->filesValues =& $GLOBALS['_FILES_BACKUP'];
         } else {
             $this->rawValues =& $_POST;
             $this->filesValues =& $_FILES;
         }
     } else {
         $this->rawValues =& $_GET;
     }
     if ($sessionLink) {
         s::bind($sessionLink, $this->sessionLink);
         if (!$this->sessionLink) {
             $this->sessionLink = array(0);
         }
     }
 }
 /**
  * Most of the code below was copied from ManyManyComplexTableField.
  * Painful, but necessary, until PHP supports multiple inheritance.
  */
 function __construct($controller, $name, $sourceClass, $fieldList, $detailFormFields = null, $sourceFilter = "", $sourceSort = "Created DESC", $sourceJoin = "")
 {
     parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter, $sourceSort, $sourceJoin);
     $manyManyTable = false;
     $classes = array_reverse(ClassInfo::ancestry($this->controllerClass()));
     foreach ($classes as $class) {
         if ($class != "Object") {
             $singleton = singleton($class);
             $manyManyRelations = $singleton->uninherited('many_many', true);
             if (isset($manyManyRelations) && array_key_exists($this->name, $manyManyRelations)) {
                 $this->manyManyParentClass = $class;
                 $manyManyTable = $class . '_' . $this->name;
                 break;
             }
             $belongsManyManyRelations = $singleton->uninherited('belongs_many_many', true);
             if (isset($belongsManyManyRelations) && array_key_exists($this->name, $belongsManyManyRelations)) {
                 $this->manyManyParentClass = $class;
                 $manyManyTable = $belongsManyManyRelations[$this->name] . '_' . $this->name;
                 break;
             }
         }
     }
     if (!$manyManyTable) {
         user_error("I could not find the relation {$this}-name in " . $this->controllerClass() . " or any of its ancestors.", E_USER_WARNING);
     }
     $tableClasses = ClassInfo::dataClassesFor($this->sourceClass);
     $source = array_shift($tableClasses);
     $sourceField = $this->sourceClass;
     if ($this->manyManyParentClass == $sourceField) {
         $sourceField = 'Child';
     }
     $parentID = $this->controller->ID;
     $this->sourceJoin .= " LEFT JOIN `{$manyManyTable}` ON (`{$source}`.`ID` = `{$sourceField}ID` AND `{$this->manyManyParentClass}ID` = '{$parentID}')";
     $this->joinField = 'Checked';
 }
Example #10
0
 function strripos($haystack, $needle, $offset = null)
 {
     // Sanity check
     if (!is_scalar($haystack)) {
         user_error('strripos() expects parameter 1 to be scalar, ' . gettype($haystack) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_scalar($needle)) {
         user_error('strripos() expects parameter 2 to be scalar, ' . gettype($needle) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_int($offset) && !is_bool($offset) && !is_null($offset)) {
         user_error('strripos() expects parameter 3 to be long, ' . gettype($offset) . ' given', E_USER_WARNING);
         return false;
     }
     // Initialise variables
     $needle = strtolower($needle);
     $haystack = strtolower($haystack);
     $needle_fc = $needle[0];
     $needle_len = strlen($needle);
     $haystack_len = strlen($haystack);
     $offset = (int) $offset;
     $leftlimit = $offset >= 0 ? $offset : 0;
     $p = $offset >= 0 ? $haystack_len : $haystack_len + $offset + 1;
     // Reverse iterate haystack
     while (--$p >= $leftlimit) {
         if ($needle_fc === $haystack[$p] && substr($haystack, $p, $needle_len) === $needle) {
             return $p;
         }
     }
     return false;
 }
Example #11
0
 function array_diff_assoc()
 {
     // Check we have enough arguments
     $args = func_get_args();
     $count = count($args);
     if (count($args) < 2) {
         user_error('Wrong parameter count for array_diff_assoc()', E_USER_WARNING);
         return;
     }
     // Check arrays
     for ($i = 0; $i < $count; $i++) {
         if (!is_array($args[$i])) {
             user_error('array_diff_assoc() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
             return;
         }
     }
     // Get the comparison array
     $array_comp = array_shift($args);
     --$count;
     // Traverse values of the first array
     foreach ($array_comp as $key => $value) {
         // Loop through the other arrays
         for ($i = 0; $i < $count; $i++) {
             // Loop through this arrays key/value pairs and compare
             foreach ($args[$i] as $comp_key => $comp_value) {
                 if ((string) $key === (string) $comp_key && (string) $value === (string) $comp_value) {
                     unset($array_comp[$key]);
                 }
             }
         }
     }
     return $array_comp;
 }
Example #12
0
 function ob_handler($buffer)
 {
     $this->releaseLock();
     $this->queueNext();
     '' !== $buffer && user_error($buffer);
     return '';
 }
 public function transform(FormField $field)
 {
     // Look for a performXXTransformation() method on the field itself.
     // performReadonlyTransformation() is a pretty commonly applied method.
     // Otherwise, look for a transformXXXField() method on this object.
     // This is more commonly done in custom transformations
     // We iterate through each array simultaneously, looking at [0] of both, then [1] of both.
     // This provides a more natural failover scheme.
     $transNames = array_reverse(array_values(ClassInfo::ancestry($this->class)));
     $fieldClasses = array_reverse(array_values(ClassInfo::ancestry($field->class)));
     $len = max(sizeof($transNames), sizeof($fieldClasses));
     for ($i = 0; $i < $len; $i++) {
         // This is lets fieldClasses be longer than transNames
         if ($transName = $transNames[$i]) {
             if ($field->hasMethod('perform' . $transName)) {
                 $funcName = 'perform' . $transName;
                 //echo "<li>$field->class used $funcName";
                 return $field->{$funcName}($this);
             }
         }
         // And this one does the reverse.
         if ($fieldClass = $fieldClasses[$i]) {
             if ($this->hasMethod('transform' . $fieldClass)) {
                 $funcName = 'transform' . $fieldClass;
                 //echo "<li>$field->class used $funcName";
                 return $this->{$funcName}($field);
             }
         }
     }
     user_error("FormTransformation:: Can't perform '{$this->class}' on '{$field->class}'", E_USER_ERROR);
 }
 function array_walk_recursive(&$input, $funcname)
 {
     if (!is_callable($funcname)) {
         if (is_array($funcname)) {
             $funcname = $funcname[0] . '::' . $funcname[1];
         }
         user_error('array_walk_recursive() Not a valid callback ' . $user_func, E_USER_WARNING);
         return;
     }
     if (!is_array($input)) {
         user_error('array_walk_recursive() The argument should be an array', E_USER_WARNING);
         return;
     }
     $args = func_get_args();
     foreach ($input as $key => $item) {
         if (is_array($item)) {
             array_walk_recursive($item, $funcname, $args);
             $input[$key] = $item;
         } else {
             $args[0] =& $item;
             $args[1] =& $key;
             call_user_func_array($funcname, $args);
             $input[$key] = $item;
         }
     }
 }
 /**
  * Add the spam protector field to a form
  * @param 	Form 	the form that the protecter field added into 
  * @param 	string	the name of the field that the protecter field will be added in front of
  * @param 	array 	an associative array 
  * 					with the name of the spam web service's field, for example post_title, post_body, author_name
  * 					and a string of field names
  * @param 	String 	Title for the captcha field
  * @param 	String 	RightTitle for the captcha field
  * @return 	SpamProtector 	object on success or null if the spamprotector class is not found 
  *							also null if spamprotectorfield creation fails. 					
  */
 static function update_form($form, $before = null, $fieldsToSpamServiceMapping = array(), $title = null, $rightTitle = null)
 {
     $protectorClass = self::get_spam_protector();
     // Don't update if no protector is set
     if (!$protectorClass) {
         return false;
     }
     if (!class_exists($protectorClass)) {
         return user_error("Spam Protector class '{$protectorClass}' does not exist. Please define a valid Spam Protector", E_USER_WARNING);
     }
     try {
         $protector = new $protectorClass();
         $field = $protector->getFormField("Captcha", $title, null, $form, $rightTitle);
         if ($field) {
             // update the mapping
             $field->setFieldMapping($fieldsToSpamServiceMapping);
             // add the form field
             if ($before && $form->Fields()->fieldByName($before)) {
                 $form->Fields()->insertBefore($field, $before);
             } else {
                 $form->Fields()->push($field);
             }
         }
     } catch (Exception $e) {
         return user_error("SpamProtectorManager::update_form(): '{$protectorClass}' is not correctly set up. " . $e, E_USER_WARNING);
     }
 }
Example #16
0
 function stripos($haystack, $needle, $offset = null)
 {
     if (!is_scalar($haystack)) {
         user_error('stripos() expects parameter 1 to be string, ' . gettype($haystack) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_scalar($needle)) {
         user_error('stripos() needle is not a string or an integer.', E_USER_WARNING);
         return false;
     }
     if (!is_int($offset) && !is_bool($offset) && !is_null($offset)) {
         user_error('stripos() expects parameter 3 to be long, ' . gettype($offset) . ' given', E_USER_WARNING);
         return false;
     }
     // Manipulate the string if there is an offset
     $fix = 0;
     if (!is_null($offset)) {
         if ($offset > 0) {
             $haystack = substr($haystack, $offset, strlen($haystack) - $offset);
             $fix = $offset;
         }
     }
     $segments = explode(strtolower($needle), strtolower($haystack), 2);
     // Check there was a match
     if (count($segments) === 1) {
         return false;
     }
     $position = strlen($segments[0]) + $fix;
     return $position;
 }
Example #17
0
 function query($query)
 {
     if (!$query) {
         return false;
     }
     if (b1n_DEBUG_MODE) {
         echo "<pre class='debug'>{$query}</pre>";
     }
     if (!$this->isConnected()) {
         user_error("PostgreSQLL NOT CONNECTED");
         return false;
     }
     $result = pg_query($this->db_link, $query);
     if (is_bool($result)) {
         return $result;
     }
     $num = pg_num_rows($result);
     if ($num > 0) {
         for ($i = 0; $i < $num; $i++) {
             $row[] = pg_fetch_array($result, $i, PGSQL_ASSOC);
         }
         return $row;
     }
     return true;
 }
Example #18
0
 /**
  * {@internal we use this to set the data array in Factory()}}
  *
  * @see Factory()
  * @param array $newsource
  */
 function _setSource(&$newsource)
 {
     if (!is_array($newsource)) {
         user_error('$source is not an array', E_USER_NOTICE);
     }
     $this->_source = $newsource;
 }
/**
 * Replace bcpowmod()
 *
 * @category    PHP
 * @package     PHP_Compat
 * @license     LGPL - http://www.gnu.org/licenses/lgpl.html
 * @copyright   2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**>
 * @link        http://php.net/function.bcpowmod
 * @author      Sara Golemon <*****@*****.**>
 * @version     $Revision: 1.1 $
 * @since       PHP 5.0.0
 * @require     PHP 4.0.0 (user_error)
 */
function php_compat_bcpowmod($x, $y, $modulus, $scale = 0)
{
    // Sanity check
    if (!is_scalar($x)) {
        user_error('bcpowmod() expects parameter 1 to be string, ' . gettype($x) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($y)) {
        user_error('bcpowmod() expects parameter 2 to be string, ' . gettype($y) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($modulus)) {
        user_error('bcpowmod() expects parameter 3 to be string, ' . gettype($modulus) . ' given', E_USER_WARNING);
        return false;
    }
    if (!is_scalar($scale)) {
        user_error('bcpowmod() expects parameter 4 to be integer, ' . gettype($scale) . ' given', E_USER_WARNING);
        return false;
    }
    $t = '1';
    while (bccomp($y, '0')) {
        if (bccomp(bcmod($y, '2'), '0')) {
            $t = bcmod(bcmul($t, $x), $modulus);
            $y = bcsub($y, '1');
        }
        $x = bcmod(bcmul($x, $x), $modulus);
        $y = bcdiv($y, '2');
    }
    return $t;
}
Example #20
0
 function array_intersect_key()
 {
     $args = func_get_args();
     if (count($args) < 2) {
         user_error('Wrong parameter count for array_intersect_key()', E_USER_WARNING);
         return;
     }
     // Check arrays
     $array_count = count($args);
     for ($i = 0; $i !== $array_count; $i++) {
         if (!is_array($args[$i])) {
             user_error('array_intersect_key() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
             return;
         }
     }
     // Compare entries
     $result = array();
     foreach ($args[0] as $key1 => $value1) {
         for ($i = 1; $i !== $array_count; $i++) {
             foreach ($args[$i] as $key2 => $value2) {
                 if ((string) $key1 === (string) $key2) {
                     $result[$key1] = $value1;
                 }
             }
         }
     }
     return $result;
 }
 function call_user_func_array($function, $param_arr)
 {
     $param_arr = array_values((array) $param_arr);
     // Sanity check
     if (!is_callable($function)) {
         if (is_array($function) && count($function) > 2) {
             $function = $function[0] . '::' . $function[1];
         }
         $error = sprintf('call_user_func_array() First argument is expected ' . 'to be a valid callback, \'%s\' was given', $function);
         user_error($error, E_USER_WARNING);
         return;
     }
     // Build argument string
     $arg_string = '';
     $comma = '';
     for ($i = 0, $x = count($param_arr); $i < $x; $i++) {
         $arg_string .= $comma . "\$param_arr[{$i}]";
         $comma = ', ';
     }
     // Determine method of calling function
     if (is_array($function)) {
         $object =& $function[0];
         $method = $function[1];
         // Static vs method call
         if (is_string($function[0])) {
             eval("\$retval = {$object}::\$method({$arg_string});");
         } else {
             eval("\$retval = \$object->\$method({$arg_string});");
         }
     } else {
         eval("\$retval = \$function({$arg_string});");
     }
     return $retval;
 }
Example #22
0
 /**
  *	Generate bcrypt hash of string
  *	@return string|FALSE
  *	@param $pw string
  *	@param $salt string
  *	@param $cost int
  **/
 function hash($pw, $salt = NULL, $cost = self::COST)
 {
     if ($cost < 4 || $cost > 31) {
         user_error(self::E_CostArg, E_USER_ERROR);
     }
     $len = 22;
     if ($salt) {
         if (!preg_match('/^[[:alnum:]\\.\\/]{' . $len . ',}$/', $salt)) {
             user_error(self::E_SaltArg, E_USER_ERROR);
         }
     } else {
         $raw = 16;
         $iv = '';
         if (extension_loaded('mcrypt')) {
             $iv = mcrypt_create_iv($raw, MCRYPT_DEV_URANDOM);
         }
         if (!$iv && extension_loaded('openssl')) {
             $iv = openssl_random_pseudo_bytes($raw);
         }
         if (!$iv) {
             for ($i = 0; $i < $raw; $i++) {
                 $iv .= chr(mt_rand(0, 255));
             }
         }
         $salt = str_replace('+', '.', base64_encode($iv));
     }
     $salt = substr($salt, 0, $len);
     $hash = crypt($pw, sprintf('$2y$%02d$', $cost) . $salt);
     return strlen($hash) > 13 ? $hash : FALSE;
 }
Example #23
0
 function bcinvert($a, $n)
 {
     // Sanity check
     if (!is_scalar($a)) {
         user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_scalar($n)) {
         user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING);
         return false;
     }
     $u1 = $v2 = '1';
     $u2 = $v1 = '0';
     $u3 = $n;
     $v3 = $a;
     while (bccomp($v3, '0')) {
         $q0 = bcdiv($u3, $v3);
         $t1 = bcsub($u1, bcmul($q0, $v1));
         $t2 = bcsub($u2, bcmul($q0, $v2));
         $t3 = bcsub($u3, bcmul($q0, $v3));
         $u1 = $v1;
         $u2 = $v2;
         $u3 = $v3;
         $v1 = $t1;
         $v2 = $t2;
         $v3 = $t3;
     }
     if (bccomp($u2, '0') < 0) {
         return bcadd($u2, $n);
     } else {
         return bcmod($u2, $n);
     }
 }
/**
 * Replace str_split()
 *
 * @category    PHP
 * @package     PHP_Compat
 * @license     LGPL - http://www.gnu.org/licenses/lgpl.html
 * @copyright   2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**>
 * @link        http://php.net/function.str_split
 * @author      Aidan Lister <*****@*****.**>
 * @version     $Revision: 1.1 $
 * @since       PHP 5
 * @require     PHP 4.0.0 (user_error)
 */
function php_compat_str_split($string, $split_length = 1)
{
    if (!is_scalar($split_length)) {
        user_error('str_split() expects parameter 2 to be long, ' . gettype($split_length) . ' given', E_USER_WARNING);
        return false;
    }
    $split_length = (int) $split_length;
    if ($split_length < 1) {
        user_error('str_split() The length of each segment must be greater than zero', E_USER_WARNING);
        return false;
    }
    // Select split method
    if ($split_length < 65536) {
        // Faster, but only works for less than 2^16
        preg_match_all('/.{1,' . $split_length . '}/s', $string, $matches);
        return $matches[0];
    } else {
        // Required due to preg limitations
        $arr = array();
        $idx = 0;
        $pos = 0;
        $len = strlen($string);
        while ($len > 0) {
            $blk = $len < $split_length ? $len : $split_length;
            $arr[$idx++] = substr($string, $pos, $blk);
            $pos += $blk;
            $len -= $blk;
        }
        return $arr;
    }
}
 /**
  * @param array $data
  */
 public function addtowishlist(array $data)
 {
     if (!class_exists('WishList')) {
         user_error('Wish List module not installed.');
     }
     $groupedProduct = $this->getController()->data();
     if (empty($data) || empty($data['Product']) || !is_array($data['Product'])) {
         $this->sessionMessage(_t('GroupedCartForm.EMPTY', 'Please select at least one product.'), 'bad');
         $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
         return $response ? $response : $this->controller->redirectBack();
     }
     $list = WishList::current();
     foreach ($data['Product'] as $id => $prodReq) {
         if (!empty($prodReq['Quantity']) && $prodReq['Quantity'] > 0) {
             $prod = Product::get()->byID($id);
             if ($prod && $prod->exists()) {
                 $buyable = $prod;
                 if (isset($prodReq['Attributes'])) {
                     $buyable = $prod->getVariationByAttributes($prodReq['Attributes']);
                     if (!$buyable || !$buyable->exists()) {
                         $this->sessionMessage("{$prod->InternalItemID} is not available with the selected options.", "bad");
                         $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
                         return $response ? $response : $this->controller->redirectBack();
                     }
                 }
                 $list->addBuyable($buyable);
             }
         }
     }
     $this->extend('updateGroupWishListResponse', $this->request, $response, $groupedProduct, $data, $this);
     return $response ? $response : $this->controller->redirect(WishListPage::inst()->Link());
 }
 public static function setupCache($ip)
 {
     $driver = Config::inst()->get('IPInfoCache', 'Driver');
     if (!$driver) {
         foreach (self::$defaultDrivers as $defaultDriver) {
             if (class_exists($defaultDriver)) {
                 $driver = $defaultDriver;
                 break;
             }
         }
         if (!$driver) {
             user_error('A driver needs to be specified');
         }
     }
     $ipService = new $driver();
     $dbJson = $ipService->processIP($ip);
     // do not cache a empty object
     if ($dbJson) {
         $cache = IPInfoCache::create();
         $cache->IP = $ip;
         $cache->Info = $dbJson;
         $cache->write();
     }
     return $ipService->getJSON();
 }
/**
 * Replace property_exists()
 *
 * @category    PHP
 * @package     PHP_Compat
 * @license     LGPL - http://www.gnu.org/licenses/lgpl.html
 * @copyright   2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**>
 * @link        http://php.net/property_exists
 * @author      Christian Stadler <*****@*****.**>
 * @version     $Revision: 269597 $
 * @since       PHP 5.1.0
 * @require     PHP 4.0.0 (user_error)
 */
function php_compat_property_exists($class, $property)
{
    if (!is_string($property)) {
        user_error('property_exists() expects parameter 2 to be a string, ' . gettype($property) . ' given', E_USER_WARNING);
        return false;
    }
    if (is_object($class) || is_string($class)) {
        if (is_string($class)) {
            if (!class_exists($class)) {
                return false;
            }
            $vars = get_class_vars($class);
        } else {
            $vars = get_object_vars($class);
        }
        // Bail out early if get_class_vars or get_object_vars didnt work
        // or returned an empty array
        if (!is_array($vars) || count($vars) <= 0) {
            return false;
        }
        $property = strtolower($property);
        foreach (array_keys($vars) as $varname) {
            if (strtolower($varname) == $property) {
                return true;
            }
        }
        return false;
    }
    user_error('property_exists() expects parameter 1 to be a string or ' . 'an object, ' . gettype($class) . ' given', E_USER_WARNING);
    return false;
}
Example #28
0
 function array_chunk($input, $size, $preserve_keys = false)
 {
     if (!is_array($input)) {
         user_error('array_chunk() expects parameter 1 to be array, ' . gettype($input) . ' given', E_USER_WARNING);
         return;
     }
     if (!is_numeric($size)) {
         user_error('array_chunk() expects parameter 2 to be long, ' . gettype($size) . ' given', E_USER_WARNING);
         return;
     }
     $size = (int) $size;
     if ($size <= 0) {
         user_error('array_chunk() Size parameter expected to be greater than 0', E_USER_WARNING);
         return;
     }
     $chunks = array();
     $i = 0;
     if ($preserve_keys !== false) {
         foreach ($input as $key => $value) {
             $chunks[(int) ($i++ / $size)][$key] = $value;
         }
     } else {
         foreach ($input as $value) {
             $chunks[(int) ($i++ / $size)][] = $value;
         }
     }
     return $chunks;
 }
 public function getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = null)
 {
     $result = null;
     if (!($componentClass = $this->has_many($componentName))) {
         user_error("DataObject::getComponents(): Unknown 1-to-many component '{$componentName}'" . " on class '{$this->class}'", E_USER_ERROR);
     }
     if ($join) {
         throw new \InvalidArgumentException('The $join argument has been removed. Use leftJoin($table, $joinClause) instead.');
     }
     // If we haven't been written yet, we can't save these relations, so use a list that handles this case
     if (!$this->ID) {
         if (!isset($this->unsavedRelations[$componentName])) {
             $this->unsavedRelations[$componentName] = UnsavedRelationList::create($this->class, $componentName, $componentClass);
         }
         return $this->unsavedRelations[$componentName];
     }
     $joinField = $this->getRemoteJoinField($componentName, 'has_many');
     $result = HasManyList::create($componentClass, $joinField);
     if ($this->model) {
         $result->setDataModel($this->model);
     }
     $result = $result->forForeignID($this->ID);
     $result = $result->where($filter)->limit($limit)->sort($sort);
     return $result;
 }
 function array_intersect_assoc()
 {
     // Sanity check
     $args = func_get_args();
     if (count($args) < 2) {
         user_error('wrong parameter count for array_intersect_assoc()', E_USER_WARNING);
         return;
     }
     // Check arrays
     $array_count = count($args);
     for ($i = 0; $i !== $array_count; $i++) {
         if (!is_array($args[$i])) {
             user_error('array_intersect_assoc() Argument #' . ($i + 1) . ' is not an array', E_USER_WARNING);
             return;
         }
     }
     // Compare entries
     $intersect = array();
     foreach ($args[0] as $key => $value) {
         $intersect[$key] = $value;
         for ($i = 1; $i < $array_count; $i++) {
             if (!isset($args[$i][$key]) || $args[$i][$key] != $value) {
                 unset($intersect[$key]);
                 break;
             }
         }
     }
     return $intersect;
 }