Example #1
0
 /**
  * Generate a path for the uploading file
  *
  * @param string $fileName The name of file for path generate
  * @param integer $splitLen Name length of each sub folder
  *
  * @return string The generated path
  */
 protected function generatePath($fileName, $splitLen = 3)
 {
     $resultName = '';
     $validFileName = preg_replace('/([^a-zA-Z0-9\\x{007f}-\\x{ffe5}\\-\\_\\@]+)+/iu', '~', pathinfo($fileName, PATHINFO_FILENAME));
     while (strpos($validFileName, '~~') !== false) {
         $validFileName = str_replace('~~', '~', $validFileName);
     }
     $fileNameLen = strlen($validFileName);
     $fileNameLastIdx = $fileNameLen - 1;
     $fileNameSplitLen = $fileNameLen - $splitLen;
     if ($fileNameLen >= $splitLen) {
         for ($charLoop = 0; $charLoop < $fileNameSplitLen;) {
             for ($elLoop = 0; $elLoop < $splitLen; $elLoop++) {
                 $resultName .= $validFileName[$charLoop];
                 if (++$charLoop > $fileNameLastIdx) {
                     break;
                 }
             }
             $resultName .= '/';
         }
         $resultName = substr($resultName, 0, strlen($resultName) - 1);
     } else {
         $resultName = date('Y') . '/' . abs((int) (crc32(date('m/w')) / 10240));
     }
     return $resultName;
 }
Example #2
0
 public function getUrlPageName()
 {
     if (static::$urlPageName !== null) {
         return static::$urlPageName;
     }
     /*
      * Cache
      */
     $key = 'urlMaker' . $this->urlComponentName . crc32(get_class($this));
     $cached = Cache::get($key, false);
     if ($cached !== false && ($cached = @unserialize($cached)) !== false) {
         $filePath = array_get($cached, 'path');
         $mtime = array_get($cached, 'mtime');
         if (!File::isFile($filePath) || $mtime != File::lastModified($filePath)) {
             $cached = false;
         }
     }
     if ($cached !== false) {
         return static::$urlPageName = array_get($cached, 'fileName');
     }
     $page = Page::useCache()->whereComponent($this->urlComponentName, 'isPrimary', '1')->first();
     if (!$page) {
         throw new ApplicationException(sprintf('Unable to a find a primary component "%s" for generating a URL in %s.', $this->urlComponentName, get_class($this)));
     }
     $baseFileName = $page->getBaseFileName();
     $filePath = $page->getFullPath();
     $cached = ['path' => $filePath, 'fileName' => $baseFileName, 'mtime' => @File::lastModified($filePath)];
     Cache::put($key, serialize($cached), Config::get('cms.parsedPageCacheTTL', 1440));
     return static::$urlPageName = $baseFileName;
 }
Example #3
0
 public function send($to, $subject, $message, $add_hostname_to_subject = false, $no_cache = false, $cc = false)
 {
     $function_cache_id = false;
     $args = func_get_args();
     foreach ($args as $k => $v) {
         $function_cache_id = $function_cache_id . serialize($k) . serialize($v);
     }
     $function_cache_id = __FUNCTION__ . crc32($function_cache_id);
     $cache_group = "notifications/email";
     $cache_content = mw()->cache_manager->get($function_cache_id, $cache_group);
     if ($no_cache == false and $cache_content != false) {
         return $cache_content;
     }
     $email_from = mw()->option_manager->get('email_from', 'email');
     if ($email_from == false or $email_from == '') {
     } else {
         if (!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
         }
     }
     if ($add_hostname_to_subject != false) {
         $subject = '[' . mw()->url_manager->hostname() . '] ' . $subject;
     }
     if (isset($to) and filter_var($to, FILTER_VALIDATE_EMAIL)) {
         $this->exec_send($to, $subject, $message);
         if (isset($cc) and $cc != false and filter_var($cc, FILTER_VALIDATE_EMAIL)) {
             $this->exec_send($cc, $subject, $message);
         }
         mw()->cache_manager->save(true, $function_cache_id, $cache_group, 30);
         return true;
     } else {
         return false;
     }
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function build($config, array $options = null)
 {
     $adapter = null;
     $cacheTtlKey = $this->getCacheTtlKey($config);
     // Check if a cache was provided
     if (isset($options['cache.adapter']) && is_string($config)) {
         $adapter = $options['cache.adapter'];
         $ttl = isset($options[$cacheTtlKey]) ? $options[$cacheTtlKey] : 3600;
         $cacheKey = 'guzzle' . crc32($config);
         // Check if the instantiated data is in the cache
         if ($cached = $adapter->fetch($cacheKey)) {
             return $cached;
         }
     }
     // Get the name of the class to instantiate for the type of data
     $factory = $this->getFactory($config);
     if (!$factory || is_string($factory)) {
         return $this->throwException($factory);
     }
     $result = $factory->build($config, $options);
     if ($adapter) {
         $adapter->save($cacheKey, $result, $ttl);
     }
     return $result;
 }
 public function execute()
 {
     if (Session::get_state() != Session::ST_LIFE) {
         self::set_client_command('refresh', array('url' => 'self'));
         self::set_result(FALSE);
         return;
     }
     if (strlen($this->message) > 65000) {
         throw new Command_exception('text length error', get_string('errors', 'text_length_error'));
     }
     $captcha_lib = Loader::get_library('captcha');
     if (!$captcha_lib->check($this->captcha)) {
         throw new Command_exception('captcha error', get_string('errors', 'captcha_error'));
     }
     require_once BASEPATH . 'global/cache.php';
     $query = array();
     $query['%text'] = Security::sanitize_text($this->message);
     $query['%name'] = Security::sanitize_text($this->name);
     $query['%email'] = Security::sanitize_text($this->email);
     $query['%quote_id'] = intval($this->quote_id);
     $query['%page'] = Cache::generate_key(TRUE);
     $query['%avatar'] = abs(crc32($this->email)) % self::AVATAR_COUNT;
     foreach ($query as $key => $value) {
         if (!in_array($key, array('%quote_id', '%avatar')) and empty($value)) {
             throw new Command_exception('empty text error', get_string('errors', 'empty_field'));
         }
     }
     db::simple_query(self::Q_SET_COMMENT, $query, TRUE);
     Cache::reset($query['%page']);
     self::set_client_command('refresh', array('url' => 'self'));
 }
 static function listArticles()
 {
     $PAGE_SIZE = 2000;
     $dbr = wfGetDB(DB_SLAVE);
     $titles = array();
     for ($page = 0;; $page++) {
         $offset = $PAGE_SIZE * $page;
         $sql = "SELECT page_id, page_title, page_touched FROM page WHERE page_namespace = " . NS_MAIN . " AND page_is_redirect = 0 ORDER BY page_touched DESC LIMIT {$offset},{$PAGE_SIZE}";
         $res = $dbr->query($sql, __FILE__);
         if (!$res->numRows()) {
             break;
         }
         foreach ($res as $row) {
             $title = Title::newFromDBKey($row->page_title);
             if (!$title) {
                 continue;
             }
             $text = $title->getText();
             $crc = crc32($text);
             $titles[] = array('uri' => $title->getFullUrl(), 'percent' => $crc % 100);
         }
     }
     usort($titles, function ($i, $j) {
         if ($i['percent'] == $j['percent']) {
             return strcasecmp($i['uri'], $j['uri']);
         } elseif ($i['percent'] < $j['percent']) {
             return -1;
         } else {
             return 1;
         }
     });
     foreach ($titles as $title) {
         print $title['uri'] . "\n";
     }
 }
Example #7
0
 /**
  * Returns cache key for some request to carrier data service
  *
  * @param string|array $key
  * @return string
  */
 public function getDataCacheKey($key)
 {
     if (is_array($key)) {
         $key = implode(',', array_keys($key));
     }
     return crc32($key);
 }
Example #8
0
 /**
  * Initializes the cookie class.
  */
 private static function initialize()
 {
     if (self::$initialized) {
         return;
     }
     self::$prefix = crc32(APP_COOKIE_SALT) . '_';
 }
 public function tName($user, $talbeName = NULL)
 {
     $tableName = parent::tName($tableName);
     $key = is_numeric($user) ? $user : abs(crc32(trim($user)));
     $key = $key % self::TABLE_NUM;
     return $tableName . '_' . $key;
 }
Example #10
0
 public function optimize($buffer)
 {
     $output = '';
     // matched buffer comes in from preg_replace_callback() as array
     $buffer = $buffer[0];
     $dom = new DOMDocument();
     $dom->loadHTML($buffer);
     $html = simplexml_import_dom($dom);
     // gather file names -
     // get URL's for each CSS file in each CSS tag of the HTML block
     $files = array();
     foreach ($html->head->link as $link) {
         // filter out things like favicon
         if ((string) $link['rel'] == 'stylesheet') {
             $file = trim((string) $link['href']);
             $files[] = trim($file, '/');
         }
     }
     // build the combined, minified output file
     // the latest mod time of the set is in output file name
     try {
         $outfile = $this->_getName($files);
         $this->_phing->log("Building {$this->_toDir}/{$outfile}");
         $this->_build($outfile, $files);
     } catch (Exception $e) {
         throw new BuildException($e->getMessage());
     }
     // output the static CSS tag
     $twoBitValue = 0x3 & crc32("{$outfile}");
     $host = str_replace('?', $twoBitValue, $this->_host);
     $path = "http://{$host}/{$outfile}";
     $output = "<link href=\"{$path}\" rel=\"stylesheet\" type=\"text/css\" />\n";
     return $output;
 }
 /**
  * Checks that configuration complies with its schema on config save.
  *
  * @param \Drupal\Core\Config\ConfigCrudEvent $event
  *   The configuration event.
  *
  * @throws \Drupal\Core\Config\Schema\SchemaIncompleteException
  *   Exception thrown when configuration does not match its schema.
  */
 public function onConfigSave(ConfigCrudEvent $event)
 {
     // Only validate configuration if in the default collection. Other
     // collections may have incomplete configuration (for example language
     // overrides only). These are not valid in themselves.
     $saved_config = $event->getConfig();
     if ($saved_config->getStorage()->getCollectionName() != StorageInterface::DEFAULT_COLLECTION) {
         return;
     }
     $name = $saved_config->getName();
     $data = $saved_config->get();
     $checksum = crc32(serialize($data));
     $exceptions = array('config_schema_test.noschema', 'config_schema_test.someschema', 'config_schema_test.schema_data_types', 'config_schema_test.no_schema_data_types', 'config_test.dynamic.system');
     if (!in_array($name, $exceptions) && !isset($this->checked[$name . ':' . $checksum])) {
         $this->checked[$name . ':' . $checksum] = TRUE;
         $errors = $this->checkConfigSchema($this->typedManager, $name, $data);
         if ($errors === FALSE) {
             throw new SchemaIncompleteException(String::format('No schema for @config_name', array('@config_name' => $name)));
         } elseif (is_array($errors)) {
             $text_errors = [];
             foreach ($errors as $key => $error) {
                 $text_errors[] = String::format('@key @error', array('@key' => $key, '@error' => $error));
             }
             throw new SchemaIncompleteException(String::format('Schema errors for @config_name with the following errors: @errors', array('@config_name' => $name, '@errors' => implode(', ', $text_errors))));
         }
     }
 }
Example #12
0
 public static function writeUrl(&$db, $loc, $lastMod = null, $changeFreq = null, $priority = null, $tableName = 'sitemap')
 {
     try {
         $loc = trim($loc);
         $checksum = crc32($loc);
         /* get the host name from url */
         preg_match('@^(?:https?:\\/\\/)?((?:www\\.)?[^\\/]+)@i', $loc, $matches);
         $host = $matches[1];
         $row = $db->select_1('select * from sitemap where loc = %s', $loc);
         /* new location */
         if (is_null($row)) {
             $db->insert('sitemap', 'checksum = \'%l\'::bigint', $checksum, 'host = %s', $host, 'loc = %s', $loc, 'last_mod = %T', $lastMod, 'change_freq = %S', $changeFreq, 'priority = %l', is_null($priority) ? 'NULL' : $priority);
             /* update as details have changed */
         } elseif ($row->t_last_mod != $lastMod || $row->s_change_freq != $changeFreq || $row->s_priority != $priority) {
             $db->update_1('sitemap', 'loc = %s', $loc, 'last_mod = %T', $lastMod, 'change_freq = %S', $changeFreq, 'priority = %l', is_null($priority) ? 'NULL' : $priority);
         }
         /* nulling used variables (big sitemaps need every scrap of memory!) */
         $row = null;
         $host = null;
         $checksum = null;
         $matches = null;
     } catch (Exception $e) {
         Atsumi::error__listen($e);
     }
 }
Example #13
0
/**
 * 通过本机共享内存件来生成一个auto_increment序列
 *
 * 序列类似MySQL的auto_increment
 *
 * @access private
 * @param  void
 * @return mixed
 */
function getNextValueByShareMemory()
{
    $addr = '127.0.0.1';
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $addr = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (!empty($_SERVER['SERVER_ADDR'])) {
        $addr = $_SERVER['SERVER_ADDR'];
    }
    $skey = 'global_serial_generator_seed_' . $addr;
    $ikey = crc32($skey);
    $sem = $shm = null;
    $retry_times = 1;
    do {
        $sem = sem_get($ikey, 1, 0777);
        $shm = shm_attach($ikey, 128, 0777);
        if (is_resource($sem) && is_resource($shm)) {
            break;
        }
        $cmd = "ipcrm -M 0x00000000; ipcrm -S 0x00000000; ipcrm -M {$ikey} ; ipcrm -S {$ikey}";
        $last_line = exec($cmd, $output, $retval);
    } while ($retry_times-- > 0);
    if (!sem_acquire($sem)) {
        return false;
    }
    $next_value = false;
    if (shm_has_var($shm, $ikey)) {
        shm_put_var($shm, $ikey, $next_value = shm_get_var($shm, $ikey) + 1);
    } else {
        shm_put_var($shm, $ikey, $next_value = 1);
    }
    $shm && shm_detach($shm);
    $sem && sem_release($sem);
    return $next_value;
}
Example #14
0
 function Explain($sql, $partial = false)
 {
     $save = $this->conn->LogSQL(false);
     if ($partial) {
         $sqlq = $this->conn->qstr($sql . '%');
         $arr = $this->conn->GetArray("select distinct distinct sql1 from adodb_logsql where sql1 like {$sqlq}");
         if ($arr) {
             foreach ($arr as $row) {
                 $sql = reset($row);
                 if (crc32($sql) == $partial) {
                     break;
                 }
             }
         }
     }
     $sql = str_replace('?', "''", $sql);
     $s = '<p><b>Explain</b>: ' . htmlspecialchars($sql) . '</p>';
     $rs = $this->conn->Execute('EXPLAIN ' . $sql);
     $this->conn->LogSQL($save);
     $s .= '<pre>';
     if ($rs) {
         while (!$rs->EOF) {
             $s .= reset($rs->fields) . "\n";
             $rs->MoveNext();
         }
     }
     $s .= '</pre>';
     $s .= $this->Tracer($sql, $partial);
     return $s;
 }
function _gzipOutput(& $output)
{
  global $HTTP_SERVER_VARS;

  if(defined('OUTPUT_GZIP_ENABLED') &&  constant('OUTPUT_GZIP_ENABLED') == false)
    return;

  if(isset($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING']) &&  strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip'))
  {
    $size = strlen($output);
    if(extension_loaded('zlib') &&   $size >= 20000)
    {
      $crc = crc32($output);

      $output = gzcompress($output, 9);

      // We can't just output it here, since the CRC is messed up. Strip off the old CRC
      $output = substr($output, 0, strlen($output) - 4);

      _gzipAppend4_chars($output, $crc);
      _gzipAppend4_chars($output, $size);

      $output = "\x1f\x8b\x08\x00\x00\x00\x00\x00" . $output;

      header('Content-Encoding: gzip');
    }
  }
}
Example #16
0
function gzipoutput($text)
{
    global $HTTP_ACCEPT_ENCODING;
    $returntext = $text;
    if (function_exists("crc32") and function_exists("gzcompress")) {
        if (strpos(" " . $HTTP_ACCEPT_ENCODING, "x-gzip")) {
            $encoding = "x-gzip";
        }
        if (strpos(" " . $HTTP_ACCEPT_ENCODING, "gzip")) {
            $encoding = "gzip";
        }
        if ($encoding) {
            header("Content-Encoding: {$encoding}");
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            // Date in the past
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            // always modified
            header("Cache-Control: no-store, no-cache, must-revalidate");
            // HTTP/1.1
            header("Cache-Control: post-check=0, pre-check=0", false);
            header("Pragma: no-cache");
            // HTTP/1.0
            $size = strlen($text);
            $crc = crc32($text);
            $returntext = "‹";
            $returntext .= substr(gzcompress($text, 1), 0, -4);
            $returntext .= pack("V", $crc);
            $returntext .= pack("V", $size);
        }
    }
    return $returntext;
}
Example #17
0
 function Explain($sql, $partial = false)
 {
     if (strtoupper(substr(trim($sql), 0, 6)) !== 'SELECT') {
         return '<p>Unable to EXPLAIN non-select statement</p>';
     }
     $save = $this->conn->LogSQL(false);
     if ($partial) {
         $sqlq = $this->conn->qstr($sql . '%');
         $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like {$sqlq}");
         if ($arr) {
             foreach ($arr as $row) {
                 $sql = reset($row);
                 if (crc32($sql) == $partial) {
                     break;
                 }
             }
         }
     }
     $sql = str_replace('?', "''", $sql);
     if ($partial) {
         $sqlq = $this->conn->qstr($sql . '%');
         $sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like {$sqlq}");
     }
     $s = '<p><b>Explain</b>: ' . htmlspecialchars($sql) . '</p>';
     $rs = $this->conn->Execute('EXPLAIN ' . $sql);
     $s .= rs2html($rs, false, false, false, false);
     $this->conn->LogSQL($save);
     $s .= $this->Tracer($sql);
     return $s;
 }
Example #18
0
 function streamData($data, $name, $time = 0, $level = -1)
 {
     $time = $this->dosTime($time);
     $crc = crc32($data);
     $dlen = strlen($data);
     $level < 0 && ($level = (int) $this->level);
     $level < 0 && ($level = self::LEVEL);
     $data = gzdeflate($data, $level);
     $zlen = strlen($data);
     $name = strtr($name, '\\', '/');
     $n = @iconv('UTF-8', 'CP850', $name);
     // If CP850 can not represent the filename, use unicode
     if ($name !== @iconv('CP850', 'UTF-8', $n)) {
         $n = $name;
         $h = "";
     } else {
         $h = "";
     }
     $nlen = strlen($n);
     $h = "" . $h . "" . pack('V', $time) . pack('V', $crc) . pack('V', $zlen) . pack('V', $dlen) . pack('v', $nlen) . pack('v', 0);
     // extra field length
     echo "PK", $h, $n, $data;
     $dlen = $this->dataLen;
     $this->dataLen += 4 + strlen($h) + $nlen + $zlen;
     $this->cdr[] = "PK" . "" . $h . pack('v', 0) . pack('v', 0) . pack('v', 0) . pack('V', 32) . pack('V', $dlen) . $n;
 }
Example #19
0
 public function __construct()
 {
     if ($this->config === null) {
         $this->config = config::getConfig(__CLASS__);
     }
     $this->config['cookie.user'] .= ':' . crc32(environment::getCurrentEnvironment());
 }
Example #20
0
 /**
  * CDN图片域名
  *
  * @param string $img  图片地址
  * @param string $path 附加路径
  * @return string 完整URL图片地址
  */
 function cdn_img_url($img, $path = '/')
 {
     if (empty($img) || strpos($img, '://') !== false) {
         return $img;
     }
     if ($img[0] == '/') {
         $path = '';
     }
     /**
      * 当使用本机时,就不用CDN处理了
      */
     if (isset($_GET['local'])) {
         return "{$path}{$img}";
     }
     if (USE_ISLOCAL_JS2CSS || USE_ISLOCAL_IMG) {
         $file_ext = strtolower(strrchr($img, '.'));
         if (USE_ISLOCAL_JS2CSS && ($file_ext == '.js' || $file_ext == '.css')) {
             return "{$path}{$img}";
         }
         if (USE_ISLOCAL_IMG && ($file_ext == '.jpg' || $file_ext == '.jpeg' || $file_ext == '.gif' || $file_ext == '.swf' || $file_ext == '.png')) {
             return "{$path}{$img}";
         }
     }
     /**
      * 分服务器加载
      */
     static $img_hosts = null;
     static $img_count = null;
     if (is_null($img_hosts)) {
         $img_hosts = json_decode(IMG_URLS, true);
         $img_count = count($img_hosts);
     }
     $key = abs(crc32($img)) % $img_count;
     return "{$img_hosts[$key]}{$path}{$img}";
 }
 function createMergeTable()
 {
     $split_ps = $this->store->getSetting('split_predicates', array());
     if (!$split_ps) {
         return 1;
     }
     $this->mrg_table_id = 'MRG_' . $this->store->getTablePrefix() . crc32(uniqid(rand()));
     $con = $this->store->getDBCon();
     $this->queryDB("FLUSH TABLES", $con);
     $indexes = $this->v('store_indexes', array('sp (s,p)', 'os (o,s)', 'po (p,o)'), $this->a);
     $index_code = $indexes ? 'KEY ' . join(', KEY ', $indexes) . ', ' : '';
     $prefix = $this->store->getTablePrefix();
     $sql = "\n      CREATE TEMPORARY TABLE IF NOT EXISTS " . $prefix . "triple_all (\n        t mediumint UNSIGNED NOT NULL,\n        s mediumint UNSIGNED NOT NULL,\n        p mediumint UNSIGNED NOT NULL,\n        o mediumint UNSIGNED NOT NULL,\n        o_lang_dt mediumint UNSIGNED NOT NULL,\n        o_comp char(35) NOT NULL,                   /* normalized value for ORDER BY operations */\n        s_type tinyint(1) NOT NULL default 0,       /* uri/bnode => 0/1 */\n        o_type tinyint(1) NOT NULL default 0,       /* uri/bnode/literal => 0/1/2 */\n        misc tinyint(1) NOT NULL default 0,         /* temporary flags */\n        UNIQUE KEY (t), " . $index_code . " KEY (misc)\n      ) \n    ";
     $v = $this->store->getDBVersion();
     $sql .= $v < '04-01-00' && $v >= '04-00-18' ? 'ENGINE' : ($v >= '04-01-02' ? 'ENGINE' : 'TYPE');
     $sql .= "=MERGE UNION=(" . $prefix . "triple";
     foreach ($split_ps as $pos => $p) {
         $sql .= ',' . $prefix . 'triple_' . abs(crc32($p));
     }
     $sql .= ")";
     //$sql .= ($v >= '04-00-00') ? " CHARACTER SET utf8" : "";
     //$sql .= ($v >= '04-01-00') ? " COLLATE utf8_unicode_ci" : "";
     //echo $sql;
     return $this->queryDB($sql, $con);
 }
/**
 * Generates a Photon URL.
 *
 * @see http://developer.wordpress.com/docs/photon/
 *
 * @param string $image_url URL to the publicly accessible image you want to manipulate
 * @param array|string $args An array of arguments, i.e. array( 'w' => '300', 'resize' => array( 123, 456 ) ), or in string form (w=123&h=456)
 * @return string The raw final URL. You should run this through esc_url() before displaying it.
 */
function jetpack_photon_url($image_url, $args = array(), $scheme = null)
{
    $image_url = trim($image_url);
    $image_url = apply_filters('jetpack_photon_pre_image_url', $image_url, $args, $scheme);
    $args = apply_filters('jetpack_photon_pre_args', $args, $image_url, $scheme);
    if (empty($image_url)) {
        return $image_url;
    }
    $image_url_parts = @parse_url($image_url);
    // Unable to parse
    if (!is_array($image_url_parts) || empty($image_url_parts['host']) || empty($image_url_parts['path'])) {
        return $image_url;
    }
    if (is_array($args)) {
        // Convert values that are arrays into strings
        foreach ($args as $arg => $value) {
            if (is_array($value)) {
                $args[$arg] = implode(',', $value);
            }
        }
        // Encode values
        // See http://core.trac.wordpress.org/ticket/17923
        $args = rawurlencode_deep($args);
    }
    // You can't run a Photon URL through Photon again because query strings are stripped.
    // So if the image is already a Photon URL, append the new arguments to the existing URL.
    if (in_array($image_url_parts['host'], array('i0.wp.com', 'i1.wp.com', 'i2.wp.com'))) {
        $photon_url = add_query_arg($args, $image_url);
        return jetpack_photon_url_scheme($photon_url, $scheme);
    }
    // This setting is Photon Server dependent
    if (!apply_filters('jetpack_photon_any_extension_for_domain', false, $image_url_parts['host'])) {
        // Photon doesn't support query strings so we ignore them and look only at the path.
        // However some source images are served via PHP so check the no-query-string extension.
        // For future proofing, this is a blacklist of common issues rather than a whitelist.
        $extension = pathinfo($image_url_parts['path'], PATHINFO_EXTENSION);
        if (empty($extension) || in_array($extension, array('php'))) {
            return $image_url;
        }
    }
    $image_host_path = $image_url_parts['host'] . $image_url_parts['path'];
    // Figure out which CDN subdomain to use
    srand(crc32($image_host_path));
    $subdomain = rand(0, 2);
    srand();
    $photon_url = "http://i{$subdomain}.wp.com/{$image_host_path}";
    // This setting is Photon Server dependent
    if (isset($image_url_parts['query']) && apply_filters('jetpack_photon_add_query_string_to_domain', false, $image_url_parts['host'])) {
        $photon_url .= '?q=' . rawurlencode($image_url_parts['query']);
    }
    if ($args) {
        if (is_array($args)) {
            $photon_url = add_query_arg($args, $photon_url);
        } else {
            // You can pass a query string for complicated requests but where you still want CDN subdomain help, etc.
            $photon_url .= '?' . $args;
        }
    }
    return jetpack_photon_url_scheme($photon_url, $scheme);
}
 function Explain($sql, $partial = false)
 {
     $save = $this->conn->LogSQL(false);
     if ($partial) {
         $sqlq = $this->conn->qstr($sql . '%');
         $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like {$sqlq}");
         if ($arr) {
             foreach ($arr as $row) {
                 $sql = reset($row);
                 if (crc32($sql) == $partial) {
                     break;
                 }
             }
         }
     }
     $qno = rand();
     $ok = $this->conn->Execute("EXPLAIN PLAN SET QUERYNO={$qno} FOR {$sql}");
     ob_start();
     if (!$ok) {
         echo "<p>Have EXPLAIN tables been created?</p>";
     } else {
         $rs = $this->conn->Execute("select * from explain_statement where queryno={$qno}");
         if ($rs) {
             rs2html($rs);
         }
     }
     $s = ob_get_contents();
     ob_end_clean();
     $this->conn->LogSQL($save);
     $s .= $this->Tracer($sql);
     return $s;
 }
Example #24
0
function quicky_function_insert_js($params, $quicky)
{
    $_files = isset($params['files']) ? $params['files'] : array();
    if (sizeof($_files) == 0) {
        return $quicky->warning('missing files.');
    }
    $_baseurl = isset($params['baseurl']) ? $params['baseurl'] : '';
    $_out = isset($params['out']) ? $params['out'] : './';
    $_id = isset($params['id']) ? $params['id'] : dechex(crc32(implode('//', $_files)));
    $fn = $_id . '.js';
    $f = $_out . $fn;
    $c = !file_exists($f) || isset($params['force_compile']) && $params['force_compile'];
    if (!$c) {
        $m = filemtime($f);
        foreach ($_files as $v) {
            if (!file_exists($v) || filemtime($v) > $m) {
                $c = TRUE;
                break;
            }
        }
    }
    if ($c) {
        $data = '';
        foreach ($_files as $v) {
            $s = file_get_contents($v);
            $s = trim($s);
            //$s = preg_replace('~^[\X20\t]*/\*.*?\*/[\X20\t]*$~sm','',$s);
            $data .= '/* Compiled from ' . $v . " */\n";
            $data .= $s . "\n";
        }
        file_put_contents($tf = $f . '.tmp', $data, LOCK_EX);
        rename($tf, $f);
    }
    return '<script type="text/javascript" src="' . $_baseurl . $fn . '"></script>';
}
Example #25
0
 /**
  * Factory method for creating new credentials.  This factory method will
  * create the appropriate credentials object with appropriate decorators
  * based on the passed configuration options.
  *
  * @param array $config Options to use when instantiating the credentials
  *
  * @return CredentialsInterface
  * @throws InvalidArgumentException If the caching options are invalid
  * @throws RuntimeException         If using the default cache and APC is disabled
  */
 public static function factory($config = array())
 {
     // Add default key values
     foreach (self::getConfigDefaults() as $key => $value) {
         if (!isset($config[$key])) {
             $config[$key] = $value;
         }
     }
     // Start tracking the cache key
     $cacheKey = $config[Options::CREDENTIALS_CACHE_KEY];
     // Create the credentials object
     if (!$config[Options::KEY] || !$config[Options::SECRET]) {
         $credentials = self::createFromEnvironment($config);
         // If no cache key was set, use the crc32 hostname of the server
         $cacheKey = $cacheKey ?: 'credentials_' . crc32(gethostname());
     } else {
         // Instantiate using short or long term credentials
         $credentials = new static($config[Options::KEY], $config[Options::SECRET], $config[Options::TOKEN], $config[Options::TOKEN_TTD]);
         // If no cache key was set, use the access key ID
         $cacheKey = $cacheKey ?: 'credentials_' . $config[Options::KEY];
     }
     // Check if the credentials are refreshable, and if so, configure caching
     $cache = $config[Options::CREDENTIALS_CACHE];
     if ($cacheKey && $cache) {
         $credentials = self::createCache($credentials, $cache, $cacheKey);
     }
     return $credentials;
 }
Example #26
0
 /**
  * Generate a random ID.
  */
 public function generate()
 {
     $pid = function_exists('zend_thread_id') ? zend_thread_id() : getmypid();
     /* Base64 can have /, +, and = characters. Restrict to URL-safe
      * characters. */
     return str_replace(array('/', '+', '='), array('-', '_', ''), base64_encode(pack('II', mt_rand(), crc32(php_uname('n'))) . pack('H*', uniqid() . sprintf('%04s', dechex($pid)))));
 }
Example #27
0
 /**
  * Initializes the session system.
  */
 private static function initialize()
 {
     // Make sure it's not initialized already
     if (self::$initialized) {
         return;
     }
     // See if we were given a session id explicitly
     // If so we also need a matching token to allow it
     $setSid = false;
     if (Input::exists('_sid')) {
         session_id(Input::get('_sid'));
         $setSid = true;
     }
     // Start the default PHP session
     self::$prefix = crc32(APP_SALT) . '_';
     session_name('session');
     session_start();
     // Set the initialized flag
     self::$initialized = true;
     // Make sure the token is good before we allow
     // explicit session id setting
     if ($setSid) {
         Auth::checkToken();
     }
 }
Example #28
0
 /**
  * Generate a unique key for a list of parameters, with same parameters
  * the key must not change (no random stuff) and the order does not matter
  *
  * @param array $parameters
  *
  * @return integer
  */
 public function getUniqueKey($parameters = array())
 {
     // First ordering parameters
     ksort($parameters);
     // Return a hash of the serialzed parameters
     return crc32(serialize($parameters));
 }
Example #29
-1
 /**
  * Generate a 36-character RFC 4122 UUID, without the urn:uuid: prefix.
  *
  * @see http://www.ietf.org/rfc/rfc4122.txt
  * @see http://labs.omniti.com/alexandria/trunk/OmniTI/Util/UUID.php
  */
 public function generate()
 {
     $this->_uuid = null;
     if (extension_loaded('uuid')) {
         if (function_exists('uuid_export')) {
             // UUID extension from http://www.ossp.org/pkg/lib/uuid/
             if (uuid_create($ctx) == UUID_RC_OK && uuid_make($ctx, UUID_MAKE_V4) == UUID_RC_OK && uuid_export($ctx, UUID_FMT_STR, $str) == UUID_RC_OK) {
                 $this->_uuid = $str;
                 uuid_destroy($ctx);
             }
         } else {
             // UUID extension from http://pecl.php.net/package/uuid
             $this->_uuid = uuid_create();
         }
     }
     if (!$this->_uuid) {
         list($time_mid, $time_low) = explode(' ', microtime());
         $time_low = (int) $time_low;
         $time_mid = (int) substr($time_mid, 2) & 0xffff;
         $time_high = mt_rand(0, 0xfff) | 0x4000;
         $clock = mt_rand(0, 0x3fff) | 0x8000;
         $node_low = function_exists('zend_thread_id') ? zend_thread_id() : getmypid();
         $node_high = isset($_SERVER['SERVER_ADDR']) ? ip2long($_SERVER['SERVER_ADDR']) : crc32(php_uname());
         $node = bin2hex(pack('nN', $node_low, $node_high));
         $this->_uuid = sprintf('%08x-%04x-%04x-%04x-%s', $time_low, $time_mid, $time_high, $clock, $node);
     }
 }
Example #30
-1
 /**
  * コンストラクタ
  */
 public function __construct($aThread, $matome = false)
 {
     parent::__construct($aThread, $matome);
     global $_conf;
     $this->_url_handlers = array('plugin_linkThread', 'plugin_link2chSubject');
     // +Wiki
     if (isset($GLOBALS['linkPluginCtl'])) {
         $this->_url_handlers[] = 'plugin_linkPlugin';
     }
     if (isset($GLOBALS['replaceImageUrlCtl'])) {
         $this->_url_handlers[] = 'plugin_replaceImageUrl';
     }
     if (P2_IMAGECACHE_AVAILABLE == 2) {
         $this->_url_handlers[] = 'plugin_imageCache2';
     } elseif ($_conf['preview_thumbnail']) {
         $this->_url_handlers[] = 'plugin_viewImage';
     }
     if ($_conf['link_youtube']) {
         $this->_url_handlers[] = 'plugin_linkYouTube';
     }
     if ($_conf['link_niconico']) {
         $this->_url_handlers[] = 'plugin_linkNicoNico';
     }
     $this->_url_handlers[] = 'plugin_linkURL';
     // imepitaのURLを加工してImageCache2させるプラグインを登録
     if (P2_IMAGECACHE_AVAILABLE == 2) {
         $this->addURLHandler(array($this, 'plugin_imepitaToImageCache2'));
     }
     // サムネイル表示制限数を設定
     if (!isset($GLOBALS['pre_thumb_unlimited']) || !isset($GLOBALS['pre_thumb_limit'])) {
         if (isset($_conf['pre_thumb_limit']) && $_conf['pre_thumb_limit'] > 0) {
             $GLOBALS['pre_thumb_limit'] = $_conf['pre_thumb_limit'];
             $GLOBALS['pre_thumb_unlimited'] = false;
         } else {
             $GLOBALS['pre_thumb_limit'] = null;
             // ヌル値だとisset()はfalseを返す
             $GLOBALS['pre_thumb_unlimited'] = true;
         }
     }
     $GLOBALS['pre_thumb_ignore_limit'] = false;
     // アクティブモナー初期化
     if (P2_ACTIVEMONA_AVAILABLE) {
         ExpackLoader::initActiveMona($this);
     }
     // ImageCache2初期化
     if (P2_IMAGECACHE_AVAILABLE == 2) {
         ExpackLoader::initImageCache($this);
     }
     // 非同期レスポップアップ・SPM初期化
     $js_id = sprintf('%u', crc32($this->thread->keydat));
     if ($this->_matome) {
         $this->asyncObjName = "t{$this->_matome}asp{$js_id}";
         $this->spmObjName = "t{$this->_matome}spm{$js_id}";
     } else {
         $this->asyncObjName = "asp{$js_id}";
         $this->spmObjName = "spm{$js_id}";
     }
     // 名無し初期化
     $this->setBbsNonameName();
 }