/** * @param $name * @return mixed */ public static function locateConfigFile($name) { if (!isset(self::$configFileCache[$name])) { $pathsToCheck = [PIMCORE_WEBSITE_PATH . "/config", PIMCORE_CONFIGURATION_DIRECTORY]; $file = PIMCORE_CONFIGURATION_DIRECTORY . "/" . $name; // check for environment configuration $env = getenv("PIMCORE_ENVIRONMENT"); if ($env) { $fileExt = File::getFileExtension($name); $pureName = str_replace("." . $fileExt, "", $name); foreach ($pathsToCheck as $path) { $tmpFile = $path . "/" . $pureName . "." . $env . "." . $fileExt; if (file_exists($tmpFile)) { $file = $tmpFile; break; } } } foreach ($pathsToCheck as $path) { $tmpFile = $path . "/" . $name; if (file_exists($tmpFile)) { $file = $tmpFile; break; } } self::$configFileCache[$name] = $file; } return self::$configFileCache[$name]; }
/** * @param null $options * @return bool|void * @throws \Exception * @throws \Zend_Http_Client_Exception */ public function send($options = null) { $sourceFile = $this->getSourceFile(); $destinationFile = $this->getDestinationFile(); if (!$sourceFile) { throw new \Exception("No sourceFile provided."); } if (!$destinationFile) { throw new \Exception("No destinationFile provided."); } if (is_array($options)) { if ($options['overwrite'] == false && file_exists($destinationFile)) { throw new \Exception("Destination file : '" . $destinationFile . "' already exists."); } } if (!$this->getHttpClient()) { $httpClient = \Pimcore\Tool::getHttpClient(null, ['timeout' => 3600 * 60]); } else { $httpClient = $this->getHttpClient(); } $httpClient->setUri($this->getSourceFile()); $response = $httpClient->request(); if ($response->isSuccessful()) { $data = $response->getBody(); File::mkdir(dirname($destinationFile)); $result = File::put($destinationFile, $data); if ($result === false) { throw new \Exception("Couldn't write destination file:" . $destinationFile); } } else { throw new \Exception("Couldn't download file:" . $sourceFile); } return true; }
public function installConfigFile() { if (!is_file($this->configFile)) { $settings = array("accordion" => ["configElements" => [["type" => "select", "name" => "type", "title" => "Type", "values" => ["panel-default" => "Default", "panel-danger" => "Dangers"], "default" => "panel-default"], ["type" => "additionalClasses", "values" => []]]], "columns" => ["configElements" => [["type" => "select", "name" => "type", "title" => "Columns", "values" => ["column_12" => "1 Column", "column_4_8" => "2 Columns (33:66)", "column_8_4" => "2 Columns (66:33)", "column_3_9" => "2 Columns (25:75)", "column_9_3" => "2 Columns (75:25)", "column_6_6" => "2 Columns (50:50)", "column_4_4_4" => "3 Columns (33:33:33)"], "default" => "column_12"], ["type" => "checkbox", "name" => "equalHeight", "title" => "Equal heights?", "reload" => FALSE]]], "slideColumns" => ["configElements" => [["type" => "select", "name" => "slidesPerView", "title" => "Slides per View", "values" => ["2" => "2 Columns", "3" => "3 Columns", "4" => "4 Columns", "6" => "6 Columns"], "default" => "4"], ["type" => "checkbox", "name" => "equalHeight", "title" => "Equal heights?", "reload" => FALSE]], "columnClasses" => ["2" => "col-xs-12 col-sm-6"], "breakpoints" => []], "content" => ["configElements" => [["type" => "additionalClasses", "values" => []]]], "download" => ["configElements" => [["type" => "additionalClasses", "values" => []]]], "gallery" => ["configElements" => [["type" => "additionalClasses", "values" => []]]], "headline" => ["configElements" => [["type" => "select", "name" => "headlineType", "title" => "Headline Size", "values" => ["h1" => "Headline 1", "h2" => "Headline 2", "h3" => "Headline 3", "h4" => "Headline 4", "h5" => "Headline 5", "h6" => "Headline 6"], "default" => "h3"], ["type" => "additionalClasses", "values" => []]]], "image" => ["configElements" => [["type" => "additionalClasses", "values" => []]]], "linklist" => ["configElements" => [["type" => "additionalClasses", "values" => []]]], "parallaxContainer" => ["configElements" => [["type" => "select", "name" => "type", "title" => "Type", "values" => ["image" => "Image", "snippet" => "Snippet"], "default" => "image"], ["type" => "additionalClasses", "values" => ["window-full-height" => "min. window height"]]]], "separator" => ["configElements" => [["type" => "select", "name" => "space", "title" => "Space before & after separator", "values" => ["default" => "Default", "medium" => "Medium", "large" => "Large"], "default" => "default"], ["type" => "additionalClasses", "values" => []]]], "teaser" => ["configElements" => [["type" => "select", "name" => "type", "title" => "Type", "values" => ["direct" => "Direct", "snippet" => "Snippet"], "default" => "direct"], ["type" => "select", "name" => "layout", "title" => "Layout", "values" => ["default" => "Default"], "default" => "default", "conditions" => [["type" => "direct"]]], ["type" => "checkbox", "name" => "useLightBox", "title" => "use Lightbox?"], ["type" => "additionalClasses", "values" => []]]], "video" => ["configElements" => [["type" => "additionalClasses", "values" => []], ["type" => "checkbox", "name" => "autoplay", "title" => "Autoplay?"]]], "googleMap" => ["configElements" => [], "mapOptions" => ["streetViewControl" => TRUE, "mapTypeControl" => FALSE, "panControl" => FALSE, "scrollwheel" => FALSE], "mapStyleUrl" => FALSE, "markerIcon" => FALSE], "ckeditor" => ["styles" => [['name' => 'test', 'element' => 'p', 'attributes' => ['class' => 'h5']]]], "disallowedSubAreas" => ["accordion" => ["accordion", "container", "slideColumns"], "columns" => ["container"], "slideColumns" => ["slideColumns", "accordion", "container", "columns", "anchor"], "container" => ["container"], "image" => ["parallaxContainer"], "snippet" => ["parallaxContainer"]], "disallowedContentSnippetAreas" => ["parallaxContainer", "teaser", "container", "snippet"], "areaBlockConfiguration" => ["toolbar" => ["title" => "Inhaltsbausteine", "width" => 200, "x" => 10, "y" => 125, "buttonWidth" => 200], "groups" => FALSE]); \Pimcore\File::putPhpFile($this->configFile, to_php_data_file_format($settings)); } }
/** * @param array $config */ public function config($config = []) { $settings = null; // check for an initial configuration template // used eg. by the demo installer $configTemplatePath = PIMCORE_CONFIGURATION_DIRECTORY . "/system.template.php"; if (file_exists($configTemplatePath)) { try { $configTemplate = new \Zend_Config(include $configTemplatePath); if ($configTemplate->general) { // check if the template contains a valid configuration $settings = $configTemplate->toArray(); // unset database configuration unset($settings["database"]["params"]["host"]); unset($settings["database"]["params"]["port"]); } } catch (\Exception $e) { } } // set default configuration if no template is present if (!$settings) { // write configuration file $settings = ["general" => ["timezone" => "Europe/Berlin", "language" => "en", "validLanguages" => "en", "debug" => "1", "debugloglevel" => "debug", "custom_php_logfile" => "1", "extjs6" => "1"], "database" => ["adapter" => "Mysqli", "params" => ["username" => "root", "password" => "", "dbname" => ""]], "documents" => ["versions" => ["steps" => "10"], "default_controller" => "default", "default_action" => "default", "error_pages" => ["default" => "/"], "createredirectwhenmoved" => "", "allowtrailingslash" => "no", "generatepreview" => "1"], "objects" => ["versions" => ["steps" => "10"]], "assets" => ["versions" => ["steps" => "10"]], "services" => [], "cache" => ["excludeCookie" => ""], "httpclient" => ["adapter" => "Zend_Http_Client_Adapter_Socket"]]; } $settings = array_replace_recursive($settings, $config); // create initial /website/var folder structure // @TODO: should use values out of startup.php (Constants) $varFolders = ["areas", "assets", "backup", "cache", "classes", "config", "email", "log", "plugins", "recyclebin", "search", "system", "tmp", "versions", "webdav"]; foreach ($varFolders as $folder) { \Pimcore\File::mkdir(PIMCORE_WEBSITE_VAR . "/" . $folder); } $configFile = \Pimcore\Config::locateConfigFile("system.php"); File::putPhpFile($configFile, to_php_data_file_format($settings)); }
/** * @param $file * @param null $filename * @return mixed|string * @throws \Exception */ public static function detect($file, $filename = null) { if (!file_exists($file)) { throw new \Exception("File " . $file . " doesn't exist"); } if (!$filename) { $filename = basename($file); } // check for an extension mapping first if ($filename) { $extension = \Pimcore\File::getFileExtension($filename); if (array_key_exists($extension, self::$extensionMapping)) { return self::$extensionMapping[$extension]; } } // check with fileinfo, if there's no extension mapping $finfo = finfo_open(FILEINFO_MIME); $type = finfo_file($finfo, $file); finfo_close($finfo); if ($type !== false && !empty($type)) { if (strstr($type, ';')) { $type = substr($type, 0, strpos($type, ';')); } return $type; } // return default mime-type if we're unable to detect it return "application/octet-stream"; }
/** * @param $body * @return mixed */ public static function processHtml($body) { $processedPaths = array(); preg_match_all("@\\<link[^>]*(rel=\"stylesheet/less\")[^>]*\\>@msUi", $body, $matches); if (is_array($matches)) { foreach ($matches[0] as $tag) { preg_match("/href=\"([^\"]+)*\"/", $tag, $href); if (array_key_exists(1, $href) && !empty($href[1])) { $source = $href[1]; $source = preg_replace("/\\?_dc=[\\d]+/", "", $source); if (is_file(PIMCORE_ASSET_DIRECTORY . $source)) { $path = PIMCORE_ASSET_DIRECTORY . $source; } else { if (is_file(PIMCORE_DOCUMENT_ROOT . $source)) { $path = PIMCORE_DOCUMENT_ROOT . $source; } } // add the same file only one time if (in_array($path, $processedPaths)) { continue; } $newFile = PIMCORE_TEMPORARY_DIRECTORY . "/less___" . File::getValidFilename(str_replace(".less", "", $source)) . "-" . filemtime($path) . ".css"; if (!is_file($newFile)) { $compiledContent = self::compile($path, $source); File::put($newFile, $compiledContent); } $body = str_replace($tag, str_replace("stylesheet/less", "stylesheet", str_replace($source, str_replace(PIMCORE_DOCUMENT_ROOT, "", $newFile), $tag)), $body); } } } return $body; }
/** * @static * @return string */ public static function getWorkingDir() { $dir = PIMCORE_CONFIGURATION_DIRECTORY . "/videopipelines"; if (!is_dir($dir)) { \Pimcore\File::mkdir($dir); } return $dir; }
public function saveAction() { $this->checkPermission("system_settings"); $values = \Zend_Json::decode($this->getParam("data")); $configFile = \Pimcore\Config::locateConfigFile("reports.php"); File::put($configFile, to_php_data_file_format($values)); $this->_helper->json(array("success" => true)); }
/** * calls prent _write and and writes temp log file * * @param array $event Event data * @return void */ protected function _write($event) { if (!is_file($this->_tempfile)) { @\Pimcore\File::put($this->_tempfile, "... continued ...\r\n"); $writerFile = new \Zend_Log_Writer_Stream($this->_tempfile); $this->_tempLogger = new \Zend_Log($writerFile); } $this->_tempLogger->log($event['message'], $event['priority']); parent::_write($event); }
/** * @param $stylesheetContent * @return mixed */ public static function getMinimizedStylesheetPath($stylesheetContent) { $stylesheetPath = PIMCORE_TEMPORARY_DIRECTORY . "/minified_css_core_" . md5($stylesheetContent) . ".css"; if (!is_file($stylesheetPath)) { //$stylesheetContent = Minify_CSS::minify($stylesheetContent); // temp. disabled until we have a better library - just combine for now // put minified contents into one single file File::put($stylesheetPath, $stylesheetContent); } return preg_replace("@^" . preg_quote(PIMCORE_DOCUMENT_ROOT, "@") . "@", "", $stylesheetPath); }
/** * @param string $name * @return $this|void * @throws DAV\Exception\Forbidden * @throws \Exception */ function setName($name) { if ($this->asset->isAllowed("rename")) { $user = AdminTool::getCurrentUser(); $this->asset->setUserModification($user->getId()); $this->asset->setFilename(\Pimcore\File::getValidFilename($name)); $this->asset->save(); } else { throw new DAV\Exception\Forbidden(); } return $this; }
/** * @param $path * @return string */ protected function preparePath($path) { if (!stream_is_local($path)) { // gs is only able to deal with local files // if your're using custom stream wrappers this wouldn't work, so we create a temp. local copy $tmpFilePath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/imagick-tmp-" . uniqid() . "." . File::getFileExtension($path); copy($path, $tmpFilePath); $path = $tmpFilePath; $this->tmpFiles[] = $path; } return $path; }
/** * @param $log */ public static function saveDeleteLog($log) { // cleanup old entries $tmpLog = array(); foreach ($log as $path => $data) { if ($data["timestamp"] > time() - 30) { // remove 30 seconds old entries $tmpLog[$path] = $data; } } \Pimcore\File::put(Asset\WebDAV\Service::getDeleteLogFile(), serialize($tmpLog)); }
/** * */ public function dispatchLoopShutdown() { if (!Tool::isHtmlResponse($this->getResponse())) { return; } if ($this->enabled) { include_once "simple_html_dom.php"; $body = $this->getResponse()->getBody(); $html = str_get_html($body); if ($html) { $styles = $html->find("link[rel=stylesheet], style[type=text/css]"); $stylesheetContent = ""; foreach ($styles as $style) { if ($style->tag == "style") { $stylesheetContent .= $style->innertext; } else { $source = $style->href; $path = ""; if (is_file(PIMCORE_ASSET_DIRECTORY . $source)) { $path = PIMCORE_ASSET_DIRECTORY . $source; } else { if (is_file(PIMCORE_DOCUMENT_ROOT . $source)) { $path = PIMCORE_DOCUMENT_ROOT . $source; } } if (!empty($path) && is_file("file://" . $path)) { $content = file_get_contents($path); $content = $this->correctReferences($source, $content); if ($style->media) { $content = "@media " . $style->media . " {" . $content . "}"; } $stylesheetContent .= $content; $style->outertext = ""; } } } if (strlen($stylesheetContent) > 1) { $stylesheetPath = PIMCORE_TEMPORARY_DIRECTORY . "/minified_css_" . md5($stylesheetContent) . ".css"; if (!is_file($stylesheetPath)) { // put minified contents into one single file File::put($stylesheetPath, $stylesheetContent); } $head = $html->find("head", 0); $head->innertext = $head->innertext . "\n" . '<link rel="stylesheet" type="text/css" href="' . str_replace(PIMCORE_DOCUMENT_ROOT, "", $stylesheetPath) . '" />' . "\n"; } $body = $html->save(); $html->clear(); unset($html); $this->getResponse()->setBody($body); } } }
/** * @param string $data * @param string $filename */ public function __construct($data, $filename = null) { if (!is_dir(PIMCORE_LOG_FILEOBJECT_DIRECTORY)) { File::mkdir(PIMCORE_LOG_FILEOBJECT_DIRECTORY); } $this->data = $data; $this->filename = $filename; if (empty($this->filename)) { $folderpath = PIMCORE_LOG_FILEOBJECT_DIRECTORY . strftime('/%Y/%m/%d'); if (!is_dir($folderpath)) { mkdir($folderpath, 0775, true); } $this->filename = $folderpath . "/" . uniqid("fileobject_", true); } File::put($this->filename, $this->data); }
/** * @param $imagePath * @param array $options * @return $this|self */ public function load($imagePath, $options = []) { $this->path = $imagePath; if (!($this->resource = @imagecreatefromstring(file_get_contents($this->path)))) { return false; } // set dimensions list($width, $height) = getimagesize($this->path); $this->setWidth($width); $this->setHeight($height); if (in_array(\Pimcore\File::getFileExtension($imagePath), ["png", "gif"])) { // in GD only gif and PNG can have an alphachannel $this->setIsAlphaPossible(true); } $this->setModified(false); return $this; }
/** * @param $name * @param $message */ public static function log($name, $message) { $log = PIMCORE_LOG_DIRECTORY . "/{$name}.log"; if (!is_file($log)) { if (is_writable(dirname($log))) { File::put($log, "AUTOCREATE\n"); } } if (is_writable($log)) { // check for big logfile, empty it if it's bigger than about 200M if (filesize($log) > 200000000) { File::put($log, ""); } $f = fopen($log, "a+"); fwrite($f, \Zend_Date::now()->getIso() . " : " . $message . "\n"); fclose($f); } }
/** * Moves a file/directory * * @param string $sourcePath * @param string $destinationPath * @return void */ public function move($sourcePath, $destinationPath) { $nameParts = explode("/", $sourcePath); $nameParts[count($nameParts) - 1] = File::getValidFilename($nameParts[count($nameParts) - 1]); $sourcePath = implode("/", $nameParts); $nameParts = explode("/", $destinationPath); $nameParts[count($nameParts) - 1] = File::getValidFilename($nameParts[count($nameParts) - 1]); $destinationPath = implode("/", $nameParts); try { if (dirname($sourcePath) == dirname($destinationPath)) { $asset = null; if ($asset = Asset::getByPath("/" . $destinationPath)) { // If we got here, this means the destination exists, and needs to be overwritten $sourceAsset = Asset::getByPath("/" . $sourcePath); $asset->setData($sourceAsset->getData()); $sourceAsset->delete(); } // see: Asset\WebDAV\File::delete() why this is necessary $log = Asset\WebDAV\Service::getDeleteLog(); if (!$asset && array_key_exists("/" . $destinationPath, $log)) { $asset = \Pimcore\Tool\Serialize::unserialize($log["/" . $destinationPath]["data"]); if ($asset) { $sourceAsset = Asset::getByPath("/" . $sourcePath); $asset->setData($sourceAsset->getData()); $sourceAsset->delete(); } } if (!$asset) { $asset = Asset::getByPath("/" . $sourcePath); } $asset->setFilename(basename($destinationPath)); } else { $asset = Asset::getByPath("/" . $sourcePath); $parent = Asset::getByPath("/" . dirname($destinationPath)); $asset->setPath($parent->getFullPath() . "/"); $asset->setParentId($parent->getId()); } $user = \Pimcore\Tool\Admin::getCurrentUser(); $asset->setUserModification($user->getId()); $asset->save(); } catch (\Exception $e) { \Logger::error($e); } }
/** * @param $name * @param $message */ public static function log($name, $message) { $log = PIMCORE_LOG_DIRECTORY . "/{$name}.log"; if (!is_file($log)) { if (is_writable(dirname($log))) { File::put($log, "AUTOCREATE\n"); } } if (is_writable($log)) { // check for big logfile, empty it if it's bigger than about 200M if (filesize($log) > 200000000) { File::put($log, ""); } $date = new \DateTime("now"); $f = fopen($log, "a+"); fwrite($f, $date->format(\DateTime::ISO8601) . " : " . $message . "\n"); fclose($f); } }
protected function execute(InputInterface $input, OutputInterface $output) { $source = "http://unicode.org/repos/cldr/trunk/common/supplemental/supplementalData.xml"; $data = file_get_contents($source); $xml = simplexml_load_string($data, null, LIBXML_NOCDATA); $languageRawData = []; foreach ($xml->territoryInfo->territory as $territory) { foreach ($territory->languagePopulation as $language) { $languageCode = (string) $language["type"]; if (\Zend_Locale::isLocale($languageCode)) { $populationAbsolute = $territory["population"] * $language["populationPercent"] / 100; if (!isset($languageRawData[$languageCode])) { $languageRawData[$languageCode] = []; } if (\Zend_Locale::isLocale($languageCode . "_" . $territory["type"], true)) { $languageRawData[$languageCode][] = ["country" => (string) $territory["type"], "population" => $populationAbsolute]; } } } } $finalData = []; foreach ($languageRawData as $languageCode => $rawLanguage) { usort($rawLanguage, function ($a, $b) { if ($a["population"] == $b["population"]) { return 0; } return $a["population"] > $b["population"] ? -1 : 1; }); $finalData[$languageCode] = []; foreach ($rawLanguage as $territory) { $finalData[$languageCode][] = $territory["country"]; } } $contents = to_php_data_file_format($finalData); $dataFile = PIMCORE_PATH . "/config/data/cldr-language-territory-mapping.php"; File::putPhpFile($dataFile, $contents); $this->output->writeln("Updated mappings in " . $dataFile); }
/** * loads the image by the specified path * * @param $imagePath * @param array $options * @return ImageMagick */ public function load($imagePath, $options = []) { // support image URLs if (preg_match("@^https?://@", $imagePath)) { $tmpFilename = "imagick_auto_download_" . md5($imagePath) . "." . File::getFileExtension($imagePath); $tmpFilePath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/" . $tmpFilename; $this->tmpFiles[] = $tmpFilePath; File::put($tmpFilePath, \Pimcore\Tool::getHttpData($imagePath)); $imagePath = $tmpFilePath; } if (!stream_is_local($imagePath)) { // imagick is only able to deal with local files // if your're using custom stream wrappers this wouldn't work, so we create a temp. local copy $tmpFilePath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/imagick-tmp-" . uniqid() . "." . File::getFileExtension($imagePath); copy($imagePath, $tmpFilePath); $imagePath = $tmpFilePath; $this->tmpFiles[] = $imagePath; } $this->imagePath = $imagePath; $this->initResource(); $this->setModified(false); return $this; }
/** * @param array $config */ public function config($config = array()) { $settings = null; // check for an initial configuration template // used eg. by the demo installer $configTemplatePath = PIMCORE_CONFIGURATION_DIRECTORY . "/system.xml.template"; if (file_exists($configTemplatePath)) { try { $configTemplate = new \Zend_Config_Xml($configTemplatePath); if ($configTemplate->general) { // check if the template contains a valid configuration $settings = $configTemplate->toArray(); // unset database configuration unset($settings["database"]["params"]["host"]); unset($settings["database"]["params"]["port"]); } } catch (\Exception $e) { } } // set default configuration if no template is present if (!$settings) { // write configuration file $settings = array("general" => array("timezone" => "Europe/Berlin", "language" => "en", "validLanguages" => "en", "debug" => "1", "debugloglevel" => "debug", "custom_php_logfile" => "1", "extjs6" => "1"), "database" => array("adapter" => "Mysqli", "params" => array("username" => "root", "password" => "", "dbname" => "")), "documents" => array("versions" => array("steps" => "10"), "default_controller" => "default", "default_action" => "default", "error_pages" => array("default" => "/"), "createredirectwhenmoved" => "", "allowtrailingslash" => "no", "allowcapitals" => "no", "generatepreview" => "1"), "objects" => array("versions" => array("steps" => "10")), "assets" => array("versions" => array("steps" => "10")), "services" => array(), "cache" => array("excludeCookie" => ""), "httpclient" => array("adapter" => "Zend_Http_Client_Adapter_Socket")); } $settings = array_replace_recursive($settings, $config); // convert all special characters to their entities so the xml writer can put it into the file $settings = array_htmlspecialchars($settings); // create initial /website/var folder structure // @TODO: should use values out of startup.php (Constants) $varFolders = array("areas", "assets", "backup", "cache", "classes", "config", "email", "log", "plugins", "recyclebin", "search", "system", "tmp", "versions", "webdav"); foreach ($varFolders as $folder) { \Pimcore\File::mkdir(PIMCORE_WEBSITE_VAR . "/" . $folder); } $config = new \Zend_Config($settings, true); $writer = new \Zend_Config_Writer_Xml(array("config" => $config, "filename" => PIMCORE_CONFIGURATION_SYSTEM)); $writer->write(); }
/** * @param array $options * @return array */ public function init($options = array()) { $this->setOptions($options); // create backup directory if not exists if (!is_dir(PIMCORE_BACKUP_DIRECTORY)) { if (!\Pimcore\File::mkdir(PIMCORE_BACKUP_DIRECTORY)) { \Logger::err("Directory " . PIMCORE_BACKUP_DIRECTORY . " does not exists and cannot be created."); exit; } } $errors = array(); $this->setFileAmount(0); // cleanup old backups if (is_file(PIMCORE_SYSTEM_TEMP_DIRECTORY . "/backup-dump.sql")) { unlink(PIMCORE_SYSTEM_TEMP_DIRECTORY . "/backup-dump.sql"); } // get steps $steps = array(); // get available tables $db = Db::get(); $tables = $this->getTables(); $steps[] = array("mysql-tables", $this->options['mysql-tables']); // tables foreach ($tables as $table) { $name = current($table); $type = next($table); if ($type != "VIEW") { $steps[] = array("mysql", array("name" => $name, "type" => $type)); } } // views foreach ($tables as $table) { reset($table); $name = current($table); $type = next($table); if ($type == "VIEW") { $steps[] = array("mysql", array("name" => $name, "type" => $type)); } } $steps[] = array("mysql-complete", null); if (!$options['only-mysql-related-tasks']) { // check files $currentFileCount = 0; $currentFileSize = 0; $currentStepFiles = array(); // check permissions $filesIn = rscandir(PIMCORE_DOCUMENT_ROOT . "/"); clearstatcache(); foreach ($filesIn as $fileIn) { if (!is_readable($fileIn)) { $errors[] = $fileIn . " is not readable."; } if ($currentFileCount > 300 || $currentFileSize > 20000000) { $currentFileCount = 0; $currentFileSize = 0; if (!empty($currentStepFiles)) { $filesToBackup[] = $currentStepFiles; } $currentStepFiles = array(); } if (file_exists($fileIn)) { $currentFileSize += filesize($fileIn); $currentFileCount++; $currentStepFiles[] = $fileIn; } } if (!empty($currentStepFiles)) { $filesToBackup[] = $currentStepFiles; } $this->setFilesToBackup($filesToBackup); $fileSteps = count($filesToBackup); for ($i = 0; $i < $fileSteps; $i++) { $steps[] = array("files", array("step" => $i)); } $steps[] = array("complete", null); } if (!empty($errors)) { $steps = null; } return array("steps" => $steps, "errors" => $errors); }
protected function writeLogFile($username, $error) { $logfile = PIMCORE_LOG_DIRECTORY . "/loginerror.log"; $data = $this->readLogFile(); $remoteHost = Tool::getAnonymizedClientIp(); $data[] = array(time(), $remoteHost, $username); $lines = array(); foreach ($data as $item) { $lines[] = implode(",", $item); } // only save 2000 entries $maxEntries = 2000; if (count($lines) > $maxEntries) { $lines = array_splice($lines, $maxEntries * -1); } File::put($logfile, implode("\n", $lines)); }
/** * @param null $imagePath * @return bool */ public function isVectorGraphic($imagePath = null) { if ($imagePath) { // use file-extension if filename is provided return in_array(File::getFileExtension($imagePath), ["svg", "svgz", "eps", "pdf", "ps"]); } else { try { $type = $this->resource->getimageformat(); $vectorTypes = array("EPT", "EPDF", "EPI", "EPS", "EPS2", "EPS3", "EPSF", "EPSI", "EPT", "PDF", "PFA", "PFB", "PFM", "PS", "PS2", "PS3", "SVG", "SVGZ", "MVG"); if (in_array(strtoupper($type), $vectorTypes)) { return true; } } catch (\Exception $e) { \Logger::err($e); } } return false; }
/** * @param $asset * @param Config $config * @param null $fileSystemPath * @param bool $deferred deferred means that the image will be generated on-the-fly (details see below) * @return mixed|string */ public static function process($asset, Config $config, $fileSystemPath = null, $deferred = false) { $format = strtolower($config->getFormat()); $contentOptimizedFormat = false; if (!$fileSystemPath && $asset instanceof Asset) { $fileSystemPath = $asset->getFileSystemPath(); } if ($asset instanceof Asset) { $id = $asset->getId(); } else { $id = "dyn~" . crc32($fileSystemPath); } if (!file_exists($fileSystemPath)) { return "/pimcore/static/img/filetype-not-supported.png"; } $modificationDate = filemtime($fileSystemPath); $fileExt = File::getFileExtension(basename($fileSystemPath)); // simple detection for source type if SOURCE is selected if ($format == "source" || empty($format)) { $format = self::getAllowedFormat($fileExt, array("jpeg", "gif", "png"), "png"); $contentOptimizedFormat = true; // format can change depending of the content (alpha-channel, ...) } if ($format == "print") { $format = self::getAllowedFormat($fileExt, array("svg", "jpeg", "png", "tiff"), "png"); if (($format == "tiff" || $format == "svg") && \Pimcore\Tool::isFrontentRequestByAdmin()) { // return a webformat in admin -> tiff cannot be displayed in browser $format = "png"; } else { if ($format == "tiff") { $transformations = $config->getItems(); if (is_array($transformations) && count($transformations) > 0) { foreach ($transformations as $transformation) { if (!empty($transformation)) { if ($transformation["method"] == "tifforiginal") { return str_replace(PIMCORE_DOCUMENT_ROOT, "", $fileSystemPath); } } } } } else { if ($format == "svg") { return str_replace(PIMCORE_DOCUMENT_ROOT, "", $fileSystemPath); } } } } $thumbDir = $asset->getImageThumbnailSavePath() . "/thumb__" . $config->getName(); $filename = preg_replace("/\\." . preg_quote(File::getFileExtension($asset->getFilename())) . "/", "", $asset->getFilename()); // add custom suffix if available if ($config->getFilenameSuffix()) { $filename .= "~-~" . $config->getFilenameSuffix(); } // add high-resolution modifier suffix to the filename if ($config->getHighResolution() > 1) { $filename .= "@" . $config->getHighResolution() . "x"; } $filename .= "." . $format; $fsPath = $thumbDir . "/" . $filename; if (!is_dir(dirname($fsPath))) { File::mkdir(dirname($fsPath)); } $path = str_replace(PIMCORE_DOCUMENT_ROOT, "", $fsPath); // check for existing and still valid thumbnail if (is_file($fsPath) and filemtime($fsPath) >= $modificationDate) { return $path; } // deferred means that the image will be generated on-the-fly (when requested by the browser) // the configuration is saved for later use in Pimcore\Controller\Plugin\Thumbnail::routeStartup() // so that it can be used also with dynamic configurations if ($deferred) { $configId = "thumb_" . $id . "__" . md5($path); TmpStore::add($configId, $config, "thumbnail_deferred"); return $path; } // transform image $image = Asset\Image::getImageTransformInstance(); if (!$image->load($fileSystemPath)) { return "/pimcore/static/img/filetype-not-supported.png"; } $image->setUseContentOptimizedFormat($contentOptimizedFormat); $startTime = StopWatch::microtime_float(); $transformations = $config->getItems(); // check if the original image has an orientation exif flag // if so add a transformation at the beginning that rotates and/or mirrors the image if (function_exists("exif_read_data")) { $exif = @exif_read_data($fileSystemPath); if (is_array($exif)) { if (array_key_exists("Orientation", $exif)) { $orientation = intval($exif["Orientation"]); if ($orientation > 1) { $angleMappings = [2 => 180, 3 => 180, 4 => 180, 5 => 90, 6 => 90, 7 => 90, 8 => 270]; if (array_key_exists($orientation, $angleMappings)) { array_unshift($transformations, ["method" => "rotate", "arguments" => ["angle" => $angleMappings[$orientation]]]); } // values that have to be mirrored, this is not very common, but should be covered anyway $mirrorMappings = [2 => "vertical", 4 => "horizontal", 5 => "vertical", 7 => "horizontal"]; if (array_key_exists($orientation, $mirrorMappings)) { array_unshift($transformations, ["method" => "mirror", "arguments" => ["mode" => $mirrorMappings[$orientation]]]); } } } } } if (is_array($transformations) && count($transformations) > 0) { foreach ($transformations as $transformation) { if (!empty($transformation)) { $arguments = array(); $mapping = self::$argumentMapping[$transformation["method"]]; if (is_array($transformation["arguments"])) { foreach ($transformation["arguments"] as $key => $value) { $position = array_search($key, $mapping); if ($position !== false) { // high res calculations if enabled if (!in_array($transformation["method"], ["cropPercent"]) && in_array($key, array("width", "height", "x", "y"))) { if ($config->getHighResolution() && $config->getHighResolution() > 1) { $value *= $config->getHighResolution(); } } $arguments[$position] = $value; } } } ksort($arguments); call_user_func_array(array($image, $transformation["method"]), $arguments); } } } $image->save($fsPath, $format, $config->getQuality()); if ($contentOptimizedFormat) { $tmpStoreKey = str_replace(PIMCORE_TEMPORARY_DIRECTORY . "/", "", $fsPath); TmpStore::add($tmpStoreKey, "-", "image-optimize-queue"); } clearstatcache(); \Logger::debug("Thumbnail " . $path . " generated in " . (StopWatch::microtime_float() - $startTime) . " seconds"); // set proper permissions @chmod($fsPath, File::getDefaultMode()); // quick bugfix / workaround, it seems that imagemagick / image optimizers creates sometimes empty PNG chunks (total size 33 bytes) // no clue why it does so as this is not continuous reproducible, and this is the only fix we can do for now // if the file is corrupted the file will be created on the fly when requested by the browser (because it's deleted here) if (is_file($fsPath) && filesize($fsPath) < 50) { unlink($fsPath); } return $path; }
public function saveFolderAction() { $object = Object::getById($this->getParam("id")); $classId = $this->getParam("class_id"); // general settings $general = \Zend_Json::decode($this->getParam("general")); $object->setValues($general); $object->setUserModification($this->getUser()->getId()); $object = $this->assignPropertiesFromEditmode($object); if ($object->isAllowed("publish")) { try { // grid config $gridConfig = \Zend_Json::decode($this->getParam("gridconfig")); if ($classId) { $configFile = PIMCORE_CONFIGURATION_DIRECTORY . "/object/grid/" . $object->getId() . "_" . $classId . "-user_" . $this->getUser()->getId() . ".psf"; } else { $configFile = PIMCORE_CONFIGURATION_DIRECTORY . "/object/grid/" . $object->getId() . "-user_" . $this->getUser()->getId() . ".psf"; } $configDir = dirname($configFile); if (!is_dir($configDir)) { File::mkdir($configDir); } File::put($configFile, Tool\Serialize::serialize($gridConfig)); $object->save(); $this->_helper->json(array("success" => true)); } catch (\Exception $e) { $this->_helper->json(array("success" => false, "message" => $e->getMessage())); } } $this->_helper->json(array("success" => false, "message" => "missing_permission")); }
public function fileexplorerAddFolderAction() { $this->checkPermission("fileexplorer"); $success = false; if ($this->getParam("filename") && $this->getParam("path")) { $path = $this->getFileexplorerPath("path"); $file = $path . "/" . $this->getParam("filename"); $file = resolvePath($file); if (strpos($file, PIMCORE_DOCUMENT_ROOT) !== 0) { throw new \Exception("not allowed"); } if (is_writeable(dirname($file))) { File::mkdir($file); $success = true; } } $this->_helper->json(["success" => $success]); }
/** * @param $params * @return mixed * @throws \Exception */ public function subscribe($params) { $onlyCreateVersion = false; $className = $this->getClassName(); $object = new $className(); // check for existing e-mail $existingObject = $className::getByEmail($params["email"], 1); if ($existingObject) { // if there's an existing user with this email address, do not overwrite the contents, but create a new // version which will be published as soon as the contact gets verified (token/email) $object = $existingObject; $onlyCreateVersion = true; //throw new \Exception("email address '" . $params["email"] . "' already exists"); } if (!array_key_exists("email", $params)) { throw new \Exception("key 'email' is a mandatory parameter"); } $object->setValues($params); if (!$object->getParentId()) { $object->setParentId(1); } $object->setNewsletterActive(true); $object->setCreationDate(time()); $object->setModificationDate(time()); $object->setUserModification(0); $object->setUserOwner(0); $object->setPublished(true); $object->setKey(\Pimcore\File::getValidFilename($object->getEmail() . "~" . substr(uniqid(), -3))); if (!$onlyCreateVersion) { $object->save(); } // generate token $token = base64_encode(\Zend_Json::encode(["salt" => md5(microtime()), "email" => $object->getEmail(), "id" => $object->getId()])); $token = str_replace("=", "~", $token); // base64 can contain = which isn't safe in URL's $object->setProperty("token", "text", $token); if (!$onlyCreateVersion) { $object->save(); } else { $object->saveVersion(true, true); } $this->addNoteOnObject($object, "subscribe"); return $object; }
/** * @param \Zend_Controller_Request_Abstract $request */ public function routeStartup(\Zend_Controller_Request_Abstract $request) { // this is a filter which checks for common used files (by browser, crawlers, ...) and prevent the default // error page, because this is more resource-intensive than exiting right here if (preg_match("@^/website/var/tmp/image-thumbnails(.*)?/([0-9]+)/thumb__([a-zA-Z0-9_\\-]+)([^\\@]+)(\\@[0-9.]+x)?\\.([a-zA-Z]{2,5})@", $request->getPathInfo(), $matches)) { $assetId = $matches[2]; $thumbnailName = $matches[3]; $format = $matches[6]; if ($asset = Asset::getById($assetId)) { try { $page = 1; $thumbnailFile = null; $thumbnailConfig = null; $deferredConfigId = "thumb_" . $assetId . "__" . md5($request->getPathInfo()); if ($thumbnailConfigItem = TmpStore::get($deferredConfigId)) { $thumbnailConfig = $thumbnailConfigItem->getData(); TmpStore::delete($deferredConfigId); if (!$thumbnailConfig instanceof Asset\Image\Thumbnail\Config) { throw new \Exception("Deferred thumbnail config file doesn't contain a valid \\Asset\\Image\\Thumbnail\\Config object"); } $tmpPage = array_pop(explode("-", $thumbnailName)); if (is_numeric($tmpPage)) { $page = $tmpPage; } } else { //get thumbnail for e.g. pdf page thumb__document_pdfPage-5 if (preg_match("|document_(.*)\\-(\\d+)\$|", $thumbnailName, $matchesThumbs)) { $thumbnailName = $matchesThumbs[1]; $page = (int) $matchesThumbs[2]; } // just check if the thumbnail exists -> throws exception otherwise $thumbnailConfig = Asset\Image\Thumbnail\Config::getByName($thumbnailName); } if ($asset instanceof Asset\Document) { $thumbnailConfig->setName(preg_replace("/\\-[\\d]+/", "", $thumbnailConfig->getName())); $thumbnailConfig->setName(str_replace("document_", "", $thumbnailConfig->getName())); $thumbnailFile = PIMCORE_DOCUMENT_ROOT . $asset->getImageThumbnail($thumbnailConfig, $page); } else { if ($asset instanceof Asset\Image) { //check if high res image is called if (array_key_exists(5, $matches)) { $highResFactor = (double) str_replace(array("@", "x"), "", $matches[5]); $thumbnailConfig->setHighResolution($highResFactor); } $thumbnailFile = PIMCORE_DOCUMENT_ROOT . $asset->getThumbnail($thumbnailConfig); } } if ($thumbnailFile && file_exists($thumbnailFile)) { $fileExtension = \Pimcore\File::getFileExtension($thumbnailFile); if (in_array($fileExtension, array("gif", "jpeg", "jpeg", "png", "pjpeg"))) { header("Content-Type: image/" . $fileExtension, true); } else { header("Content-Type: " . $asset->getMimetype(), true); } header("Content-Length: " . filesize($thumbnailFile), true); while (@ob_end_flush()) { } flush(); readfile($thumbnailFile); exit; } } catch (\Exception $e) { // nothing to do \Logger::error("Thumbnail with name '" . $thumbnailName . "' doesn't exist"); } } } }