Пример #1
0
 private static function _getTextMode()
 {
     if (!function_exists('getText') || strncasecmp(PHP_OS, 'WIN', 3) == 0) {
         return self::GETTEXT_MODE_LIBRARY;
     }
     return self::GETTEXT_MODE_NATIVE;
 }
Пример #2
0
 /**
  * Constructs absolute URL from Request object.
  * @return string|NULL
  */
 public function constructUrl(PresenterRequest $appRequest, Url $refUrl)
 {
     if ($this->flags & self::ONE_WAY) {
         return NULL;
     }
     $params = $appRequest->getParameters();
     // presenter name
     $presenter = $appRequest->getPresenterName();
     if (strncasecmp($presenter, $this->module, strlen($this->module)) === 0) {
         $params[self::PRESENTER_KEY] = substr($presenter, strlen($this->module));
     } else {
         return NULL;
     }
     // remove default values; NULL values are retain
     foreach ($this->defaults as $key => $value) {
         if (isset($params[$key]) && $params[$key] == $value) {
             // intentionally ==
             unset($params[$key]);
         }
     }
     $url = ($this->flags & self::SECURED ? 'https://' : 'http://') . $refUrl->getAuthority() . $refUrl->getPath();
     $sep = ini_get('arg_separator.input');
     $query = http_build_query($params, '', $sep ? $sep[0] : '&');
     if ($query != '') {
         // intentionally ==
         $url .= '?' . $query;
     }
     return $url;
 }
Пример #3
0
 /**
  * Match a list of proxies.
  *
  * @param array $list The list of proxies in front of this service.
  *
  * @return bool
  */
 public function matches(array $list)
 {
     $list = array_values($list);
     // Ensure that we have an indexed array
     if ($this->isSizeValid($list)) {
         $mismatch = false;
         foreach ($this->chain as $i => $search) {
             $proxy_url = $list[$i];
             if (preg_match('/^\\/.*\\/[ixASUXu]*$/s', $search)) {
                 if (preg_match($search, $proxy_url)) {
                     phpCAS::trace("Found regexp " . $search . " matching " . $proxy_url);
                 } else {
                     phpCAS::trace("No regexp match " . $search . " != " . $proxy_url);
                     $mismatch = true;
                     break;
                 }
             } else {
                 if (strncasecmp($search, $proxy_url, strlen($search)) == 0) {
                     phpCAS::trace("Found string " . $search . " matching " . $proxy_url);
                 } else {
                     phpCAS::trace("No match " . $search . " != " . $proxy_url);
                     $mismatch = true;
                     break;
                 }
             }
         }
         if (!$mismatch) {
             phpCAS::trace("Proxy chain matches");
             return true;
         }
     } else {
         phpCAS::trace("Proxy chain skipped: size mismatch");
     }
     return false;
 }
Пример #4
0
 public static function run()
 {
     if (!Site::init(!empty($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : '')) {
         @header('HTTP/1.1 404 Not Found');
         exit;
     }
     $method = Core::getRequestMethod();
     if (!in_array($method, array('get', 'put', 'delete', 'post'))) {
         @header("HTTP/1.1 501 Not Implemented");
         exit;
     }
     $data = Core::getRequestData();
     if (empty($data[$method]) && !in_array($_SERVER['REQUEST_URI'], array($_SERVER['SCRIPT_NAME'], "", "/"))) {
         $data[$method] = $_SERVER['REQUEST_URI'];
     }
     $resource = Core::getResource($data, $method);
     $staticFolders = array('/cache/', '/static/', '/uploads/', '/vendor/');
     foreach ($staticFolders as $folder) {
         if (strncasecmp($resource, $folder, strlen($folder)) === 0) {
             @header('HTTP/1.1 404 Not Found');
             exit;
         }
     }
     App::set(App::parse($resource));
     Core::resource($resource);
     Module::init();
     $response = Response\Factory::get($resource, $method);
     if (empty($response)) {
         @header('HTTP/1.1 406 Not Acceptable');
         exit;
     }
     Request::init($response, $data);
     echo Request::run($resource, $method);
 }
Пример #5
0
 /**
  * Copy file.
  *
  * @param string $source source file path
  * @param string $dest destination file path.
  * @param bool|null $overwrite whether to overwrite destination file if it already exist.
  * @return bool whether the copying operation succeeded.
  */
 public static function copyFile($source, $dest, $overwrite = null)
 {
     if (!is_file($source)) {
         Console::stderr("File {$dest} skipped ({$source} not exist)", Console::FG_GREEN);
         return true;
     }
     if (is_file($dest)) {
         if (file_get_contents($source) === file_get_contents($dest)) {
             Console::stdout("File {$dest} unchanged", Console::FG_GREEN);
             return true;
         }
         Console::stdout("File {$dest} exist, overwrite? [Yes|No|Quit]", Console::FG_YELLOW);
         $answer = $overwrite === null ? Console::stdin() : $overwrite;
         if (!strncasecmp($answer, 'q', 1) || strncasecmp($answer, 'y', 1) !== 0) {
             Console::stdout("Skipped {$dest}", Console::FG_GREEN);
             return false;
         }
         file_put_contents($dest, file_get_contents($source));
         Console::stdout("Overwritten {$dest}", Console::FG_GREEN);
         return true;
     }
     if (!is_dir(dirname($dest))) {
         @mkdir(dirname($dest), 0777, true);
     }
     file_put_contents($dest, file_get_contents($source));
     Console::stdout("Copied {$source} to {$dest}", Console::FG_GREEN);
     return true;
 }
Пример #6
0
 function substr_compare($main_str, $str, $offset, $length = NULL, $case_insensitivity = false)
 {
     $offset = (int) $offset;
     // Throw a warning because the offset is invalid
     if ($offset >= strlen($main_str)) {
         trigger_error('The start position cannot exceed initial string length.', E_USER_WARNING);
         return false;
     }
     // We are comparing the first n-characters of each string, so let's use the PHP function to do it
     if ($offset == 0 && is_int($length) && $case_insensitivity === true) {
         return strncasecmp($main_str, $str, $length);
     }
     // Get the substring that we are comparing
     if (is_int($length)) {
         $main_substr = substr($main_str, $offset, $length);
         $str_substr = substr($str, 0, $length);
     } else {
         $main_substr = substr($main_str, $offset);
         $str_substr = $str;
     }
     // Return a case-insensitive comparison of the two strings
     if ($case_insensitivity === true) {
         return strcasecmp($main_substr, $str_substr);
     }
     // Return a case-sensitive comparison of the two strings
     return strcmp($main_substr, $str_substr);
 }
Пример #7
0
 /**
  * @brief Widget execution
  * Get extra_vars declared in ./widgets/widget/conf/info.xml as arguments
  * After generating the result, do not print but return it.
  */
 function proc($args)
 {
     // Set a path of the template skin (values of skin, colorset settings)
     $tpl_path = sprintf('%sskins/%s', $this->widget_path, $args->skin);
     Context::set('colorset', $args->colorset);
     // Specify a template file
     if (Context::get('is_logged')) {
         $tpl_file = 'login_info';
     } else {
         $tpl_file = 'login_form';
     }
     // Get the member configuration
     $oModuleModel = getModel('module');
     $this->member_config = $oModuleModel->getModuleConfig('member');
     Context::set('member_config', $this->member_config);
     // Set a flag to check if the https connection is made when using SSL and create https url
     $ssl_mode = false;
     $useSsl = Context::getSslStatus();
     if ($useSsl != 'none') {
         if (strncasecmp('https://', Context::getRequestUri(), 8) === 0) {
             $ssl_mode = true;
         }
     }
     Context::set('ssl_mode', $ssl_mode);
     // Compile a template
     $oTemplate =& TemplateHandler::getInstance();
     return $oTemplate->compile($tpl_path, $tpl_file);
 }
Пример #8
0
 /**
  * Constructor
  *
  * @param   string|RFormatter $format      Output format ID, or formatter instance defaults to 'html'
  */
 public function __construct($format = 'html')
 {
     static $didIni = false;
     if (!$didIni) {
         $didIni = true;
         foreach (array_keys(static::$config) as $key) {
             $iniVal = get_cfg_var('ref.' . $key);
             print_r($iniVal);
             if ($iniVal !== false) {
                 static::$config[$key] = $iniVal;
             }
         }
     }
     if ($format instanceof RFormatter) {
         $this->fmt = $format;
     } else {
         $format = __NAMESPACE__ . '\\' . (isset(static::$config['formatters'][$format]) ? static::$config['formatters'][$format] : 'R' . ucfirst($format) . 'Formatter');
         if (!class_exists($format, true)) {
             throw new \Exception(sprintf('%s class not found', $format));
         }
         $this->fmt = new $format();
     }
     if (static::$env) {
         return;
     }
     static::$env = array('is54' => version_compare(PHP_VERSION, '5.4') >= 0, 'is546' => version_compare(PHP_VERSION, '5.4.6') >= 0, 'is56' => version_compare(PHP_VERSION, '5.6') >= 0, 'curlActive' => function_exists('curl_version'), 'mbStr' => function_exists('mb_detect_encoding'), 'supportsDate' => strncasecmp(PHP_OS, 'WIN', 3) !== 0 || version_compare(PHP_VERSION, '5.3.10') >= 0);
 }
Пример #9
0
 /**
  * Collects the table column metadata.
  * @param CDbTableSchema the table metadata
  * @return boolean whether the table exists in the database
  */
 protected function findColumns($table)
 {
     $sql = "PRAGMA table_info({$table->rawName})";
     $columns = $this->getDbConnection()->createCommand($sql)->queryAll();
     if (empty($columns)) {
         return false;
     }
     foreach ($columns as $column) {
         $c = $this->createColumn($column);
         $table->columns[$c->name] = $c;
         if ($c->isPrimaryKey) {
             if ($table->primaryKey === null) {
                 $table->primaryKey = $c->name;
             } else {
                 if (is_string($table->primaryKey)) {
                     $table->primaryKey = array($table->primaryKey, $c->name);
                 } else {
                     $table->primaryKey[] = $c->name;
                 }
             }
         }
     }
     if (is_string($table->primaryKey) && !strncasecmp($table->columns[$table->primaryKey]->dbType, 'int', 3)) {
         $table->sequenceName = '';
     }
     return true;
 }
Пример #10
0
 function getBlockCode_ViewImage()
 {
     $sSiteUrl = $this->_aSite['url'];
     $aFile = BxDolService::call('photos', 'get_photo_array', array($this->_aSite['photo'], 'file'), 'Search');
     $sImage = $aFile['no_image'] ? '' : $aFile['file'];
     // BEGIN STW INTEGRATION
     if (getParam('bx_sites_account_type') != 'No Automated Screenshots') {
         if ($sImage == '') {
             $aSTWOptions = array();
             bx_sites_import('STW');
             $sThumbHTML = getThumbnailHTML($sSiteUrl, $aSTWOptions, false, false);
         }
     }
     // END STW INTEGRATION
     $sVote = '';
     if (strncasecmp($sSiteUrl, 'http://', 7) != 0 && strncasecmp($sSiteUrl, 'https://', 8) != 0) {
         $sSiteUrl = 'http://' . $sSiteUrl;
     }
     if ($this->_oConfig->isVotesAllowed() && $this->_oSites->oPrivacy->check('rate', $this->_aSite['id'], $this->_oSites->iOwnerId)) {
         bx_import('BxTemplVotingView');
         $oVotingView = new BxTemplVotingView('bx_sites', $this->_aSite['id']);
         if ($oVotingView->isEnabled()) {
             $sVote = $oVotingView->getBigVoting();
         }
     }
     $sContent = $this->_oTemplate->parseHtmlByName('view_image.html', array('title' => $this->_aSite['title'], 'site_url' => $sSiteUrl, 'site_url_view' => $this->_aSite['url'], 'bx_if:is_image' => array('condition' => $sThumbHTML == false, 'content' => array('image' => $sImage ? $sImage : $this->_oTemplate->getImageUrl('no-image-thumb.png'))), 'bx_if:is_thumbhtml' => array('condition' => $sThumbHTML != '', 'content' => array('thumbhtml' => $sThumbHTML)), 'vote' => $sVote, 'view_count' => $this->_aSite['views']));
     return array($sContent, array(), array(), false);
 }
Пример #11
0
 /**
  * Index
  */
 public function actionIndex()
 {
     // define confirm message
     $confirmMsg = "\r\n";
     $confirmMsg .= "Please confirm:\r\n";
     $confirmMsg .= "\r\n";
     $confirmMsg .= "    From        [ {$this->from} ]\r\n";
     $confirmMsg .= "    To          [ {$this->to} ]\r\n";
     $confirmMsg .= "    Namespace   [ {$this->namespace} ]\r\n";
     $confirmMsg .= "\r\n";
     $confirmMsg .= "(yes|no)";
     // confirm copy
     $confirm = $this->prompt($confirmMsg, ["required" => true, "default" => "no"]);
     // process copy
     if (strncasecmp($confirm, "y", 1) === 0) {
         // handle aliases and copy files
         $fromPath = Yii::getAlias($this->from);
         $toPath = Yii::getAlias($this->to);
         $this->copyFiles($fromPath, $toPath, $this->namespace);
     } else {
         echo "\r\n";
         echo "--- Copy cancelled! --- \r\n";
         echo "\r\n";
         echo "You can specify the paths using:\r\n\r\n";
         echo "    php yii user/copy --from=@vendor/amnah/yii2-user";
         echo " --to=@app/modules/user --namespace=app\\\\modules\\\\user";
         echo "\r\n";
     }
 }
Пример #12
0
 protected function statement($key, $value)
 {
     if (strncasecmp($key, 'etag', 4) == 0) {
         $value = '"' . $value . '"';
     }
     return sprintf('%s: %s', $key, (string) $value);
 }
Пример #13
0
 public function handle(Event $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getParameter('request_type')) {
         return false;
     }
     $exception = $event->getParameter('exception');
     $request = $event->getParameter('request');
     if (null !== $this->logger) {
         $this->logger->err(sprintf('%s: %s (uncaught exception)', get_class($exception), $exception->getMessage()));
     } else {
         error_log(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));
     }
     $logger = null !== $this->logger ? $this->logger->getDebugLogger() : null;
     $attributes = array('_controller' => $this->controller, 'exception' => FlattenException::create($exception), 'logger' => $logger, 'format' => 0 === strncasecmp(PHP_SAPI, 'cli', 3) ? 'txt' : $request->getRequestFormat());
     $request = $request->duplicate(null, null, $attributes);
     try {
         $response = $event->getSubject()->handle($request, HttpKernelInterface::SUB_REQUEST, true);
     } catch (\Exception $e) {
         if (null !== $this->logger) {
             $this->logger->err(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage()));
         }
         // re-throw the exception as this is a catch-all
         throw new \RuntimeException('Exception thrown when handling an exception.', 0, $e);
     }
     $event->setReturnValue($response);
     return true;
 }
function test_mimetypes($mimetypes)
{
    foreach ($mimetypes as $mimetype) {
        list($host, $port) = explode(':', PHP_CLI_SERVER_ADDRESS);
        $port = intval($port) ?: 80;
        $fp = fsockopen($host, $port, $errno, $errstr, 0.5);
        if (!$fp) {
            die('Connect failed');
        }
        file_put_contents(__DIR__ . "/foo.{$mimetype}", '');
        $header = <<<HEADER
GET /foo.{$mimetype} HTTP/1.1
Host: {$host}


HEADER;
        if (fwrite($fp, $header)) {
            while (!feof($fp)) {
                $text = fgets($fp);
                if (strncasecmp("Content-type:", $text, 13) == 0) {
                    echo "foo.{$mimetype} => ", $text;
                }
            }
            @unlink(__DIR__ . "/foo.{$mimetype}");
            fclose($fp);
        }
    }
}
Пример #15
0
 protected function _CreateColumn($Name, $Type, $Null, $Default, $KeyType)
 {
     $Length = '';
     $Precision = '';
     // Check to see if the type starts with a 'u' for unsigned.
     if (is_string($Type) && strncasecmp($Type, 'u', 1) == 0) {
         $Type = substr($Type, 1);
         $Unsigned = TRUE;
     } else {
         $Unsigned = FALSE;
     }
     // Check for a length in the type.
     if (is_string($Type) && preg_match('/(\\w+)\\s*\\(\\s*(\\d+)\\s*(?:,\\s*(\\d+)\\s*)?\\)/', $Type, $Matches)) {
         $Type = $Matches[1];
         $Length = $Matches[2];
         if (count($Matches) >= 4) {
             $Precision = $Matches[3];
         }
     }
     $Column = new stdClass();
     $Column->Name = $Name;
     $Column->Type = is_array($Type) ? 'enum' : $Type;
     $Column->Length = $Length;
     $Column->Precision = $Precision;
     $Column->Enum = is_array($Type) ? $Type : FALSE;
     $Column->AllowNull = $Null;
     $Column->Default = $Default;
     $Column->KeyType = $KeyType;
     $Column->Unsigned = $Unsigned;
     $Column->AutoIncrement = FALSE;
     return $Column;
 }
Пример #16
0
 public function toExecLsCommand(CliGuy $I)
 {
     $command = strncasecmp(PHP_OS, 'WIN', 3) == 0 ? 'dir' : 'ls';
     $res = $I->taskExec($command)->run();
     verify($res->getMessage())->contains('src');
     verify($res->getMessage())->contains('codeception.yml');
 }
Пример #17
0
 public function run($args)
 {
     if (!isset($this->servers)) {
         echo "No server specified in config!";
         exit;
     }
     if (!isset($this->aliases)) {
         echo "No alias defined in config!";
         exit;
     }
     if (!isset($args[2])) {
         $this->getHelp();
         exit;
     }
     $src = $args[0];
     $dest = $args[1];
     $alias = $args[2];
     $path = Yii::getPathOfAlias($this->aliases[$alias]);
     $relativePath = str_replace(Yii::app()->basePath, "", $path);
     $srcUrl = $this->servers[$src] . $relativePath . "/";
     $destUrl = $this->servers[$dest] . $relativePath . "/";
     echo "Start rsync of '" . $alias . "' (" . $relativePath . ") from '" . $src . "' to '" . $dest . "'? [Yes|No] ";
     if (!strncasecmp(trim(fgets(STDIN)), 'y', 1)) {
         $cmd = "rsync -av " . $srcUrl . " " . $destUrl;
         echo "\n" . $cmd . "\n";
         system($cmd, $output);
     } else {
         echo "Skipped.\n";
     }
 }
Пример #18
0
 public function __unset($name)
 {
     $setter = 'set' . $name;
     if (method_exists($this, $setter)) {
         $this->{$setter}(null);
     } elseif (strncasecmp($name, 'on', 2) === 0 && method_exists($this, $name)) {
         unset($this->_e[strtolower($name)]);
     } elseif (is_array($this->_m)) {
         if (isset($this->_m[$name])) {
             $this->detachBehavior($name);
         } else {
             foreach ($this->_m as $object) {
                 if ($object->getEnabled()) {
                     if (property_exists($object, $name)) {
                         return $object->{$name} = null;
                     } elseif ($object->canSetProperty($name)) {
                         return $object->{$setter}(null);
                     }
                 }
             }
         }
     } elseif (method_exists($this, 'get' . $name)) {
         throw new CException(Yii::t('yii', 'Property "{class}.{property}" is read only.', array('{class}' => get_class($this), '{property}' => $name)));
     }
 }
Пример #19
0
 /**
  * @brief Message output
  **/
 function dispMessage()
 {
     // Get configurations (using module model object)
     $oModuleModel = getModel('module');
     $config = $oModuleModel->getModuleConfig('message');
     if (!$config->mskin) {
         $config->mskin = 'default';
     }
     // Set the template path
     $template_path = sprintf('%sm.skins/%s', $this->module_path, $config->mskin);
     // Get the member configuration
     $oModuleModel = getModel('module');
     $member_config = $oModuleModel->getModuleConfig('member');
     Context::set('member_config', $member_config);
     // Set a flag to check if the https connection is made when using SSL and create https url
     $ssl_mode = false;
     if ($member_config->enable_ssl == 'Y') {
         if (strncasecmp('https://', Context::getRequestUri(), 8) === 0) {
             $ssl_mode = true;
         }
     }
     Context::set('ssl_mode', $ssl_mode);
     Context::set('system_message', nl2br($this->getMessage()));
     Context::set('act', 'procMemberLogin');
     Context::set('mid', '');
     $this->setTemplatePath($template_path);
     $this->setTemplateFile('system_message');
 }
Пример #20
0
 protected function getCallstack($logs)
 {
     $stack = array();
     $results = array();
     $n = 0;
     foreach ($logs as $log) {
         if ($log[1] !== CLogger::LEVEL_PROFILE) {
             continue;
         }
         $message = $log[0];
         if (!strncasecmp($message, 'begin:', 6)) {
             $log[0] = substr($message, 6);
             $log[4] = $n;
             $stack[] = $log;
             $n++;
         } else {
             if (!strncasecmp($message, 'end:', 4)) {
                 $token = substr($message, 4);
                 if (($last = array_pop($stack)) !== null && $last[0] === $token) {
                     $delta = $log[3] - $last[3];
                     $results[$last[4]] = array($token, $delta, count($stack));
                 } else {
                     throw new CException(Yii::t('yii', 'CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', array('{token}' => $token)));
                 }
             }
         }
     }
     // remaining entries should be closed here
     $now = microtime(true);
     while (($last = array_pop($stack)) !== null) {
         $results[$last[4]] = array($last[0], $now - $last[3], count($stack));
     }
     ksort($results);
     return array_map(array($this, 'formatLog'), $results);
 }
Пример #21
0
 /**
  * Locate a font
  *
  * @param   string font
  * @return  string
  */
 protected function locate($font)
 {
     $windows = strncasecmp(PHP_OS, 'Win', 3) === 0;
     // Compile extension list
     $extensions = ['.ttf', '.TTF'];
     if (strncasecmp($ext = substr($font, -4, 4), '.ttf', 4) === 0) {
         $font = substr($font, 0, -4);
         $extensions[] = $ext;
     }
     // Compose TTF search path
     if ($windows) {
         $search = ['.\\', getenv('WINDIR') . '\\fonts\\'];
     } else {
         $search = ['./', '/usr/X11R6/lib/X11/fonts/TrueType/', '/usr/X11R6/lib/X11/fonts/truetype/', '/usr/X11R6/lib/X11/fonts/TTF/', '/usr/share/fonts/TrueType/', '/usr/share/fonts/truetype/', '/usr/openwin/lib/X11/fonts/TrueType/'];
     }
     // Check for absolute filenames
     if (DIRECTORY_SEPARATOR === $font[0] || $windows && strlen($font) > 1 && (':' === $font[1] || '/' === $font[0])) {
         array_unshift($search, dirname($font) . DIRECTORY_SEPARATOR);
         $font = basename($font);
     }
     // Search
     foreach ($search as $dir) {
         foreach ($extensions as $ext) {
             if (file_exists($q = $dir . $font . $ext)) {
                 return $q;
             }
         }
     }
     throw new \lang\IllegalArgumentException('Could not locate font "' . $font . '[' . implode(', ', $extensions) . ']" in ' . \xp::stringOf($search));
 }
Пример #22
0
 /**
  * @param string reference
  * @param array reference
  * @return bool
  * @throws InvalidArgumentException
  */
 public static function parse(&$name, array &$args)
 {
     $mode = $by = NULL;
     if (strncasecmp($name, 'findBy', 6) === 0) {
         $mode = 'findBy';
         $by = substr($name, 6);
     } else {
         if (strncasecmp($name, 'getBy', 5) === 0) {
             $mode = 'getBy';
             $by = substr($name, 5);
         }
     }
     if ($mode and $by) {
         $where = array();
         foreach (explode('And', $by) as $n => $key) {
             if ($key[0] != "_") {
                 $key[0] = $key[0] | " ";
             }
             // lcfirst
             if (!array_key_exists($n, $args)) {
                 throw new InvalidArgumentException("There is no value for '{$key}' in '{$name}'.");
             }
             $where[$key] = $args[$n];
             unset($args[$n]);
         }
         if (count($args)) {
             throw new InvalidArgumentException("There is extra value in '{$name}'.");
         }
         $name = $mode;
         $args = $where;
         return true;
     }
     return false;
 }
 /**
  * Result postprocessor, that transforms the results to hash.
  */
 protected function prepareResult($rows)
 {
     // Process ARRAY_KEY feature.
     if (is_array($rows) && $rows) {
         // Find ARRAY_KEY* AND PARENT_KEY fields in field list.
         $pk = null;
         $ak = array();
         foreach (current($rows) as $fieldName => $dummy) {
             if (0 == strncasecmp($fieldName, self::ALIAS_ARRAY_KEY, strlen(self::ALIAS_ARRAY_KEY))) {
                 $ak[] = $fieldName;
             } else {
                 if (0 == strncasecmp($fieldName, self::ALIAS_PARENT_KEY, strlen(self::ALIAS_PARENT_KEY))) {
                     $pk = $fieldName;
                 }
             }
         }
         natsort($ak);
         // sort ARRAY_KEY* using natural comparision
         if ($ak) {
             // Tree-based array? Fields: ARRAY_KEY, PARENT_KEY
             if ($pk !== null) {
                 return $this->prepareResult2Forest($rows, $ak[0], $pk);
             }
             // Key-based array? Fields: ARRAY_KEY.
             return $this->prepareResult2Hash($rows, $ak);
         }
     }
     return $rows;
 }
Пример #24
0
 public static function GetAccountByName($name)
 {
     if (strlen($name) <= 0) {
         throw new Exception("name");
     }
     $arResult = null;
     if (!strncasecmp("group-", $name, 6) && CModule::IncludeModule("socialnetwork")) {
         $groupId = intval(substr($name, 6));
         if (array_key_exists($groupId, self::$accountsCache["groups"])) {
             return self::$accountsCache["groups"][$groupId];
         }
         $dbGroup = CSocNetGroup::GetList(array(), array("ID" => $groupId, "ACTIVE" => "Y"), false, false, array("ID", "SITE_ID", "NAME", "OWNER_ID", "OWNER_EMAIL"));
         if ($arGroup = $dbGroup->Fetch()) {
             $arResult = self::ExtractAccountFromGroup($arGroup);
             self::$accountsCache["groups"][$arGroup["ID"]] = $arResult;
         }
         return $arResult;
     }
     if (array_key_exists($name, self::$accountsCacheMap)) {
         return self::$accountsCache["users"][self::$accountsCacheMap[$name]];
     }
     $dbUsers = CUser::GetList($by = "ID", $order = "desc", array("LOGIN_EQUAL_EXACT" => $name, "ACTIVE" => "Y"));
     if ($arUser = $dbUsers->Fetch()) {
         $arResult = self::ExtractAccountFromUser($arUser);
         self::$accountsCache["users"][$arUser["ID"]] = $arResult;
         self::$accountsCacheMap[$name] = $arUser["ID"];
     }
     return $arResult;
 }
Пример #25
0
 function getPatches($stop = null)
 {
     $start = $this->start;
     $stop = $stop ? $stop : $this->end;
     $patches = array();
     while (true) {
         $next = glob($this->sqldir . substr($start, 0, 8) . '-*.patch.sql');
         if (count($next) == 1) {
             $patches[] = $next[0];
             $start = substr(basename($next[0]), 9, 8);
         } elseif (count($next) == 0) {
             # There are no patches leaving the current signature. We
             # have to assume that we've applied all the available
             # patches.
             break;
         } else {
             # Problem -- more than one patch exists from this snapshot.
             # We probably need a graph approach to solve this.
             break;
         }
         # Break if we've reached our target stop.
         if (!$start || !strncasecmp($start, $stop, 8)) {
             break;
         }
     }
     return $patches;
 }
Пример #26
0
 static function __static()
 {
     if (function_exists('random_bytes')) {
         self::$sources[self::SYSTEM] = ['bytes' => 'random_bytes', 'ints' => 'random_int'];
     }
     if (function_exists('mcrypt_create_iv')) {
         self::$sources[self::MCRYPT] = ['bytes' => [__CLASS__, self::MCRYPT], 'ints' => null];
     }
     if (strncasecmp(PHP_OS, 'Win', 3) !== 0 && is_readable('/dev/urandom')) {
         self::$sources[self::URANDOM] = ['bytes' => [__CLASS__, self::URANDOM], 'ints' => null];
     }
     // All of these above are secure pseudo-random sources
     if (!empty(self::$sources)) {
         self::$sources[self::SECURE] =& self::$sources[key(self::$sources)];
     }
     if (function_exists('openssl_random_pseudo_bytes')) {
         self::$sources[self::OPENSSL] = ['bytes' => [__CLASS__, self::OPENSSL], 'ints' => null];
         if (!isset(self::$sources[self::SECURE])) {
             self::$sources[self::SECURE] =& self::$sources[self::OPENSSL];
         }
     }
     // The Mersenne Twister algorithm is always available
     self::$sources[self::MTRAND] = ['bytes' => [__CLASS__, self::MTRAND], 'ints' => 'mt_rand'];
     self::$sources[self::BEST] =& self::$sources[key(self::$sources)];
     self::$sources[self::FAST] =& self::$sources[self::MTRAND];
 }
 protected function catchMessageId($line)
 {
     if (0 === strncasecmp($this->bodyLine, 'Message-Id:', 11) && preg_match('/^Message-Id:\\s+<(.*)>/i', $this->bodyLine, $m)) {
         $this->unregister(array(__FUNCTION__ => T_MAIL_BODY));
         $this->reportMessageId($m[1]);
     }
 }
Пример #28
0
 public static function getGridObject($sObject)
 {
     $oDb = BxDolDb::getInstance();
     $sQuery = $oDb->prepare("SELECT * FROM `sys_objects_grid` WHERE `object` = ?", $sObject);
     $aObject = $oDb->getRow($sQuery);
     if (!$aObject || !is_array($aObject)) {
         return false;
     }
     // paginate
     if (!empty($aObject['paginate_url']) && 0 != strncasecmp($aObject['paginate_url'], 'http://', 7) && 0 != strncasecmp($aObject['paginate_url'], 'https://', 8)) {
         $aObject['paginate_url'] = BX_DOL_URL_ROOT . $aObject['paginate_url'];
     }
     // filter
     if ($aObject['filter_fields']) {
         $aObject['filter_fields'] = array_map('trim', explode(',', $aObject['filter_fields']));
     }
     if ($aObject['filter_fields_translatable']) {
         $aObject['filter_fields_translatable'] = array_map('trim', explode(',', $aObject['filter_fields_translatable']));
     }
     // sorting
     if ($aObject['sorting_fields']) {
         $aObject['sorting_fields'] = array_map('trim', explode(',', $aObject['sorting_fields']));
     }
     if ($aObject['sorting_fields_translatable']) {
         $aObject['sorting_fields_translatable'] = array_map('trim', explode(',', $aObject['sorting_fields_translatable']));
         $aObject['sorting_fields'] = array_merge($aObject['sorting_fields'], $aObject['sorting_fields_translatable']);
     }
     // get fields
     $sQuery = $oDb->prepare("SELECT * FROM `sys_grid_fields` WHERE `object` = ? ORDER BY `order`", $sObject);
     $aFields = $oDb->getAllWithKey($sQuery, 'name');
     if (!$aFields || !is_array($aFields)) {
         // it is impossible to have grid without any fields
         return false;
     }
     foreach ($aFields as $sKey => $aRow) {
         $aObject['fields'][$sKey] = array('title' => _t($aRow['title']), 'width' => $aRow['width'], 'translatable' => $aRow['translatable'], 'chars_limit' => $aRow['chars_limit']);
         if (empty($aRow['params'])) {
             continue;
         }
         $aAdd = unserialize($aRow['params']);
         if (!empty($aAdd) && is_array($aAdd)) {
             $aObject['fields'][$sKey] = array_merge($aObject['fields'][$sKey], $aAdd);
         }
     }
     // get actions
     $a = array('bulk', 'single', 'independent');
     foreach ($a as $sActionType) {
         $sActionField = 'actions_' . $sActionType;
         $aObject[$sActionField] = array();
         $sQuery = $oDb->prepare("SELECT * FROM `sys_grid_actions` WHERE `object` = ? AND `type` = ? ORDER BY `order`", $sObject, $sActionType);
         $aActions = $oDb->getAllWithKey($sQuery, 'name');
         if (!$aActions || !is_array($aActions)) {
             continue;
         }
         foreach ($aActions as $sKey => $aRow) {
             $aObject[$sActionField][$sKey] = $aRow['title'] || $aRow['icon'] ? array('title' => _t($aRow['title']), 'icon' => $aRow['icon'], 'confirm' => $aRow['confirm'], 'icon_only' => $aRow['icon_only']) : array();
         }
     }
     return $aObject;
 }
Пример #29
0
/**
 *
 *
 * @file modifier.domain.php
 * @package plugins
 * @author liyudong@baidu.com
 * @date 2011-11-03 10:47
 */
function smarty_modifier_domain($string, $encodeURI = false)
{
    $logArr['smarty_modifier'] = "modifier_domain";
    $status = 0;
    $logArr['url'] = $string;
    $domain = $string;
    if (strncasecmp($domain, "http://", 7) == 0) {
        $domain = substr($domain, 7);
    } elseif (strncasecmp($domain, "url:", 4) == 0) {
        $pos = strspn($domain, " ", 4);
        $domain = substr($domain, 4 + $pos);
        if (strncasecmp($domain, "http://", 7) == 0) {
            $domain = substr($domain, 7);
        }
    }
    if (strlen($domain) == 0) {
        $domain = $string;
    }
    if ($encodeURI) {
        $result = hilight_encodeURI($domain);
        $logArr['result'] = $result;
        if (false === $result) {
            $status = -1;
            CLog::warning("fail to call hilight_domain", $status, $logArr, 1);
            return $domain;
        }
    } else {
        $result = $domain;
    }
    return $result;
}
Пример #30
0
 /**
  * Constructor. Accepts one of the following:
  *
  * <ul>
  *   <li>The values TRUE or FALSE</li>
  *   <li>An integer - any non-zero value will be regarded TRUE</li>
  *   <li>The strings "true" and "false", case-insensitive</li>
  *   <li>Numeric strings - any non-zero value will be regarded TRUE</li>
  * </ul>
  *
  * @param   var value
  * @throws  lang.IllegalArgumentException if value is not acceptable
  */
 public function __construct($value)
 {
     if (TRUE === $value || FALSE === $value) {
         $this->value = $value;
     } else {
         if (is_int($value)) {
             $this->value = 0 !== $value;
         } else {
             if ('0' === $value) {
                 $this->value = FALSE;
             } else {
                 if (is_string($value) && ($l = strlen($value)) && strspn($value, '1234567890') === $l) {
                     $this->value = TRUE;
                 } else {
                     if (0 === strncasecmp($value, 'true', 4)) {
                         $this->value = TRUE;
                     } else {
                         if (0 === strncasecmp($value, 'false', 5)) {
                             $this->value = FALSE;
                         } else {
                             throw new IllegalArgumentException('Not a valid boolean: ' . xp::stringOf($value));
                         }
                     }
                 }
             }
         }
     }
 }