public function init() { // default path to runtime if (!Alias::existsAlias('runtime')) { Alias::setAlias('runtime', dirname(__DIR__) . '/runtime'); } $this->twig = new \Twig_Environment(null, array_merge(['cache' => Alias::getAlias($this->cachePath)], $this->options)); //$this->twig->setBaseTemplateClass('rock\template\twig\Template'); // Adding custom globals (objects or static classes) if (!empty($this->globals)) { $this->addGlobals($this->globals); } // Adding custom functions if (!empty($this->functions)) { $this->addFunctions($this->functions); } // Adding custom filters if (!empty($this->filters)) { $this->addFilters($this->filters); } $this->addExtensions([new Extension($this->uses)]); // Adding custom extensions if (!empty($this->extensions)) { $this->addExtensions($this->extensions); } //$this->twig->addGlobal('app', \rock\Rock::$app); // Change lexer syntax (must be set after other settings) if (!empty($this->lexerOptions)) { $this->addLexerOptions($this->lexerOptions); } }
/** * Renders a view with a layout. * @param string $layout name of the view to be rendered. * @param array $placeholders list placeholders. * @param string $defaultPathLayout * @param bool $isAjax * @return string the rendering result. Null if the rendering result is not required. * @throws \Exception */ public function render($layout, array $placeholders = [], $defaultPathLayout = '@views', $isAjax = false) { $layout = FileHelper::normalizePath(Alias::getAlias($layout)); if (!strstr($layout, DS)) { $class = explode('\\', get_class($this)); $layout = Alias::getAlias($defaultPathLayout) . DS . 'layouts' . DS . strtolower(str_replace('Controller', '', array_pop($class))) . DS . $layout; } return $this->getTemplate()->render($layout, $placeholders, $this, $isAjax); }
public function init() { if (!($this->adapter = Instance::ensure($this->adapter, null, [], false))) { throw new ImageException(ImageException::NOT_INSTALL_FILE); } $this->adapterCache = Instance::ensure($this->adapterCache); $this->srcImage = Alias::getAlias($this->srcImage); $this->srcCache = Alias::getAlias($this->srcCache); }
public function init() { $this->path = Alias::getAlias($this->path); $this->pathAssignments = Alias::getAlias($this->pathAssignments); if (empty(static::$items)) { static::$items = $this->load($this->path); } if (empty(static::$assignments)) { static::$assignments = $this->load($this->pathAssignments); } }
/** * Set config scope * * @param string $path path to config * @param bool $clear clear DIC. * @throws RouteException * @throws \Exception */ public static function setConfigScope($path, $clear = true) { $path = Alias::getAlias($path); if (!file_exists($path) || !($config = (require $path))) { throw new RouteException(RouteException::UNKNOWN_FILE, ['path' => $path]); } if ($clear) { Container::removeAll(); } $components = $config['components'] ?: []; if (class_exists('\\rock\\Rock')) { unset($config['components']); Rock::$components = $components; Rock::$config = $config; } Container::registerMulti($components); }
public function get() { if (!($dataImage = $this->captcha->get())) { return '#'; } if ($dataImage['mime_type'] === 'image/x-png') { $ext = '.png'; } elseif ($dataImage['mime_type'] === 'image/jpeg') { $ext = '.jpg'; } else { $ext = '.gif'; } $uniq = uniqid(); $path = Alias::getAlias('@assets') . DS . 'cache' . DS . 'captcha' . DS . $uniq . $ext; if (FileHelper::create($path, $dataImage['image'])) { return Alias::getAlias('@web') . '/cache/captcha/' . $uniq . $ext; } return '#'; }
/** * Saves the uploaded file. * Note that this method uses php's move_uploaded_file() method. If the target file `$file` * already exists, it will be overwritten. * * @param string $file the file path used to save the uploaded file * @param boolean $deleteTempFile whether to delete the temporary file after saving. * If true, you will not be able to save the uploaded file again in the current request. * @param bool $createDir * @return bool true whether the file is saved successfully * @throws \Exception * @see error */ public function saveAs($file, $deleteTempFile = true, $createDir = false) { if ($this->error !== UPLOAD_ERR_OK) { return false; } $file = Alias::getAlias($file); if ($this->calculatePathname instanceof \Closure) { $file = call_user_func($this->calculatePathname, $this, $file, $this->adapter); } if ($createDir) { FileHelper::createDirectory(dirname($file)); } if ($deleteTempFile) { return move_uploaded_file($this->tempName, $file); } elseif (is_uploaded_file($this->tempName)) { return copy($this->tempName, $file); } return false; }
protected static function calculateConfig($config) { if (is_string($config)) { $class = Alias::getAlias($config); $config = []; } elseif (isset($config['class'])) { $class = Alias::getAlias($config['class']); unset($config['class'], $config['singleton']); } else { throw new ContainerException('Object configuration must be an array containing a "class" element.'); } $class = ltrim(str_replace(['\\', '_', '/'], '\\', $class), '\\'); return [$class, $config]; }
/** * @param string $path the current session save path. This can be either a directory name or a path alias. * @throws SessionException if the path is not a valid directory */ public function setSavePath($path) { $path = Alias::getAlias($path); if (is_dir($path)) { session_save_path($path); } else { throw new SessionException("Session save path is not a valid directory: {$path}."); } }
/** * Adds a frame around of the image. Please note that the image size will increase by `$margin` x 2. * * @param string|resource $pathOrResource the full path to the image file * @param integer $margin the frame size to add around the image * @param string $color the frame color * @param integer $alpha the alpha value of the frame. * @return ImageInterface */ public static function frame($pathOrResource, $margin = 20, $color = '666', $alpha = 100) { /** @var ImageInterface $img */ $img = is_resource($pathOrResource) ? static::getImagine()->read($pathOrResource) : static::getImagine()->open(Alias::getAlias($pathOrResource)); $size = $img->getSize(); $pasteTo = new Point($margin, $margin); $box = new Box($size->getWidth() + ceil($margin * 2), $size->getHeight() + ceil($margin * 2)); $image = static::getImagine()->create($box, (new RGB())->color($color, $alpha)); $image->paste($img, $pasteTo); return $image; }
protected function normalizeRules(array &$result = [], array &$aliases = [], array $rules, array $params = [], array $group = []) { foreach ($rules as $alias => $rule) { if ($rule[0] === self::REST) { $this->normalizeRules($result, $aliases, ArrayHelper::only($this->RESTHandlers, Helper::getValue($rule['only'], []), Helper::getValue($rule['exclude'], [])), ['prefix' => $alias, 'replace' => $rule[1], 'controller' => $rule[2], 'filters' => isset($rule['filters']) ? $rule['filters'] : null], $group); continue; } list(, $pattern) = $rule; if (is_string($alias)) { if (isset($params['replace'])) { if (isset($params['prefix']) && !is_string($params['prefix'])) { $params['prefix'] = $params['replace']; } $alias = "{$params['prefix']}.{$alias}"; } if (isset($group['as'])) { $alias = "{$group['as']}.{$alias}"; } } $result[$alias] = $rule; if (isset($params['controller'])) { $result[$alias]['params']['controller'] = $params['controller']; } if (isset($params['filters']) && !isset($result[$alias][3])) { $result[$alias]['filters'] = $params['filters']; } if (!is_array($pattern)) { $value = $pattern; $pattern = []; $pattern[self::FILTER_PATH] = $value; } if (isset($pattern[self::FILTER_PATH])) { if (isset($params['replace'])) { $pattern[self::FILTER_PATH] = is_array($params['replace']) ? strtr($pattern[self::FILTER_PATH], $params['replace']) : str_replace('{url}', $params['replace'], $pattern[self::FILTER_PATH]); } if (isset($group[self::FILTER_PATH])) { $pattern[self::FILTER_PATH] = rtrim($group[self::FILTER_PATH], '/') . '/' . ltrim($pattern[self::FILTER_PATH], '/'); } } foreach ($pattern as $key => &$data) { if (is_array($data)) { foreach ($data as $k => $value) { if (is_string($value)) { $data[$k] = $this->parse($value, '.+'); } } continue; } $data = $key != self::FILTER_PATH ? $this->parse($data, '.+') : $this->parse($data); } $result[$alias][1] = $pattern; if (is_string($alias)) { $build = $this->buildAlias($pattern, $params, $group); $placeholders = ['self_path' => $this->request->getUrlWithoutArgs(), 'self_scheme' => $this->request->getScheme()]; foreach ($this->request->rawGet() ?: [] as $name => $placeholder) { $placeholders["self_query_{$name}"] = $placeholder; } Alias::setAlias(str_replace('/', '.', $alias), StringHelper::replace($build, $placeholders, false), false); $aliases[$alias] = $build; } } }
\rock\base\Alias::setAlias('root', dirname(dirname(dirname(__DIR__)))); \rock\base\Alias::setAlias('rock', \rock\Rock::$dir); \rock\base\Alias::setAlias('vendor', '@root/vendor'); \rock\base\Alias::setAlias('assets', '@root/public/assets'); \rock\base\Alias::setAlias('web', '/assets'); \rock\base\Alias::setAlias('web.img', '/assets/images'); \rock\base\Alias::setAlias('app', '@root/apps'); \rock\base\Alias::setAlias('common', '@app/common'); \rock\base\Alias::setAlias('frontend', '@app/frontend'); \rock\base\Alias::setAlias('backend', '@app/backend'); \rock\base\Alias::setAlias('admin', '@backend'); // namespaces \rock\base\Alias::setAlias('common.ns', 'apps\\common'); \rock\base\Alias::setAlias('frontend.ns', 'apps\\frontend'); \rock\base\Alias::setAlias('backend.ns', 'apps\\backend'); \rock\base\Alias::setAlias('ns', '@common.ns'); // runtime \rock\base\Alias::setAlias('common.runtime', '@common/runtime'); // views \rock\base\Alias::setAlias('common.views', '@common/views'); \rock\base\Alias::setAlias('frontend.views', '@frontend/views'); // media \rock\base\Alias::setAlias('img', '@assets/images'); \rock\base\Alias::setAlias('images', '@img'); // links $request = new \rock\request\Request(); \rock\base\Alias::setAlias('link.home', $request->getHostInfo() ?: 'localhost'); \rock\base\Alias::setAlias('link.ajax', '@link.home/ajax'); \rock\base\Alias::setAlias('email', 'support@' . ($request->getHost() ?: 'localhost')); $config = \rock\helpers\ArrayHelper::merge(require \rock\base\Alias::getAlias('@rock/classes.php'), require __DIR__ . '/classes.php', require __DIR__ . '/controllers.php'); return ['components' => $config];
/** * Initializes the widget. * This renders the form open tag. */ public function init() { $this->csrf = Instance::ensure($this->csrf, '\\rock\\csrf\\CSRF', [], false); $this->request = Instance::ensure($this->request, '\\rock\\request\\Request'); if (!empty($this->clientAction)) { $this->clientAction = Alias::getAlias($this->clientAction); } if (!isset($this->options['id'])) { $this->options['id'] = $this->getId(); } if (!isset($this->fieldConfig['class'])) { $this->fieldConfig['class'] = ActiveField::className(); $this->fieldConfig['enableClientValidation'] = $this->enableClientValidation; $this->fieldConfig['validateOnChanged'] = $this->validateOnChanged; } $this->modelName = $this->model->formName(); $this->options = $this->clientOptions($this->options); echo ActiveHtml::beginForm($this->action, $this->method, $this->modelName, $this->options); }
/** * Display fatal error. * * @param Response $response * @throws \Exception */ public static function displayFatal(Response $response = null) { if (isset($response)) { $response->setStatusCode(500); $response->send(); $request = new Request(); if ($response->format !== Response::FORMAT_HTML || $request->isAjax() || $request->isCORS()) { echo 0; return; } } if (!isset(static::$pathFatal) || !file_exists(Alias::getAlias(static::$pathFatal))) { die('This site is temporarily unavailable. Please, visit the page later.'); } die(file_get_contents(Alias::getAlias(static::$pathFatal))); }
/** * @param string $value * @return string */ protected function preparePath($value) { return Alias::getAlias($this->path) . DIRECTORY_SEPARATOR . md5($value) . '.php'; }
/** * Returns current url. * @return string * @throws \Exception */ protected function currentInternal() { return $this->current ? Alias::getAlias($this->current) : $this->request->getAbsoluteUrl(); }
<?php use rock\base\Alias; use rock\db\BatchQueryResult; use rock\rbac\Permission; use rock\rbac\Role; use rock\Rock; use rock\security\Security; use rock\template\Template; return array_merge(['route' => ['class' => \rock\route\Route::className()], 'access' => ['class' => \rock\access\Access::className()], 'behavior' => ['class' => \rock\components\Behavior::className()], 'db' => ['class' => \rock\db\Connection::className(), 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'dsn' => 'mysql:host=localhost;dbname=rockdemo;charset=utf8', 'tablePrefix' => 'spt_', 'aliasSeparator' => '__'], 'BatchQueryResult' => ['class' => BatchQueryResult::className()], 'template' => ['class' => Template::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale'], 'autoEscape' => Template::ESCAPE | Template::TO_TYPE, 'handlerLink' => function ($link, Template $template, array $params = []) { if (!($link = Alias::getAlias("@{$link}", [], false))) { return '#'; } return $template->autoEscape(\rock\template\filters\BaseFilter::modifyUrl($link, $params)); }, 'extensions' => ['cfg' => function (array $keys) { return \rock\helpers\ArrayHelper::getValue(Rock::$config, $keys); }, 'user' => function (array $keys) { if (current($keys) === 'isGuest') { return Rock::$app->user->isGuest(); } elseif (in_array(current($keys), ['isLogged', 'isAuthenticated'], true)) { return !Rock::$app->user->isGuest(); } return \rock\helpers\ArrayHelper::getValue(Rock::$app->user->getAll(), $keys); }, 'call' => function (array $call, array $params = [], Template $template) { if (!isset($call[1])) { $call[1] = null; } list($class, $method) = $call; if ($class === 'context') { $object = $template->context; $function = [$object, $method];
<?php // Config scope "frontend" $config = (require dirname(dirname(__DIR__)) . '/common/configs/configs.php'); \rock\base\Alias::setAlias('scope', '@frontend'); \rock\base\Alias::setAlias('views', '@frontend/views'); \rock\base\Alias::setAlias('runtime', '@frontend/runtime'); \rock\base\Alias::setAlias('ns', '@frontend.ns'); $request = new \rock\request\Request(); \rock\base\Alias::setAlias('link.home', $request->getHostInfo()); \rock\base\Alias::setAlias('link.ajax', '@link.home/ajax'); \rock\base\Alias::setAlias('email', 'support@' . $request->getHost()); $config['components'] = \rock\helpers\ArrayHelper::merge($config['components'], require __DIR__ . '/classes.php', require __DIR__ . '/models.php', require __DIR__ . '/controllers.php'); return $config;
/** * Sets a path to dictionaries. * @param string $pathDict * @return $this */ public function setPathDict($pathDict) { $this->pathDict = Alias::getAlias($pathDict); return $this; }
protected function defaultHandlers() { $path = $path = Alias::getAlias('@runtime/logs'); FileHelper::createDirectory($path); $paths = [self::DEBUG => "{$path}/debug.log", self::INFO => "{$path}/info.log", self::NOTICE => "{$path}/error.log", self::WARNING => "{$path}/error.log", self::ERROR => "{$path}/error.log", self::CRITICAL => "{$path}/error.log", self::ALERT => "{$path}/error.log", self::EMERGENCY => "{$path}/error.log"]; $formatter = new LineFormatter("[%datetime%]\t%level_name%\t%extra.hash%\t%message%\t%extra.user_id%\t%extra.user_ip%\t%extra.user_agent%\n"); $this->logger->pushProcessor(function ($record) { $record['extra']['hash'] = substr(md5($record['message']), -6); $record['extra']['user_agent'] = strip_tags($_SERVER['HTTP_USER_AGENT']); $record['extra']['user_ip'] = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP); $record['extra']['user_id'] = isset($_SESSION['user']['id']) ? $_SESSION['user']['id'] : 'NULL'; return $record; }); $handlers = []; foreach ($paths as $level => $path) { $handlers[$level] = (new StreamHandler($path, $level, false))->setFormatter($formatter); } return $handlers; }
/** * Adds dicts. * * ```php * [ 'ru' => * [ * 'path/lang/ru/lang.php', * 'path/lang/ru/validate.php', * ] * ] * ``` * * @param array $dicts * @throws \Exception * @throws i18nException */ public function addDicts(array $dicts) { if (!empty(static::$data)) { return; } foreach ($dicts as $lang => $paths) { $total = []; foreach ($paths as $path) { $path = Alias::getAlias($path); if (!file_exists($path) || !($data = (require $path)) || !is_array($data)) { throw new i18nException(i18nException::UNKNOWN_FILE, ['path' => $path]); break 2; } $context = basename($path, '.php'); $total[$context] = array_merge(Helper::getValue($total[$context], [], true), $data); } static::$data[$lang] = array_merge(Helper::getValue(static::$data[$lang], [], true), $total); } }
/** * @return string the homepage URL */ public function getHomeUrl() { if ($this->_homeUrl === null) { if ($this->showScriptName) { return $this->getScriptUrl(); } else { return $this->getBaseUrl() . '/'; } } else { return Alias::getAlias($this->_homeUrl); } }
/** * Normalize path. * @param string $path * @return string * @throws TemplateException * @throws \Exception */ protected function normalizePath($path) { $path = Alias::getAlias($path, ['lang' => $this->locale]); $path = FileHelper::normalizePath($path, DIRECTORY_SEPARATOR, false); if (!pathinfo($path, PATHINFO_EXTENSION)) { $path .= '.' . $this->defaultExtension; } $normalizePath = $path; // relative path if ((strpos($normalizePath, DIRECTORY_SEPARATOR) === false || strpos($normalizePath, '.' . DIRECTORY_SEPARATOR) !== false) && $this->path) { $normalizePath = dirname($this->path) . DIRECTORY_SEPARATOR . $normalizePath; $normalizePath = realpath($normalizePath); } if (!file_exists($normalizePath)) { throw new TemplateException(TemplateException::UNKNOWN_FILE, ['path' => $path]); } return $normalizePath; }
<?php return ['db' => ['class' => 'rock\\db\\Connection', 'username' => 'rock', 'password' => 'rock', 'charset' => 'utf8', 'dsn' => 'mysql:host=localhost;dbname=rockdemo;charset=utf8', 'tablePrefix' => 'spt_', 'aliasSeparator' => '__', 'enableSchemaCache' => true], 'template' => ['chroots' => ['@common/views', '@frontend/views']], 'i18n' => ['class' => \rock\i18n\i18n::className(), 'pathsDicts' => ['ru' => ['@common/messages/ru/lang.php', '@common/messages/ru/validate.php', '@frontend/messages/ru/lang.php'], 'en' => ['@common/messages/en/lang.php', '@common/messages/en/validate.php', '@frontend/messages/en/lang.php']]], 'execute' => ['class' => \rock\execute\CacheExecute::className(), 'path' => '@common/runtime/execute'], 'markdown' => ['class' => 'rock\\markdown\\Markdown', 'handlerLinkByUsername' => [\apps\common\configs\MarkdownProperties::className(), 'handlerLinkByUsername']], 'mail' => ['From' => \rock\base\Alias::getAlias('@email')]];