/** * @param CM_Frontend_Render $render * @throws CM_Exception */ public function __construct(CM_Frontend_Render $render) { parent::__construct($render); $this->addVariables(); $file = new CM_File(DIR_PUBLIC . 'static/css/library/icon.less'); if ($file->exists()) { $this->add($file->read()); } foreach (array_reverse($render->getSite()->getModules()) as $moduleName) { foreach (array_reverse($render->getSite()->getThemes()) as $theme) { foreach (CM_Util::rglob('*.less', $render->getThemeDir(true, $theme, $moduleName) . 'css/') as $path) { $file = new CM_File($path); $this->add($file->read()); } } } $viewClasses = CM_View_Abstract::getClassChildren(true); foreach ($viewClasses as $viewClassName) { $validModule = in_array(CM_Util::getNamespace($viewClassName), $render->getSite()->getModules()); $validViewClass = $this->_isValidViewClass($viewClassName); if ($validModule && $validViewClass) { $asset = new CM_Asset_Css_View($this->_render, $viewClassName); $this->add($asset->_getContent()); } } }
function smarty_function_tag(array $params, Smarty_Internal_Template $template) { if (!isset($params['el'])) { trigger_error('Param `el` missing.'); } $name = $params['el']; unset($params['el']); $content = ''; if (isset($params['content'])) { $content = (string) $params['content']; unset($params['content']); } $attributes = $params; // http://www.w3.org/TR/html-markup/syntax.html#void-element $namesVoid = array('area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'); $html = '<' . $name; foreach ($attributes as $attributeName => $attributeValue) { if (isset($attributeValue)) { $html .= ' ' . $attributeName . '="' . CM_Util::htmlspecialchars($attributeValue) . '"'; } } if (in_array($name, $namesVoid)) { $html .= '>'; } else { $html .= '>' . $content . '</' . $name . '>'; } return $html; }
/** * @param string $elementName * @param string|null $content * @param array|null $attributes * @param array|null $dataAttributes * @return string * @throws CM_Exception_Invalid */ public function renderTag($elementName, $content = null, array $attributes = null, array $dataAttributes = null) { $elementName = (string) $elementName; if ('' === $elementName) { throw new CM_Exception_Invalid('Empty element name'); } $content = (string) $content; if (null === $attributes) { $attributes = []; } if (null === $dataAttributes) { $dataAttributes = []; } // http://www.w3.org/TR/html-markup/syntax.html#void-element $namesVoid = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']; $html = '<' . $elementName; foreach ($dataAttributes as $dataKey => $dataValue) { $attributes['data-' . $dataKey] = $dataValue; } foreach ($attributes as $attributeName => $attributeValue) { if (isset($attributeValue)) { $html .= ' ' . CM_Util::htmlspecialchars($attributeName) . '="' . CM_Util::htmlspecialchars($attributeValue) . '"'; } } if (in_array($elementName, $namesVoid)) { $html .= '>'; } else { $html .= '>' . $content . '</' . $elementName . '>'; } return $html; }
/** * @return CM_Elasticsearch_Type_Abstract[] */ public function getTypes() { $types = CM_Util::getClassChildren('CM_Elasticsearch_Type_Abstract'); return \Functional\map($types, function ($className) { return new $className($this->getRandomClient()); }); }
public function autoloadCommands() { $classes = CM_Util::getClassChildren('CM_Cli_Runnable_Abstract', false); foreach ($classes as $className) { $this->addRunnable($className); } }
/** * @param CM_Frontend_Render $render * @param string $className * @throws CM_Exception */ public function __construct(CM_Frontend_Render $render, $className) { parent::__construct($render); if (!preg_match('#^([^_]+)_([^_]+)_?(.*)$#', $className, $matches)) { throw new CM_Exception('Cannot detect all className parts from view\'s className', null, ['className' => $className]); } list($className, $namespace, $viewType, $viewName) = $matches; $viewPath = $viewType . '/'; if ($viewName) { $viewPath .= $viewName . '/'; } $relativePaths = array(); foreach ($render->getSite()->getThemes() as $theme) { $basePath = $render->getThemeDir(true, $theme, $namespace) . $viewPath; foreach (CM_Util::rglob('*.less', $basePath) as $path) { $relativePaths[] = preg_replace('#^' . $basePath . '#', '', $path); } } foreach (array_unique($relativePaths) as $path) { $prefix = '.' . $className; if ($path !== 'default.less' && strpos($path, '/') === false) { $prefix .= '.' . preg_replace('#.less$#', '', $path); } $file = $render->getLayoutFile($viewPath . $path, $namespace); $this->add($file->read(), $prefix); } }
/** * @param CM_Log_Handler_HandlerInterface $handler * @return CM_Log_Logger */ protected function _createLogger(CM_Log_Handler_HandlerInterface $handler) { $computerInfo = new CM_Log_Context_ComputerInfo(CM_Util::getFqdn(), phpversion()); $globalContext = new CM_Log_Context(); $globalContext->setComputerInfo($computerInfo); return new CM_Log_Logger($globalContext, $handler); }
public function iconRefresh() { /** @var CM_File[] $svgFileList */ $svgFileList = array(); foreach (CM_Bootloader::getInstance()->getModules() as $moduleName) { $iconPath = CM_Util::getModulePath($moduleName) . 'layout/default/resource/img/icon/'; foreach (glob($iconPath . '*.svg') as $svgPath) { $svgFile = new CM_File($svgPath); $svgFileList[strtolower($svgFile->getFileName())] = $svgFile; } } if (0 === count($svgFileList)) { throw new CM_Exception_Invalid('Cannot process `0` icons'); } $this->_getStreamOutput()->writeln('Processing ' . count($svgFileList) . ' unique icons...'); $dirWork = CM_File::createTmpDir(); $dirBuild = $dirWork->joinPath('/build'); foreach ($svgFileList as $fontFile) { $fontFile->copyToFile($dirWork->joinPath($fontFile->getFileName())); } CM_Util::exec('fontcustom', array('compile', $dirWork->getPathOnLocalFilesystem(), '--no-hash', '--autowidth', '--font-name=icon-webfont', '--output=' . $dirBuild->getPathOnLocalFilesystem())); $cssFile = $dirBuild->joinPath('/icon-webfont.css'); $less = preg_replace('/url\\("(?:.*?\\/)(.+?)(\\??#.+?)?"\\)/', 'url(urlFont("\\1") + "\\2")', $cssFile->read()); CM_File::create(DIR_PUBLIC . 'static/css/library/icon.less', $less); foreach (glob($dirBuild->joinPath('/icon-webfont.*')->getPathOnLocalFilesystem()) as $fontPath) { $fontFile = new CM_File($fontPath); $fontFile->rename(DIR_PUBLIC . 'static/font/' . $fontFile->getFileName()); } $dirWork->delete(true); $this->_getStreamOutput()->writeln('Created web-font and stylesheet.'); }
/** * @param string|null $email * @param int|null $size * @param string|null $default * @return string */ public function getUrl($email, $size = null, $default = null) { if (null !== $email) { $email = (string) $email; } if (null !== $size) { $size = (int) $size; } if (null !== $default) { $default = (string) $default; } if (null === $email && null !== $default) { return $default; } $url = 'https://secure.gravatar.com/avatar'; if (null !== $email) { $url .= '/' . md5(strtolower(trim($email))); } $params = array(); if (null !== $size) { $params['s'] = $size; } if (null !== $default) { $params['d'] = $default; } return CM_Util::link($url, $params); }
public function getHtml($zoneName, $zoneData, array $variables) { $zoneId = CM_Util::htmlspecialchars($zoneData['zoneId']); $variables = $this->_variableKeysToUnderscore($variables); $variables['key'] = $zoneData['accessKey']; $html = '<div id="epom-' . $zoneId . '" class="epom-ad" data-zone-name="' . $zoneName . '" data-variables="' . CM_Util::htmlspecialchars(json_encode($variables, JSON_FORCE_OBJECT)) . '"></div>'; return $html; }
/** * @param string $namespace */ private function _dbToFileSql($namespace) { $namespace = (string) $namespace; $tables = CM_Db_Db::exec("SHOW TABLES LIKE ?", array(strtolower($namespace) . '_%'))->fetchAllColumn(); sort($tables); $dump = CM_Db_Db::getDump($tables, true); CM_File::create(CM_Util::getModulePath($namespace) . '/resources/db/structure.sql', $dump); }
protected function _processItem($itemRaw) { $index = serialize($itemRaw); if (null === ($model = $this->_modelList[$index])) { throw new CM_Exception_Nonexistent('Model itemRaw: `' . CM_Util::var_line($itemRaw) . '` has no data'); } return $model; }
/** * @param int $id * @throws CM_Exception_Nonexistent */ public function __construct($id) { $this->_id = (int) $id; $this->_text = CM_Db_Db::select('cm_captcha', 'number', array('captcha_id' => $this->getId()))->fetchColumn(); if (!$this->_text) { throw new CM_Exception_Nonexistent('Invalid captcha id `' . $id . '`', CM_Exception::WARN); } $this->_fontPath = CM_Util::getModulePath('CM') . 'resources/font/comicsans.ttf'; }
/** * @param array $formattedRecord * @return array */ protected function _sanitizeRecord(array $formattedRecord) { array_walk_recursive($formattedRecord, function (&$value, $key) { if (is_string($value) && !mb_check_encoding($value, 'UTF-8')) { $value = CM_Util::sanitizeUtf($value); } }); return $formattedRecord; }
public function __construct(CM_Site_Abstract $site) { $content = ''; foreach (array_reverse($site->getModules()) as $moduleName) { $libraryPath = DIR_ROOT . CM_Bootloader::getInstance()->getModulePath($moduleName) . 'client-vendor/after-body/'; foreach (CM_Util::rglob('*.js', $libraryPath) as $path) { $content .= (new CM_File($path))->read() . ';' . PHP_EOL; } } $this->_content = $content; }
public function getHtml($zoneName, $zoneData, array $variables) { $src = (string) $zoneData['src']; $width = (string) $zoneData['width']; $height = (string) $zoneData['height']; $params = ['src' => $src, 'width' => $width, 'height' => $height, 'class' => 'advertisement-hasContent', 'data-variables' => json_encode($variables, JSON_FORCE_OBJECT), 'frameborder' => 0, 'scrolling' => 'no']; $params = Functional\map($params, function ($value, $key) { return $key . '="' . CM_Util::htmlspecialchars($value) . '"'; }); return '<iframe ' . join(' ', $params) . '></iframe>'; }
private function _setInitialVersion() { $app = CM_App::getInstance(); foreach (CM_App::getInstance()->getUpdateScriptPaths() as $namespace => $path) { $updateFiles = CM_Util::rglob('*.php', $path); $version = array_reduce($updateFiles, function ($initial, $path) { $filename = basename($path); return max($initial, (int) $filename); }, 0); $app->setVersion($version, $namespace); } }
/** * @param int $level * @param string $message * @param CM_Log_Context $context * @throws CM_Exception_Invalid */ public function __construct($level, $message, CM_Log_Context $context) { $level = (int) $level; $message = (string) $message; if (!CM_Log_Logger::hasLevel($level)) { throw new CM_Exception_Invalid('Log level does not exist.', null, ['level' => $level]); } $this->_level = $level; $this->_message = $message; $this->_context = $context; $this->_createdAt = CM_Util::createDateTimeWithMillis(); }
/** * @param string $verbName * @param CM_Model_User|int $actor * @param int $typeEmail */ public function __construct($verbName, $actor, $typeEmail) { parent::__construct($verbName, $actor); $typeEmail = (int) $typeEmail; try { $className = CM_Mail_Mailable::_getClassName($typeEmail); $this->_nameEmail = ucwords(CM_Util::uncamelize(str_replace('_', '', preg_replace('#\\A[^_]++_[^_]++_#', '', $className)), ' ')); } catch (CM_Class_Exception_TypeNotConfiguredException $exception) { CM_Service_Manager::getInstance()->getLogger()->warning('Unrecognized mail type when creating mail action', (new CM_Log_Context())->setException($exception)); $this->_nameEmail = (string) $typeEmail; } }
public function clear() { $this->_getStreamOutput()->writeln('Clearing cache…'); $classes = CM_Util::getClassChildren('CM_Cache_Storage_Abstract', false); foreach ($classes as $className) { $this->_getStreamOutput()->writeln(' ' . $className); /** @var CM_Cache_Storage_Abstract $cache */ $cache = new $className(); $cache->flush(); } $this->_getStreamOutput()->writeln('Cache cleared.'); }
public function load(CM_OutputStream_Interface $output) { $mongoClient = $this->getServiceManager()->getMongoDb(); foreach (CM_Util::getResourceFiles('mongo/collections.json') as $dump) { $collectionInfo = CM_Params::jsonDecode($dump->read()); foreach ($collectionInfo as $collection => $indexes) { $mongoClient->createCollection($collection); foreach ($indexes as $indexInfo) { $mongoClient->createIndex($collection, $indexInfo['key'], $indexInfo['options']); } } } }
/** * @param string $verbName * @param CM_Model_User|int $actor * @param int $typeEmail */ public function __construct($verbName, $actor, $typeEmail) { parent::__construct($verbName, $actor); $typeEmail = (int) $typeEmail; try { $className = CM_Mail::_getClassName($typeEmail); $this->_nameEmail = ucwords(CM_Util::uncamelize(str_replace('_', '', preg_replace('#\\A[^_]++_[^_]++_#', '', $className)), ' ')); } catch (CM_Class_Exception_TypeNotConfiguredException $exception) { $exception->setSeverity(CM_Exception::WARN); CM_Bootloader::getInstance()->getExceptionHandler()->handleException($exception); $this->_nameEmail = (string) $typeEmail; } }
/** * @param CM_Params $params * @param CM_Http_Response_View_Ajax $response * @throws CM_Exception_Invalid * @return array */ public function loadPage(CM_Params $params, CM_Http_Response_View_Ajax $response) { $path = $params->getString('path'); $currentLayoutClass = $params->getString('currentLayout'); $request = $this->_createGetRequestWithUrl($path); $responseFactory = new CM_Http_ResponseFactory($this->getServiceManager()); $count = 0; $fragments = []; do { $fragment = CM_Util::link($request->getPath(), $request->getQuery()); $fragments[] = $fragment; $url = $this->getRender()->getSite()->getUrlBase() . $fragment; if ($count++ > 10) { throw new CM_Exception_Invalid('Page redirect loop detected (' . implode(' -> ', $fragments) . ').'); } $responsePage = $responseFactory->getResponse($request); if (!$responsePage->getSite()->equals($this->getSite())) { $redirectExternalFragment = CM_Util::link($responsePage->getRequest()->getPath(), $responsePage->getRequest()->getQuery()); return array('redirectExternal' => $responsePage->getRender()->getUrl($redirectExternalFragment)); } $responseEmbed = new CM_Http_Response_Page_Embed($responsePage->getRequest(), $responsePage->getSite(), $this->getServiceManager()); $responseEmbed->process(); $request = $responseEmbed->getRequest(); if ($redirectUrl = $responseEmbed->getRedirectUrl()) { if (!$this->_isPageOnSameSite($redirectUrl)) { return array('redirectExternal' => $redirectUrl); } } } while ($redirectUrl); foreach ($responseEmbed->getCookies() as $name => $cookieParameters) { $response->setCookie($name, $cookieParameters['value'], $cookieParameters['expire'], $cookieParameters['path']); } $page = $responseEmbed->getPage(); $this->_setStringRepresentation(get_class($page)); $frontend = $responseEmbed->getRender()->getGlobalResponse(); $html = $responseEmbed->getContent(); $js = $frontend->getJs(); $autoId = $frontend->getTreeRoot()->getValue()->getAutoId(); $frontend->clear(); $layoutRendering = null; $layoutClass = $page->getLayout($this->getRender()->getEnvironment()); if ($layoutClass !== $currentLayoutClass) { $layout = new $layoutClass(); $layoutRendering = $this->_getComponentRendering($layout); } $title = $responseEmbed->getTitle(); $menuList = array_merge($this->getSite()->getMenus($this->getRender()->getEnvironment()), $responseEmbed->getRender()->getMenuList()); $menuEntryHashList = $this->_getMenuEntryHashList($menuList, get_class($page), $page->getParams()); $jsTracking = $responseEmbed->getRender()->getServiceManager()->getTrackings()->getJs(); return ['pageRendering' => ['js' => $js, 'html' => $html, 'autoId' => $autoId], 'layoutRendering' => $layoutRendering, 'title' => $title, 'url' => $url, 'menuEntryHashList' => $menuEntryHashList, 'jsTracking' => $jsTracking]; }
function smarty_function_locationFlag(array $params, Smarty_Internal_Template $template) { /** @var CM_Frontend_Render $render */ $render = $template->smarty->getTemplateVars('render'); /** @var CM_Model_Location $location */ $location = $params['location']; $html = ''; if ($abbreviation = $location->getAbbreviation(CM_Model_Location::LEVEL_COUNTRY)) { $flagUrl = $render->getUrlResource('layout', 'img/flags/' . strtolower($abbreviation) . '.png'); $name = $location->getName(CM_Model_Location::LEVEL_COUNTRY); $html .= '<img class="flag" src="' . $flagUrl . '" title="' . CM_Util::htmlspecialchars($name) . '" />'; } return $html; }
public function __construct(CM_Frontend_Render $render) { parent::__construct($render); $extensions = array('css', 'less'); foreach (array_reverse($render->getSite()->getModules()) as $moduleName) { $libraryPath = DIR_ROOT . CM_Bootloader::getInstance()->getModulePath($moduleName) . 'client-vendor/'; foreach ($extensions as $extension) { foreach (CM_Util::rglob('*.' . $extension, $libraryPath) as $path) { $file = new CM_File($path); $this->add($file->read()); } } } }
/** * @param ReflectionClass $reflection * @return null|string */ protected function _generatePageContent(ReflectionClass $reflection) { if ($reflection->isSubclassOf('CM_Page_Abstract')) { $parentClassName = $reflection->getParentClass()->getName(); $content = "{extends file=\$render->getLayoutPath('" . $this->_extractTemplateName($parentClassName) . "default.tpl'"; if ($reflection->isAbstract()) { $namespace = CM_Util::getNamespace($parentClassName); $content .= ", '" . $namespace . "'"; } $content .= ")}\n"; return $content; } return null; }
public function load(CM_OutputStream_Interface $output) { /** @var CM_Model_Language $language */ foreach (new CM_Paging_Language_All() as $language) { $path = 'translations/' . $language->getAbbreviation() . '.php'; foreach (CM_Util::getResourceFiles($path) as $translationsFile) { $translationsSetter = (require $translationsFile->getPath()); if (!$translationsSetter instanceof Closure) { throw new CM_Exception_Invalid('Invalid translation file. `' . $translationsFile->getPath() . '` must return callable'); } $translationsSetter($language); } } $this->_setLoaded(true); }
/** * @param string $key * @param mixed $value * @return mixed * @throws CM_Exception_Invalid * @throws CM_Model_Exception_Validation */ public function encodeField($key, $value) { $key = (string) $key; if ($this->hasField($key)) { $schemaField = $this->_schema[$key]; if (null !== $value) { $type = isset($schemaField['type']) ? $schemaField['type'] : null; if (null !== $type) { switch ($type) { case 'integer': case 'int': $value = (int) $value; break; case 'float': $value = (double) $value; break; case 'string': break; case 'boolean': case 'bool': $value = (bool) $value; break; case 'array': break; case 'DateTime': /** @var DateTime $value */ $value = $value->getTimestamp(); break; default: if (!(class_exists($type) && is_subclass_of($type, 'CM_Model_Abstract'))) { throw new CM_Model_Exception_Validation('Field `' . $key . '` is not a valid model'); } if (!$value instanceof $type) { throw new CM_Model_Exception_Validation('Value `' . CM_Util::var_line($value) . '` is not an instance of `' . $type . '`'); } /** @var CM_Model_Abstract $value */ $id = $value->getIdRaw(); if (count($id) == 1) { $value = $value->getId(); } else { $value = CM_Params::jsonEncode($id); } } } } } return $value; }
/** * @param string[]|null $variables * @throws CM_Exception_Invalid */ public function setVariables(array $variables = null) { $previousVariables = $this->getVariables(); $variables = (array) $variables; $variables = array_values($variables); sort($variables); if ($previousVariables !== $variables) { $variablesEncoded = CM_Params::jsonEncode($variables); $this->_set('variables', $variablesEncoded); $this->_increaseUpdateCount(); if ($this->_getUpdateCount() > self::MAX_UPDATE_COUNT) { $message = ['Variables for languageKey `' . $this->getName() . '` have been updated over ' . self::MAX_UPDATE_COUNT . ' times since release.', 'Previous variables: `' . CM_Util::var_line($previousVariables) . '`', 'Current variables: `' . CM_Util::var_line($variables) . '`']; throw new CM_Exception_Invalid(join(PHP_EOL, $message)); } } }
public function getQuery() { if ($this->_bodyQuery === null) { if ($this->_bodyEncoding == self::ENCODING_JSON) { $body = CM_Util::sanitizeUtf($this->getBody()); if (!is_array($this->_bodyQuery = json_decode($body, true))) { throw new CM_Exception_Invalid('Cannot extract query from body', CM_Exception::WARN, ['body' => $body]); } } elseif ($this->_bodyEncoding == self::ENCODING_FORM) { parse_str($this->getBody(), $this->_bodyQuery); } else { $this->_bodyQuery = array(); } } return array_merge($this->_query, $this->_bodyQuery); }