コード例 #1
0
ファイル: StringHelperTest.php プロジェクト: aivavic/yii2
 public function testSubstr()
 {
     $this->assertEquals('th', StringHelper::byteSubstr('this', 0, 2));
     $this->assertEquals('э', StringHelper::byteSubstr('это', 0, 2));
     $this->assertEquals('abcdef', StringHelper::byteSubstr('abcdef', 0));
     $this->assertEquals('abcdef', StringHelper::byteSubstr('abcdef', 0, null));
     $this->assertEquals('de', StringHelper::byteSubstr('abcdef', 3, 2));
     $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3));
     $this->assertEquals('def', StringHelper::byteSubstr('abcdef', 3, null));
     $this->assertEquals('cd', StringHelper::byteSubstr('abcdef', -4, 2));
     $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4));
     $this->assertEquals('cdef', StringHelper::byteSubstr('abcdef', -4, null));
     $this->assertEquals('', StringHelper::byteSubstr('abcdef', 4, 0));
     $this->assertEquals('', StringHelper::byteSubstr('abcdef', -4, 0));
     $this->assertEquals('это', StringHelper::byteSubstr('это', 0));
     $this->assertEquals('это', StringHelper::byteSubstr('это', 0, null));
     $this->assertEquals('т', StringHelper::byteSubstr('это', 2, 2));
     $this->assertEquals('то', StringHelper::byteSubstr('это', 2));
     $this->assertEquals('то', StringHelper::byteSubstr('это', 2, null));
     $this->assertEquals('т', StringHelper::byteSubstr('это', -4, 2));
     $this->assertEquals('то', StringHelper::byteSubstr('это', -4));
     $this->assertEquals('то', StringHelper::byteSubstr('это', -4, null));
     $this->assertEquals('', StringHelper::byteSubstr('это', 4, 0));
     $this->assertEquals('', StringHelper::byteSubstr('это', -4, 0));
 }
コード例 #2
0
ファイル: Csrf.php プロジェクト: semnt/tp01
 public static function compTokens($token, $trueToken)
 {
     $token = base64_decode(str_replace('.', '+', $token));
     $n = StringHelper::byteLength($token);
     if ($n <= static::CSRF_MASK_LENGTH) {
         return false;
     }
     $mask = StringHelper::byteSubstr($token, 0, static::CSRF_MASK_LENGTH);
     $token = StringHelper::byteSubstr($token, static::CSRF_MASK_LENGTH, $n - static::CSRF_MASK_LENGTH);
     $token = static::xorTokens($mask, $token);
     return $token === $trueToken;
 }
コード例 #3
0
 /**
  * @return string|false
  */
 public function moveToUpload()
 {
     $filename = sha1(microtime());
     $ext = pathinfo($this->getName(), PATHINFO_EXTENSION);
     $upload_path = File\Module::module()->upload_path;
     $p1 = StringHelper::byteSubstr($filename, 0, 2);
     $p2 = StringHelper::byteSubstr($filename, 2, 2);
     $path = $upload_path . DIRECTORY_SEPARATOR . $p1 . DIRECTORY_SEPARATOR . $p2;
     if (!file_exists($path)) {
         FileHelper::createDirectory($path);
     }
     $file_path = $path . DIRECTORY_SEPARATOR . $filename . '.' . $ext;
     $result = copy($this->getTemp(), $file_path);
     $this->clear();
     chmod($file_path, 0664);
     return $result === true ? $file_path : false;
 }
コード例 #4
0
 /**
  *
  * @param string $url
  * @return self
  */
 protected static function setDomains($url)
 {
     self::$baseFolder = '';
     if (empty(self::$homeUrl)) {
         self::$homeUrl = rtrim(StringHelper::dirname($_SERVER['PHP_SELF']), '/');
     }
     if (empty(self::$baseFolder)) {
         if ($str = mb_stristr(self::$homeUrl, 'admin', TRUE)) {
             self::$baseFolder = $str . "admin";
         }
         if ($str == false && !empty(self::$homeUrl)) {
             self::$baseFolder = rtrim(self::$homeUrl, '/');
         }
         self::$baseFolder = rtrim(self::$baseFolder, '/');
     }
     $url = StringHelper::byteSubstr($url, StringHelper::byteLength(self::$baseFolder), StringHelper::byteLength($url));
     self::$domains = explode('/', ltrim($url, '/'));
     return self::$domains;
 }
コード例 #5
0
ファイル: Security.php プロジェクト: Jaaviieer/PrograWeb
 /**
  * Generates specified number of random bytes.
  * Note that output may not be ASCII.
  * @see generateRandomString() if you need a string.
  *
  * @param integer $length the number of bytes to generate
  * @return string the generated random bytes
  * @throws InvalidConfigException if OpenSSL extension is required (e.g. on Windows) but not installed.
  * @throws Exception on failure.
  */
 public function generateRandomKey($length = 32)
 {
     /*
      * Strategy
      *
      * The most common platform is Linux, on which /dev/urandom is the best choice. Many other OSs
      * implement a device called /dev/urandom for Linux compat and it is good too. So if there is
      * a /dev/urandom then it is our first choice regardless of OS.
      *
      * Nearly all other modern Unix-like systems (the BSDs, Unixes and OS X) have a /dev/random
      * that is a good choice. If we didn't get bytes from /dev/urandom then we try this next but
      * only if the system is not Linux. Do not try to read /dev/random on Linux.
      *
      * Finally, OpenSSL can supply CSPR bytes. It is our last resort. On Windows this reads from
      * CryptGenRandom, which is the right thing to do. On other systems that don't have a Unix-like
      * /dev/urandom, it will deliver bytes from its own CSPRNG that is seeded from kernel sources
      * of randomness. Even though it is fast, we don't generally prefer OpenSSL over /dev/urandom
      * because an RNG in user space memory is undesirable.
      *
      * For background, see http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
      */
     $bytes = '';
     // If we are on Linux or any OS that mimics the Linux /dev/urandom device, e.g. FreeBSD or OS X,
     // then read from /dev/urandom.
     if (@file_exists('/dev/urandom')) {
         $handle = fopen('/dev/urandom', 'r');
         if ($handle !== false) {
             $bytes .= fread($handle, $length);
             fclose($handle);
         }
     }
     if (StringHelper::byteLength($bytes) >= $length) {
         return StringHelper::byteSubstr($bytes, 0, $length);
     }
     // If we are not on Linux and there is a /dev/random device then we have a BSD or Unix device
     // that won't block. It's not safe to read from /dev/random on Linux.
     if (PHP_OS !== 'Linux' && @file_exists('/dev/random')) {
         $handle = fopen('/dev/random', 'r');
         if ($handle !== false) {
             $bytes .= fread($handle, $length);
             fclose($handle);
         }
     }
     if (StringHelper::byteLength($bytes) >= $length) {
         return StringHelper::byteSubstr($bytes, 0, $length);
     }
     if (!extension_loaded('openssl')) {
         throw new InvalidConfigException('The OpenSSL PHP extension is not installed.');
     }
     $bytes .= openssl_random_pseudo_bytes($length, $cryptoStrong);
     if (StringHelper::byteLength($bytes) < $length || !$cryptoStrong) {
         throw new Exception('Unable to generate random bytes.');
     }
     return StringHelper::byteSubstr($bytes, 0, $length);
 }
コード例 #6
0
 /**
  * Sends the specified content as a file to the browser.
  *
  * Note that this method only prepares the response for file sending. The file is not sent
  * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  *
  * @param string $content the content to be sent. The existing [[content]] will be discarded.
  * @param string $attachmentName the file name shown to the user.
  * @param string $mimeType the MIME type of the content.
  * @return static the response object itself
  * @throws HttpException if the requested range is not satisfiable
  */
 public function sendContentAsFile($content, $attachmentName, $mimeType = 'application/octet-stream')
 {
     $headers = $this->getHeaders();
     $contentLength = StringHelper::byteLength($content);
     $range = $this->getHttpRange($contentLength);
     if ($range === false) {
         $headers->set('Content-Range', "bytes */{$contentLength}");
         throw new HttpException(416, 'Requested range not satisfiable');
     }
     $headers->setDefault('Pragma', 'public')->setDefault('Accept-Ranges', 'bytes')->setDefault('Expires', '0')->setDefault('Content-Type', $mimeType)->setDefault('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')->setDefault('Content-Transfer-Encoding', 'binary')->setDefault('Content-Length', StringHelper::byteLength($content))->setDefault('Content-Disposition', "attachment; filename=\"{$attachmentName}\"");
     list($begin, $end) = $range;
     if ($begin != 0 || $end != $contentLength - 1) {
         $this->setStatusCode(206);
         $headers->set('Content-Range', "bytes {$begin}-{$end}/{$contentLength}");
         $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
     } else {
         $this->setStatusCode(200);
         $this->content = $content;
     }
     $this->format = self::FORMAT_RAW;
     return $this;
 }
コード例 #7
0
ファイル: BaseFileHelper.php プロジェクト: aoopvn/EduSec4.0.0
 /**
  * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
  * @param string $pattern
  * @param boolean $caseSensitive
  * @throws \yii\base\InvalidParamException
  * @return array with keys: (string) pattern, (int) flags, (int|boolean)firstWildcard
  */
 private static function parseExcludePattern($pattern, $caseSensitive)
 {
     if (!is_string($pattern)) {
         throw new InvalidParamException('Exclude/include pattern must be a string.');
     }
     $result = ['pattern' => $pattern, 'flags' => 0, 'firstWildcard' => false];
     if (!$caseSensitive) {
         $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
     }
     if (!isset($pattern[0])) {
         return $result;
     }
     if ($pattern[0] == '!') {
         $result['flags'] |= self::PATTERN_NEGATIVE;
         $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
     }
     if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) == '/') {
         $pattern = StringHelper::byteSubstr($pattern, 0, -1);
         $result['flags'] |= self::PATTERN_MUSTBEDIR;
     }
     if (strpos($pattern, '/') === false) {
         $result['flags'] |= self::PATTERN_NODIR;
     }
     $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
     if ($pattern[0] == '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
         $result['flags'] |= self::PATTERN_ENDSWITH;
     }
     $result['pattern'] = $pattern;
     return $result;
 }
コード例 #8
0
ファイル: Response.php プロジェクト: nanodesu88/yii2
 /**
  * Sends the specified content as a file to the browser.
  *
  * Note that this method only prepares the response for file sending. The file is not sent
  * until [[send()]] is called explicitly or implicitly. The latter is done after you return from a controller action.
  *
  * @param string $content the content to be sent. The existing [[content]] will be discarded.
  * @param string $attachmentName the file name shown to the user.
  * @param array $options additional options for sending the file. The following options are supported:
  *
  *  - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'.
  *  - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false,
  *    meaning a download dialog will pop up.
  *
  * @return $this the response object itself
  * @throws HttpException if the requested range is not satisfiable
  * @see sendFile() for an example implementation.
  */
 public function sendContentAsFile($content, $attachmentName, $options = [])
 {
     $headers = $this->getHeaders();
     $contentLength = StringHelper::byteLength($content);
     $range = $this->getHttpRange($contentLength);
     if ($range === false) {
         $headers->set('Content-Range', "bytes */{$contentLength}");
         throw new HttpException(416, 'Requested range not satisfiable');
     }
     list($begin, $end) = $range;
     if ($begin != 0 || $end != $contentLength - 1) {
         $this->setStatusCode(206);
         $headers->set('Content-Range', "bytes {$begin}-{$end}/{$contentLength}");
         $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
     } else {
         $this->setStatusCode(200);
         $this->content = $content;
     }
     $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
     $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
     $this->format = self::FORMAT_RAW;
     return $this;
 }
コード例 #9
0
ファイル: Upload.php プロジェクト: mootensai/yii2-mongodb
 /**
  * Adds string content to the upload.
  * This method can invoked several times before [[complete()]] is called.
  * @param string $content binary content.
  * @return $this self reference.
  */
 public function addContent($content)
 {
     $freeBufferLength = $this->chunkSize - StringHelper::byteLength($this->buffer);
     $contentLength = StringHelper::byteLength($content);
     if ($contentLength > $freeBufferLength) {
         $this->buffer .= StringHelper::byteSubstr($content, 0, $freeBufferLength);
         $this->flushBuffer(true);
         return $this->addContent(StringHelper::byteSubstr($content, $freeBufferLength));
     } else {
         $this->buffer .= $content;
         $this->flushBuffer();
     }
     return $this;
 }
コード例 #10
0
 /**
  * Get full path to image by Uri
  *
  * @param string $url Uri
  * @return string
  */
 public function getImageByUri($url)
 {
     $return = false;
     $url = (string) parse_url($url, PHP_URL_PATH);
     $file = StringHelper::basename($url, '.' . $this->config['extension']);
     if (32 > (int) StringHelper::byteLength($file)) {
         return $return;
     }
     $fileName = StringHelper::byteSubstr($file, 0, 32);
     $suffix = StringHelper::byteSubstr($file, 32);
     if ($result = $this->arcresultOne($fileName)) {
         $dirName = dirname($result->path);
         $targetPath = FileHelper::normalizePath(\Yii::getAlias($this->config['directories']['target'] . $dirName));
         $sourceFile = $targetPath . DIRECTORY_SEPARATOR . $fileName . '.' . $this->config['extension'];
         if (is_file($sourceFile)) {
             $return = $sourceFile;
         }
         if (empty($suffix)) {
             return $return;
         }
         $itemData = ['extension' => $this->config['extension'], 'quality' => (int) $this->config['quality'], 'file' => $fileName, 'source' => $sourceFile, 'directories' => ['source' => $targetPath, 'target' => $targetPath], 'targets' => []];
         if (false === is_file($itemData['source'])) {
             if ($files = glob($targetPath . DIRECTORY_SEPARATOR . $fileName . '*')) {
                 $fileSize = 0;
                 foreach ($files as $file) {
                     if ($fileSize < filesize($file)) {
                         $itemData['source'] = $file;
                         $fileSize = filesize($file);
                     }
                 }
             }
         }
         if (is_file($itemData['source'])) {
             if (false === empty($this->config['targets'])) {
                 foreach ($this->config['targets'] as $name => $target) {
                     if (isset($target['suffix']) && $suffix === $target['suffix']) {
                         $itemData['targets'][$name] = $target;
                         break;
                     }
                 }
             }
             if (empty($itemData['targets'])) {
                 if (false === empty($this->config['commands'])) {
                     $status = false;
                     foreach ($this->config['commands'] as $command) {
                         if (false === empty($command['targets'])) {
                             foreach ($command['targets'] as $name => $target) {
                                 if (isset($target['suffix']) && $suffix === $target['suffix']) {
                                     $itemData['targets'][$name] = $target;
                                     $status = true;
                                     break;
                                 }
                             }
                         }
                         if ($status) {
                             break;
                         }
                     }
                 }
             }
             if ($this->makeFile($itemData)) {
                 if (is_file($targetPath . DIRECTORY_SEPARATOR . basename($url))) {
                     $return = $targetPath . DIRECTORY_SEPARATOR . basename($url);
                 }
             }
         }
     }
     return $return;
 }
コード例 #11
0
ファイル: File.php プロジェクト: rmrevin/yii2-file
 /**
  * @return string
  */
 public function getAbsolutePath()
 {
     $upload_path = \rmrevin\yii\module\File\Module::module()->upload_path;
     $p1 = StringHelper::byteSubstr($this->name, 0, 2);
     $p2 = StringHelper::byteSubstr($this->name, 2, 2);
     return $upload_path . DIRECTORY_SEPARATOR . $p1 . DIRECTORY_SEPARATOR . $p2 . DIRECTORY_SEPARATOR . $this->name;
 }
コード例 #12
0
ファイル: index.php プロジェクト: BorisMatonickin/yiicms
                            </div>
                        </div>

                        <div class="col-xs-12 col-sm-10 blog-content">
                            <?php 
    $img = Html::img('@web/images/blog/' . Html::encode($page->cover_image), ['class' => 'img-responsive img-blog', 'width' => '100%']);
    ?>
                            <?php 
    echo Html::a($img, ['page/view', 'id' => $page->id]);
    ?>
                            <h2><?php 
    echo Html::a(Html::encode($page->title), ['page/view', 'id' => $page->id]);
    ?>
</h2>
                            <h3><?php 
    echo Html::encode(StringHelper::byteSubstr($page->content, 0, 215));
    ?>
...</h3>
                            <?php 
    echo Html::a('Read More', ['page/view', 'id' => $page->id], ['class' => 'btn btn-primary readmore']);
    ?>
                        </div>
                    </div>    
                </div><!--/.blog-item-->
                <?php 
}
?>

                <?php 
echo LinkPager::widget(['pagination' => $pagination, 'prevPageLabel' => 'Previous Page', 'nextPageLabel' => 'Next Page']);
?>
コード例 #13
0
ファイル: Context.php プロジェクト: alex-dwt/file
 /**
  * The method internally called in [[self::parseInputValue()]] and parse only string typed value.
  * @see [[self::parseInputValue()]]
  * @param string $value
  * @return string|null
  */
 protected function parseInputStringValue($value)
 {
     if ($value === '') {
         return null;
     }
     if (StringHelper::startsWith($value, $this->postParamUploadPrefix)) {
         $charset = Yii::$app->charset;
         $storagePrefixPos = mb_strpos($value, $this->postParamStoragePrefix, 0, $charset);
         $uploadPrefixLength = mb_strlen($this->postParamUploadPrefix, $charset);
         $valueLength = mb_strlen($value, $charset);
         $length = $storagePrefixPos === false ? $valueLength - $uploadPrefixLength : $storagePrefixPos - $uploadPrefixLength;
         $formName = mb_substr($value, $uploadPrefixLength, $length, $charset);
         if ($result = UploadedFile::getInstanceByName($formName)) {
             return $result;
         }
         if ($storagePrefixPos !== false) {
             $storagePrefixLength = mb_strlen($this->postParamStoragePrefix, $charset);
             $pos = $storagePrefixPos + $storagePrefixLength;
             $storageFileData = mb_substr($value, $pos, $valueLength - $pos, $charset);
         }
     }
     if (!isset($storageFileData) && StringHelper::startsWith($value, $this->postParamStoragePrefix)) {
         $storageFileData = StringHelper::byteSubstr($value, StringHelper::byteLength($this->postParamStoragePrefix));
     }
     if (isset($storageFileData) && $this->getStorage()->fileExists($storageFileData)) {
         return $storageFileData;
     }
     return null;
 }
コード例 #14
0
ファイル: View.php プロジェクト: appmake/yii2-minify-view
 /**
  * @param string $url
  *
  * @return null|string
  */
 private function getImportContent($url)
 {
     $result = null;
     if ('url(' === helpers\StringHelper::byteSubstr($url, 0, 4)) {
         $url = str_replace(['url(\'', 'url("', 'url(', '\')', '")', ')'], '', $url);
         if (helpers\StringHelper::byteSubstr($url, 0, 2) === '//') {
             $url = preg_replace('|^//|', 'http://', $url, 1);
         }
         $url = $this->rel2abs($url, Url::home(true));
         //var_dump($this->rel2abs($url, 'http://welooking.local'));
         //var_dump($url);
         if (!empty($url)) {
             $result = file_get_contents($url);
         }
     }
     return $result;
 }
コード例 #15
0
ファイル: Download.php プロジェクト: yiisoft/yii2-mongodb
 /**
  * Return part of a file.
  * @param int $start reading start position.
  * If non-negative, the returned string will start at the start'th position in file, counting from zero.
  * If negative, the returned string will start at the start'th character from the end of file.
  * @param int $length number of bytes to read.
  * If given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of file).
  * If given and is negative, then that many characters will be omitted from the end of file (after the start position has been calculated when a start is negative).
  * @return string|false the extracted part of file or `false` on failure
  */
 public function substr($start, $length)
 {
     $document = $this->getDocument();
     if ($start < 0) {
         $start = max($document['length'] + $start, 0);
     }
     if ($start > $document['length']) {
         return false;
     }
     if ($length < 0) {
         $length = $document['length'] - $start + $length;
         if ($length < 0) {
             return false;
         }
     }
     $chunkSize = $document['chunkSize'];
     $startChunkNumber = floor($start / $chunkSize);
     $chunkIterator = $this->getChunkIterator();
     if (!$chunkIterator->valid()) {
         // invalid iterator state - recreate iterator
         // unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
         $chunkIterator = $this->getChunkIterator(true);
     }
     if ($chunkIterator->key() > $startChunkNumber) {
         // unable to go back by iterator
         // unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
         $chunkIterator = $this->getChunkIterator(true);
     }
     $result = '';
     $chunkDataOffset = $start - $startChunkNumber * $chunkSize;
     while ($chunkIterator->valid()) {
         if ($chunkIterator->key() >= $startChunkNumber) {
             $chunk = $chunkIterator->current();
             $data = $chunk['data']->getData();
             $readLength = min($chunkSize - $chunkDataOffset, $length);
             $result .= StringHelper::byteSubstr($data, $chunkDataOffset, $readLength);
             $length -= $readLength;
             if ($length <= 0) {
                 break;
             }
             $chunkDataOffset = 0;
         }
         $chunkIterator->next();
     }
     return $result;
 }
コード例 #16
0
ファイル: View.php プロジェクト: audriusdob/yii2-minify-view
 /**
  * @param string $url
  * @return null|string
  */
 protected function _getImportContent($url)
 {
     $result = null;
     if ('url(' === helpers\StringHelper::byteSubstr($url, 0, 4)) {
         $url = str_replace(['url(\'', 'url("', 'url(', '\')', '")', ')'], '', $url);
         if (helpers\StringHelper::byteSubstr($url, 0, 2) === '//') {
             $url = preg_replace('|^//|', 'http://', $url, 1);
         }
         if (!empty($url)) {
             $result = file_get_contents($url);
         }
     }
     return $result;
 }
コード例 #17
0
ファイル: index.php プロジェクト: artoodetoo/BlogMVC
</h2>

                        <p>
                            Category: <?php 
    echo Html::a($post->category->name, '#');
    ?>
, by <?php 
    echo Html::a(ucfirst($post->user->username), '#');
    ?>
 on <?php 
    echo Yii::$app->formatter->asDate($post->created, 'long');
    ?>
                        </p>
                        <p>
                            <?php 
    echo Html::decode(nl2br(StringHelper::byteSubstr(Markdown::convert($post->content), 0, 400))) . '...';
    ?>
                            <br>
                            <?php 
    echo Html::a('Read more...', ['/post/view', 'id' => $post->id], ['class' => 'col-md-2 pull-right btn btn-primary']);
    ?>
                        </p>
                    </div>
                </div>
            </article>
        <?php 
}
?>
    </div>
    <div class="pagination">
        <?php 
コード例 #18
0
 /**
  * Checks if the given file path satisfies the filtering options.
  * @param string $path the path of the file or directory to be checked
  * @param array $options the filtering options. See [[findFiles()]] for explanations of
  * the supported options.
  * @return boolean whether the file or directory satisfies the filtering options.
  */
 public static function filterPath($path, $options)
 {
     if (isset($options['filter'])) {
         $result = call_user_func($options['filter'], $path);
         if (is_bool($result)) {
             return $result;
         }
     }
     if (empty($options['except']) && empty($options['only'])) {
         return true;
     }
     $path = str_replace('\\', '/', $path);
     if ($isDir = is_dir($path)) {
         $path .= '/';
     }
     $n = StringHelper::byteLength($path);
     if (!empty($options['except'])) {
         foreach ($options['except'] as $name) {
             if (StringHelper::byteSubstr($path, -StringHelper::byteLength($name), $n) === $name) {
                 return false;
             }
         }
     }
     if (!$isDir && !empty($options['only'])) {
         foreach ($options['only'] as $name) {
             if (StringHelper::byteSubstr($path, -StringHelper::byteLength($name), $n) === $name) {
                 return true;
             }
         }
         return false;
     }
     return true;
 }
コード例 #19
0
ファイル: Security.php プロジェクト: yiisoft/yii2
 /**
  * Validates if the given data is tampered.
  * @param string $data the data to be validated. The data must be previously
  * generated by [[hashData()]].
  * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
  * function to see the supported hashing algorithms on your system. This must be the same
  * as the value passed to [[hashData()]] when generating the hash for the data.
  * @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]].
  * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
  * of lowercase hex digits only.
  * hex digits will be generated.
  * @return string the real data with the hash stripped off. False if the data is tampered.
  * @throws InvalidConfigException when HMAC generation fails.
  * @see hashData()
  */
 public function validateData($data, $key, $rawHash = false)
 {
     $test = @hash_hmac($this->macHash, '', '', $rawHash);
     if (!$test) {
         throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
     }
     $hashLength = StringHelper::byteLength($test);
     if (StringHelper::byteLength($data) >= $hashLength) {
         $hash = StringHelper::byteSubstr($data, 0, $hashLength);
         $pureData = StringHelper::byteSubstr($data, $hashLength, null);
         $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
         if ($this->compareString($hash, $calculatedHash)) {
             return $pureData;
         }
     }
     return false;
 }
コード例 #20
0
ファイル: BaseSecurity.php プロジェクト: pathman/yii2comm
 /**
  * Validates if the given data is tampered.
  * @param string $data the data to be validated. The data must be previously
  * generated by [[hashData()]].
  * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
  * @param string $algorithm the hashing algorithm (e.g. "md5", "sha1", "sha256", etc.). Call PHP "hash_algos()"
  * function to see the supported hashing algorithms on your system. This must be the same
  * as the value passed to [[hashData()]] when generating the hash for the data.
  * @return string the real data with the hash stripped off. False if the data is tampered.
  * @see hashData()
  */
 public static function validateData($data, $key, $algorithm = 'sha256')
 {
     $hashSize = StringHelper::byteLength(hash_hmac($algorithm, 'test', $key));
     $n = StringHelper::byteLength($data);
     if ($n >= $hashSize) {
         $hash = StringHelper::byteSubstr($data, 0, $hashSize);
         $data2 = StringHelper::byteSubstr($data, $hashSize, $n - $hashSize);
         return $hash === hash_hmac($algorithm, $data2, $key) ? $data2 : false;
     } else {
         return false;
     }
 }
コード例 #21
0
ファイル: Model.php プロジェクト: cookyii/module-media
 /**
  * @return string
  */
 public function getAbsolutePath()
 {
     $upload_path = static::getMediaModule()->uploadPath;
     $p1 = StringHelper::byteSubstr($this->name, 0, 2);
     $p2 = StringHelper::byteSubstr($this->name, 2, 2);
     return $upload_path . DIRECTORY_SEPARATOR . $p1 . DIRECTORY_SEPARATOR . $p2 . DIRECTORY_SEPARATOR . $this->name;
 }
コード例 #22
0
ファイル: StringHelperTest.php プロジェクト: sciurodont/yii2
 public function testSubstr()
 {
     $this->assertEquals('th', StringHelper::byteSubstr('this', 0, 2));
     $this->assertEquals('э', StringHelper::byteSubstr('это', 0, 2));
 }
コード例 #23
0
ファイル: _sidebar.php プロジェクト: BorisMatonickin/yiicms
    ?>
                <div class="single_comments">
                    <?php 
    echo Html::img($comment->user->profile_image ? '@web/images/blog/' . Html::encode($comment->user->profile_image) : '@web/images/blog/avatar3.png', ['width' => '64', 'height' => '64']);
    ?>
                    <p><?php 
    echo Html::encode(StringHelper::byteSubstr($comment->comment, 0, 70));
    ?>
</p>
                    <div class="entry-meta small muted">
                        <span>By <?php 
    echo Html::a(Html::encode($comment->user->username), ['/profile', 'id' => $comment->user->id]);
    ?>
</span> <span>On 
                            <?php 
    $title = Html::encode(StringHelper::byteSubstr($comment->page->title, 0, 23));
    ?>
...</span>
                            <?php 
    echo Html::a($title, ['page/view', 'id' => $comment->page->id]);
    ?>
                    </div>
                </div>
                <?php 
}
?>
            </div>
        </div>                     
    </div><!--/.recent comments-->

    <div class="widget categories">
コード例 #24
0
ファイル: users.php プロジェクト: grutabow/getyii
use yii\helpers\Html;
/** @var \yii\base\Object $model */
/** @var \common\models\User $value */
?>

<?php 
foreach ($model as $key => $value) {
    ?>
    <div class="col-xs-2" style="min-width: 100px;">
        <div class="media user-card">
            <div class="media-left">
                <?php 
    echo Html::a(Html::img($value->userAvatar, ['class' => 'media-object']), ['/user/default/show', 'username' => $value['username']], ['title' => $value['username']]);
    ?>
            </div>
            <div class="media-body">
                <div class="media-heading">
                    <?php 
    echo Html::a(\yii\helpers\StringHelper::byteSubstr($value['username'], 0, 10), ['/user/default/show', 'username' => $value['username']], ['title' => $value['username']]);
    ?>
                </div>
                <div class="">
                    积分:<?php 
    echo $value->merit ? $value->merit->merit : 0;
    ?>
                </div>
            </div>
        </div>
    </div>
<?php 
}
コード例 #25
0
ファイル: Request.php プロジェクト: Wookashlab/MainRepo
 /**
  * Validates CSRF token
  *
  * @param string $token
  * @param string $trueToken
  * @return boolean
  */
 private function validateCsrfTokenInternal($token, $trueToken)
 {
     $token = base64_decode(str_replace('.', '+', $token));
     $n = StringHelper::byteLength($token);
     if ($n <= static::CSRF_MASK_LENGTH) {
         return false;
     }
     $mask = StringHelper::byteSubstr($token, 0, static::CSRF_MASK_LENGTH);
     $token = StringHelper::byteSubstr($token, static::CSRF_MASK_LENGTH, $n - static::CSRF_MASK_LENGTH);
     $token = $this->xorTokens($mask, $token);
     return $token === $trueToken;
 }
コード例 #26
0
ファイル: ImageWrapper.php プロジェクト: rmrevin/yii2-file
 /**
  * @return string[]
  */
 private function getPath()
 {
     $filename = basename($this->File->name);
     $p1 = StringHelper::byteSubstr($filename, 0, 2);
     $p2 = StringHelper::byteSubstr($filename, 2, 2);
     $p = DIRECTORY_SEPARATOR . $p1 . DIRECTORY_SEPARATOR . $p2;
     return [Module::module()->storage_path . $p, Module::module()->storage_web_path . $p];
 }