public function render($type) { $image = $this->image; if (!$image) { $image = $this->desktop->assetsUrl . '/images/icon_application.png'; } else { if (\yii\helpers\Url::isRelative($image) && $this->desktop->iconPath) { $image = rtrim($this->desktop->iconPath, '/') . '/' . $image; } } $attributes = ['src' => $image]; $styles = []; switch ($type) { case self::DISPLAY_MENU: $styles = ['height' => '16px', 'position' => 'relative', 'top' => '-2px']; break; case self::DISPLAY_DOCK: $styles = ['height' => '16px']; break; case self::DISPLAY_TITLEBAR: $styles = ['float' => 'left', 'margin' => '4px 5px 0 0', 'height' => '20px']; break; case self::DISPLAY_DESKTOP: $styles = ['height' => '32px']; break; } Html::addCssStyle($attributes, $styles); return Html::img($attributes['src'], $attributes); }
/** * @inheritdoc */ public function getAssetUrl($bundle, $asset) { if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) { if (strncmp($actualAsset, '@web/', 5) === 0) { $asset = substr($actualAsset, 5); $basePath = Yii::getAlias("@webroot"); $baseUrl = Yii::getAlias("@web"); } else { $asset = Yii::getAlias($actualAsset); $basePath = $this->basePath; $baseUrl = $this->baseUrl; } } else { $basePath = $bundle->basePath; $baseUrl = $bundle->baseUrl; } if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) { return $asset; } if ($this->appendTimestamp) { foreach (['', '.gz'] as $appendExtension) { if (($timestamp = @filemtime("{$basePath}/{$asset}{$appendExtension}")) > 0) { return "{$baseUrl}/{$asset}?v={$timestamp}"; } } } return "{$baseUrl}/{$asset}"; }
public function register() { $this->traitRegister(); if ($this->jsNotifier) { Yii::$app->on(\yii\web\Application::EVENT_BEFORE_ACTION, function ($event) { Yii::$app->view->on(\yii\web\View::EVENT_BEFORE_RENDER, function ($event) { $host = $this->errbit['host']; if (Url::isRelative($host)) { $host = '//' . $host; } $event->sender->registerJsFile(rtrim($host, '/') . '/javascripts/notifier.js', ['position' => \yii\web\View::POS_HEAD]); $js = 'Airbrake.setKey(' . Json::htmlEncode($this->errbit['api_key']) . ');'; $js .= 'Airbrake.setHost(' . Json::htmlEncode($this->errbit['host']) . ');'; if (isset($this->errbit['environment_name'])) { $js .= 'Airbrake.setEnvironment(' . Json::htmlEncode($this->errbit['environment_name']) . ');'; } if (is_array($this->jsOptions)) { foreach ($this->jsOptions as $key => $value) { $js .= 'Airbrake.set' . ucfirst($key) . '(' . Json::htmlEncode($value) . ');'; } } $controller = Yii::$app->controller; if ($controller !== null && $controller instanceof UserInfoInterface) { $user = $controller->getErrbitUserInfo(); if (is_array($user)) { $js .= 'Airbrake.setCurrentUser(' . Json::htmlEncode($user) . ');'; } } $event->sender->registerJs($js, \yii\web\View::POS_HEAD); }); }); } }
/** * @param \yii\web\Application $app */ public function bootstrap($app) { if ($app instanceof Application) { $app->response->on(Response::EVENT_AFTER_PREPARE, function (Event $e) use($app) { /** * @var $response Response */ $response = $e->sender; $this->trigger(self::EVENT_BEFORE_PROCESSING); if ($this->enabled && !$app->request->isAjax && !$app->request->isPjax && $app->response->format == Response::FORMAT_HTML) { \Yii::beginProfile('ExternalLinks'); $content = $response->content; $this->initReplaceLinks(); $matches = []; if (preg_match_all("/<[Aa][\\s]{1}[^>]*[Hh][Rr][Ee][Ff][^=]*=[ '\"\\s]*([^ \"'>\\s#]+)[^>]*>/", $content, $matches)) { if (isset($matches[1])) { foreach ($matches[1] as $link) { //Относительные ссылки пропускать if (Url::isRelative($link)) { continue; } if ($dataLink = parse_url($link)) { //Для этого хоста не нужно менять ссылку $host = ArrayHelper::getValue($dataLink, 'host'); if (in_array($host, $this->noReplaceLinksOnDomains)) { continue; } } $linkForUrl = $link; if ($this->enabledB64Encode) { $linkForUrl = base64_encode($link); } $newUrl = Url::to([$this->backendRoute, $this->backendRouteParam => $linkForUrl]); //replacing references only after <body $bodyPosition = strpos($content, '<body'); $headerContent = substr($content, 0, $bodyPosition); $bodyContent = substr($content, $bodyPosition, strlen($content)); $resultContent = ''; $replaceUrl = 'href="' . $newUrl . '"'; $bodyContent = str_replace('href="' . $link . '"', $replaceUrl, $bodyContent); $replaceUrl = 'href=\'' . $newUrl . '\''; $bodyContent = str_replace('href=\'' . $link . '\'', $replaceUrl, $bodyContent); $resultContent = $headerContent . $bodyContent; $content = $resultContent; } } } $response->content = $content; \Yii::endProfile('ExternalLinks'); } }); } }
/** * @param $hash * @param array $params * @param string $translit * @param null $default * @return null|string */ public static function absoluteUrl($hash, array $params = [], $translit = '', $default = null) { if (!$hash) { return $default; } if (!Url::isRelative($hash)) { return $hash; } $imbo = self::getImbo(); $imageUrl = $imbo->getImageUrl($hash); $imageUrl->thumbnail()->jpg(); $response = $imbo->generateShortUrl($imageUrl); return $imbo->imageDomain . '/s/' . $response['id']; }
/** * @param $from * @param $to * @param $imports * @return string */ public static function rewrite($from, $to, &$imports) { $dirFrom = FileHelper::normalizePath(dirname($from)); $dirTo = FileHelper::normalizePath(dirname($to)); $content = file_get_contents($from); if ($dirFrom == $dirTo) { return $content; } // Относительный путь $path = ''; while (0 !== strpos($dirFrom, $dirTo)) { $path .= '../'; if (false !== ($pos = strrpos($dirTo, '/'))) { $dirTo = substr($dirTo, 0, $pos); } else { $dirTo = ''; break; } } $path .= ltrim(substr($dirFrom . '/', strlen($dirTo)), '/'); // Заменяем адреса $content = CssUtils::filterUrls($content, function ($matches) use($path) { if (!Url::isRelative($matches['url']) || 0 === strpos($matches['url'], 'data:') || isset($matches['url'][0]) && '/' == $matches['url'][0]) { // Абсолютный путь или data uri bили путь относительно корня return $matches[0]; } // Пусть относительно файла $url = FileHelper::normalizePath($path . $matches['url'], '/'); return str_replace($matches['url'], $url, $matches[0]); }); // Собираем и корректируем импорты $newImports = CssUtils::extractImports($content); if (!empty($newImports)) { foreach ($newImports as $i => $import) { if (!Url::isRelative($import) || 0 === strpos($import, 'data:') || isset($import[0]) && '/' == $import[0]) { // Абсолютный путь или data uri bили путь относительно корня continue; } // Пусть относительно файла $newImports[$i] = FileHelper::normalizePath($path . $import, '/'); } $imports = array_merge($imports, $newImports); } return $content; }
/** * Publishes the asset bundle if its source code is not under Web-accessible directory. * It will also try to convert non-CSS or JS files (e.g. LESS, Sass) into the corresponding * CSS or JS files using [[AssetManager::converter|asset converter]]. * @param AssetManager $am the asset manager to perform the asset publishing */ public function publish($am) { if ($this->sourcePath !== null && !isset($this->basePath, $this->baseUrl)) { list($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions); } if (isset($this->basePath, $this->baseUrl) && ($converter = $am->getConverter()) !== null) { foreach ($this->js as $i => $js) { if (Url::isRelative($js)) { $this->js[$i] = $converter->convert($js, $this->basePath); } } foreach ($this->css as $i => $css) { if (Url::isRelative($css)) { $this->css[$i] = $converter->convert($css, $this->basePath); } } } }
/** * @param array $files * @return array */ protected function _processingCssFiles($files = []) { $fileName = md5(implode(array_keys($files)) . $this->getSettingsHash()) . '.css'; $publicUrl = \Yii::getAlias('@web/assets/css-compress/' . $fileName); $rootDir = \Yii::getAlias('@webroot/assets/css-compress'); $rootUrl = $rootDir . '/' . $fileName; if (file_exists($rootUrl)) { $resultFiles = []; foreach ($files as $fileCode => $fileTag) { if (Url::isRelative($fileCode)) { } else { if (!$this->cssFileRemouteCompile) { $resultFiles[$fileCode] = $fileTag; } } } $publicUrl = $publicUrl . "?v=" . filemtime($rootUrl); $resultFiles[$publicUrl] = Html::cssFile($publicUrl); return $resultFiles; } //Reading the contents of the files try { $resultContent = []; $resultFiles = []; foreach ($files as $fileCode => $fileTag) { if (Url::isRelative($fileCode)) { $contentTmp = trim($this->fileGetContents(Url::to(\Yii::getAlias($fileCode), true))); $fileCodeTmp = explode("/", $fileCode); unset($fileCodeTmp[count($fileCodeTmp) - 1]); $prependRelativePath = implode("/", $fileCodeTmp) . "/"; $contentTmp = \Minify_CSS::minify($contentTmp, ["prependRelativePath" => $prependRelativePath, 'compress' => true, 'removeCharsets' => true, 'preserveComments' => true]); //$contentTmp = \CssMin::minify($contentTmp); $resultContent[] = $contentTmp; } else { if ($this->cssFileRemouteCompile) { //Пытаемся скачать удаленный файл $resultContent[] = trim($this->fileGetContents($fileCode)); } else { $resultFiles[$fileCode] = $fileTag; } } } } catch (\Exception $e) { \Yii::error($e->getMessage(), static::className()); return $files; } if ($resultContent) { $content = implode($resultContent, "\n"); if (!is_dir($rootDir)) { if (!FileHelper::createDirectory($rootDir, 0777)) { return $files; } } if ($this->cssFileCompress) { $content = \CssMin::minify($content); } $page = \Yii::$app->request->absoluteUrl; $useFunction = function_exists('curl_init') ? 'curl extension' : 'php file_get_contents'; $filesString = implode(', ', array_keys($files)); \Yii::info("Create css file: {$publicUrl} from files: {$filesString} to use {$useFunction} on page '{$page}'", static::className()); $file = fopen($rootUrl, "w"); fwrite($file, $content); fclose($file); } if (file_exists($rootUrl)) { $publicUrl = $publicUrl . "?v=" . filemtime($rootUrl); $resultFiles[$publicUrl] = Html::cssFile($publicUrl); return $resultFiles; } else { return $files; } }
public static function getRedirect() { if (!($redirect = Yii::$app->getRequest()->get('redirect')) || !\yii\helpers\Url::isRelative($redirect)) { $redirect = null; } return $redirect; }
/** * Delete all thumbs from the thumbs directorys * You should use this function in conjunction with the [[deleteFile]] call function within a cron job. * @param string The url from the original file. This must be a relative url. */ public function deleteThumbs($url) { if (!Url::isRelative($url)) { throw new \yii\base\InvalidParamException('Url must be relative'); } $info = pathinfo($url); $webroot = Yii::getAlias('@webroot'); $thumbStyles = array_keys($this->thumbStyles); //Delete all files in the thumb styles directories foreach ($thumbStyles as $style) { $file = $webroot . DIRECTORY_SEPARATOR . $info['dirname'] . DIRECTORY_SEPARATOR . $this->thumbDirectory . DIRECTORY_SEPARATOR . $style . DIRECTORY_SEPARATOR . $info['basename']; @unlink($file); } //Delete the files in the thumbDirectory (default thumbs) //$pattern = $info['filename'] . '_[1-9]{1}[0-9]*x{1}[1-9]{1}[0-9]*\.(jpg|jpeg|gif|png)'; $pattern = $info['filename'] . '_*x*.*'; $files = glob($webroot . DIRECTORY_SEPARATOR . $info['dirname'] . DIRECTORY_SEPARATOR . $this->thumbDirectory . DIRECTORY_SEPARATOR . $pattern); foreach ($files as $file) { @unlink($file); } return $files; }
/** * @param array $files * @return array */ protected function _processingCssFiles($files = []) { $fileName = md5(implode(array_keys($files)) . $this->getSettingsHash()) . '.css'; $publicUrl = Yii::getAlias('@web/assets/css-compress/' . $fileName); $rootDir = Yii::getAlias('@webroot/assets/css-compress'); $rootUrl = $rootDir . '/' . $fileName; if (file_exists($rootUrl)) { $resultFiles = []; foreach ($files as $fileCode => $fileTag) { if (!Url::isRelative($fileCode) && !$this->cssFileRemouteCompile) { $resultFiles[$fileCode] = $fileTag; } } $publicUrl = $publicUrl . "?v=" . filemtime($rootUrl); $resultFiles[$publicUrl] = Html::cssFile($publicUrl); return $resultFiles; } $resultContent = []; $resultFiles = []; foreach ($files as $fileCode => $fileTag) { if (Url::isRelative($fileCode)) { $contentTmp = trim($this->fileGetContents(Url::to(Yii::$app->request->hostInfo . $fileCode, true))); $fileCodeTmp = explode("/", $fileCode); unset($fileCodeTmp[count($fileCodeTmp) - 1]); $prependRelativePath = implode("/", $fileCodeTmp) . "/"; $contentTmp = \Minify_CSS::minify($contentTmp, ["prependRelativePath" => $prependRelativePath, 'compress' => true, 'removeCharsets' => true, 'preserveComments' => true]); //$contentTmp = \CssMin::minify($contentTmp); $resultContent[] = $contentTmp; } else { if ($this->cssFileRemouteCompile) { //Trying to download a remote file $resultContent[] = trim($this->fileGetContents($fileCode)); } else { $resultFiles[$fileCode] = $fileTag; } } } if ($resultContent) { $content = implode($resultContent, "\n"); if (!is_dir($rootDir)) { if (!FileHelper::createDirectory($rootDir, 0777)) { return $files; } } if ($this->cssFileCompress) { $content = \CssMin::minify($content); } $file = fopen($rootUrl, "w"); fwrite($file, $content); fclose($file); } if (file_exists($rootUrl)) { $publicUrl = $publicUrl . "?v=" . filemtime($rootUrl); $resultFiles[$publicUrl] = Html::cssFile($publicUrl); return $resultFiles; } else { return $files; } }
public function testAlternativeEndPageWithVersion() { $view = $this->getView(); $view->assetManager->appendTimestamp = true; $view->expand_imports = false; $view->force_charset = false; minify\tests\unit\data\TestAssetBundle::register($view); ob_start(); echo '<html>This is test page versioning</html>'; $view->endBody(); $this->assertEquals(2, count($view->jsFiles[minify\View::POS_HEAD])); $this->assertEquals(1, count($view->jsFiles[minify\View::POS_READY])); foreach ($view->jsFiles[minify\View::POS_HEAD] as $file => $html) { if (Url::isRelative($file)) { $this->assertTrue(strpos($file, '?v=') !== false); } } foreach ($view->jsFiles[minify\View::POS_READY] as $file => $html) { if (Url::isRelative($file)) { $this->assertTrue(strpos($file, '?v=') !== false); } } $view->endPage(false); }
public function testIsRelative() { $this->assertTrue(Url::isRelative('/test/index.php')); $this->assertTrue(Url::isRelative('index.php')); $this->assertFalse(Url::isRelative('//example.com/')); $this->assertFalse(Url::isRelative('http://example.com/')); $this->assertFalse(Url::isRelative('https://example.com/')); }
/** * Function performing the minification of asset files. * @param \yii\web\AssetBundle $bundle * @param string $filename * @return string The path of the minified file. */ protected function minify($bundle, $filename) { if (Url::isRelative($filename)) { if ($this->workPath === self::WORKPATH_SOURCE) { $sourcePath = $bundle->sourcePath ? $bundle->sourcePath : Yii::getAlias('@webroot'); } else { $sourcePath = $bundle->basePath; } $this->refreshAssetBundle($bundle, $sourcePath, dirname($filename)); $sourcePath = $bundle->basePath . '/' . $filename; $extension = pathinfo($filename, PATHINFO_EXTENSION); $filename = preg_replace('/\\.(min\\.)*' . preg_quote($extension, '/') . '$/i', '.min.' . $extension, $filename); $minPath = "{$bundle->basePath}/{$filename}"; if ($this->testFile($minPath, $sourcePath)) { file_put_contents($minPath, $this->getMinifierByExtension($extension)->minify($sourcePath)); $this->createGzFile($minPath); } } return $filename; }
/** * @param AssetBundle $bundle * @param string $asset * @return string|boolean */ protected function resolveAsset($bundle, $asset) { if (isset($this->assetMap[$asset])) { return $this->assetMap[$asset]; } if ($bundle->sourcePath !== null && Url::isRelative($asset)) { $asset = $bundle->sourcePath . '/' . $asset; } $n = mb_strlen($asset); foreach ($this->assetMap as $from => $to) { $n2 = mb_strlen($from); if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) { return $to; } } return false; }
echo Html::encode($user->userInfo->info); ?> </div> </div> <?php } ?> <?php if ($user->userInfo->website) { ?> <div class="panel panel-default"> <div class="panel-heading"><i class="fa fa-link"></i>个人网站</div> <div class="panel-body"> <?php if (\yii\helpers\Url::isRelative($user->userInfo->website)) { $user->userInfo->website = 'http://' . $user->userInfo->website; } echo Html::a(Html::encode($user->userInfo->website), Html::encode($user->userInfo->website)); ?> </div> </div> <?php } ?> <div class="panel panel-default"> <div class="panel-heading"><i class="fa fa-dashboard"></i>个人成就</div> <ul class="list-group"> <li class="list-group-item text-right"> <span class="pull-left"><strong class="">被感谢次数</strong></span>
/** * Publishes the asset bundle if its source code is not under Web-accessible directory. * It will also try to convert non-CSS or JS files (e.g. LESS, Sass) into the corresponding * CSS or JS files using [[AssetManager::converter|asset converter]]. * @param AssetManager $am the asset manager to perform the asset publishing */ public function publish($am) { if ($this->sourcePath !== null && !isset($this->basePath, $this->baseUrl)) { list($this->basePath, $this->baseUrl) = $am->publish($this->sourcePath, $this->publishOptions); } if (isset($this->basePath, $this->baseUrl) && ($converter = $am->getConverter()) !== null) { foreach ($this->js as $i => $js) { if (is_array($js)) { $file = array_shift($js); if (Url::isRelative($file)) { $js = ArrayHelper::merge($this->jsOptions, $js); array_unshift($js, $converter->convert($file, $this->basePath)); $this->js[$i] = $js; } } elseif (Url::isRelative($js)) { $this->js[$i] = $converter->convert($js, $this->basePath); } } foreach ($this->css as $i => $css) { if (is_array($css)) { $file = array_shift($css); if (Url::isRelative($file)) { $css = ArrayHelper::merge($this->cssOptions, $css); array_unshift($css, $converter->convert($file, $this->basePath)); $this->css[$i] = $css; } } elseif (Url::isRelative($css)) { $this->css[$i] = $converter->convert($css, $this->basePath); } } } }
/** * Combining asset files depending on type. * @param AssetBundle $assetBundle The AssetBundle to be processed. * @param string $property The type of the assets to be processed, `css` or `js`. * @param integer $position The position of the AssetBundle. */ protected function combineAssetBundle($assetBundle, $property, $position) { foreach ($assetBundle->{$property} as $filename) { if (is_array($filename)) { $filename = array_shift($filename); } if (Url::isRelative($filename)) { $path = $assetBundle->basePath . '/' . $filename; $this->_files[$position][$property][$path . @filemtime($path)] = ['basePath' => $path, 'baseUrl' => dirname($assetBundle->baseUrl . '/' . $filename)]; } else { $this->_assetBundles[$position]->{$property}[] = $filename; } } }