/** * @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; }
/** * @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; }
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)); }
/** * @param $imagePath * @param array $options * @return $this|bool|self */ 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 ($this->resource) { unset($this->resource); $this->resource = null; } try { $i = new \Imagick(); $this->imagePath = $imagePath; if (method_exists($i, "setcolorspace")) { $i->setcolorspace(\Imagick::COLORSPACE_SRGB); } $i->setBackgroundColor(new \ImagickPixel('transparent')); //set .png transparent (print) if (isset($options["resolution"])) { // set the resolution to 2000x2000 for known vector formats // otherwise this will cause problems with eg. cropPercent in the image editable (select specific area) // maybe there's a better solution but for now this fixes the problem $i->setResolution($options["resolution"]["x"], $options["resolution"]["y"]); } $imagePathLoad = $imagePath; if (!defined("HHVM_VERSION")) { $imagePathLoad .= "[0]"; // not supported by HHVM implementation - selects the first layer/page in layered/pages file formats } if (!$i->readImage($imagePathLoad) || !filesize($imagePath)) { return false; } $this->resource = $i; // this is because of HHVM which has problems with $this->resource->readImage(); // set dimensions $dimensions = $this->getDimensions(); $this->setWidth($dimensions["width"]); $this->setHeight($dimensions["height"]); // check if image can have alpha channel if (!$this->reinitializing) { $alphaChannel = $i->getImageAlphaChannel(); if ($alphaChannel) { $this->setIsAlphaPossible(true); } } $this->setColorspaceToRGB(); } catch (\Exception $e) { \Logger::error("Unable to load image: " . $imagePath); \Logger::error($e); return false; } $this->setModified(false); return $this; }
/** * @static * @param $scriptContent * @return mixed */ public static function getMinimizedScriptPath($scriptContent) { $scriptPath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/minified_javascript_core_" . md5($scriptContent) . ".js"; if (!is_file($scriptPath)) { File::put($scriptPath, $scriptContent); } $params = ["scriptPath" => "/website/var/system/", "scripts" => basename($scriptPath), "_dc" => \Pimcore\Version::getRevision()]; return "/admin/misc/script-proxy?" . array_toquerystring($params); }
/** * 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 $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 $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); } }
/** * @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); } }
/** * 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.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 = 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); } $configFile = \Pimcore\Config::locateConfigFile("system.php"); File::put($configFile, to_php_data_file_format($settings)); }
/** * @throws \Exception */ public function save() { if (!$this->getKey()) { throw new \Exception("A field-collection needs a key to be saved!"); } $fieldCollectionFolder = PIMCORE_CLASS_DIRECTORY . "/fieldcollections"; // create folder if not exist if (!is_dir($fieldCollectionFolder)) { File::mkdir($fieldCollectionFolder); } $serialized = Serialize::serialize($this); $definitionFile = $fieldCollectionFolder . "/" . $this->getKey() . ".psf"; if (!is_writable(dirname($definitionFile)) || is_file($definitionFile) && !is_writable($definitionFile)) { throw new \Exception("Cannot write definition file in: " . $definitionFile . " please check write permission on this directory."); } File::put($definitionFile, $serialized); $extendClass = "Object\\Fieldcollection\\Data\\AbstractData"; if ($this->getParentClass()) { $extendClass = $this->getParentClass(); $extendClass = "\\" . ltrim($extendClass, "\\"); } // create class file $cd = '<?php '; $cd .= "\n\n"; $cd .= "/** Generated at " . date('c') . " */"; $cd .= "\n\n"; $cd .= "/**\n"; if ($_SERVER["REMOTE_ADDR"]) { $cd .= "* IP: " . $_SERVER["REMOTE_ADDR"] . "\n"; } $cd .= "*/\n"; $cd .= "\n\n"; $cd .= "namespace Pimcore\\Model\\Object\\Fieldcollection\\Data;"; $cd .= "\n\n"; $cd .= "use Pimcore\\Model\\Object;"; $cd .= "\n\n"; $cd .= "class " . ucfirst($this->getKey()) . " extends " . $extendClass . " {"; $cd .= "\n\n"; $cd .= 'public $type = "' . $this->getKey() . "\";\n"; if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) { foreach ($this->getFieldDefinitions() as $key => $def) { $cd .= "public \$" . $key . ";\n"; } } $cd .= "\n\n"; if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) { $relationTypes = array(); foreach ($this->getFieldDefinitions() as $key => $def) { /** * @var $def Object\ClassDefinition\Data */ $cd .= $def->getGetterCodeFieldcollection($this); $cd .= $def->getSetterCodeFieldcollection($this); } } $cd .= "}\n"; $cd .= "\n"; $fieldClassFolder = PIMCORE_CLASS_DIRECTORY . "/Object/Fieldcollection/Data"; if (!is_dir($fieldClassFolder)) { File::mkdir($fieldClassFolder); } $classFile = $fieldClassFolder . "/" . ucfirst($this->getKey()) . ".php"; if (!is_writable(dirname($classFile)) || is_file($classFile) && !is_writable($classFile)) { throw new \Exception("Cannot write definition file in: " . $classFile . " please check write permission on this directory."); } File::put($classFile, $cd); // update classes $classList = new Object\ClassDefinition\Listing(); $classes = $classList->load(); if (is_array($classes)) { foreach ($classes as $class) { foreach ($class->getFieldDefinitions() as $fieldDef) { if ($fieldDef instanceof Object\ClassDefinition\Data\Fieldcollections) { if (in_array($this->getKey(), $fieldDef->getAllowedTypes())) { $this->getResource()->createUpdateTable($class); break; } } } } } }
/** * Updates and save the email log entry to the db and the file-system */ protected function update() { $this->getDao()->update(); if (!is_dir(PIMCORE_LOG_MAIL_PERMANENT)) { File::mkdir(PIMCORE_LOG_MAIL_PERMANENT); } if ($html = $this->getBodyHtml()) { if (File::put(PIMCORE_LOG_MAIL_PERMANENT . '/email-' . $this->getId() . '-html.log', $html) === false) { Logger::warn('Could not write html email log file. LogId: ' . $this->getId()); } } if ($text = $this->getBodyText()) { if (File::put(PIMCORE_LOG_MAIL_PERMANENT . '/email-' . $this->getId() . '-text.log', $text) === false) { Logger::warn('Could not write text email log file. LogId: ' . $this->getId()); } } }
/** * @throws \Exception * @throws \Zend_Db_Adapter_Exception */ public function update() { $class = get_object_vars($this->model); $data = array(); foreach ($class as $key => $value) { if (in_array($key, $this->getValidTableColumns("custom_layouts"))) { if (is_array($value) || is_object($value)) { $value = Serialize::serialize($value); } else { if (is_bool($value)) { $value = (int) $value; } } $data[$key] = $value; } } $this->db->update("custom_layouts", $data, $this->db->quoteInto("id = ?", $this->model->getId())); // save definition as a serialized file $definitionFile = PIMCORE_CUSTOMLAYOUT_DIRECTORY . "/custom_definition_" . $this->model->getId() . ".psf"; if (!is_writable(dirname($definitionFile)) || is_file($definitionFile) && !is_writable($definitionFile)) { throw new \Exception("Cannot write definition file in: " . $definitionFile . " please check write permission on this directory."); } File::put($definitionFile, Serialize::serialize($this->model->layoutDefinitions)); }
/** * IMPORTER */ public function importUploadAction() { $data = file_get_contents($_FILES["Filedata"]["tmp_name"]); $data = Tool\Text::convertToUTF8($data); $importFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_" . $this->getParam("id"); File::put($importFile, $data); $importFileOriginal = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_" . $this->getParam("id") . "_original"; File::put($importFileOriginal, $data); $this->_helper->json(array("success" => true), false); // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in // Ext.form.Action.Submit and mark the submission as failed $this->getResponse()->setHeader("Content-Type", "text/html"); }
/** * @static * */ public static function initLogger() { // for forks, etc ... \Logger::resetLoggers(); // try to load configuration $conf = Config::getSystemConfig(); if ($conf) { // redirect php error_log to /website/var/log/php.log if ($conf->general->custom_php_logfile) { $phpLog = PIMCORE_LOG_DIRECTORY . "/php.log"; if (!file_exists($phpLog)) { touch($phpLog); } if (is_writable($phpLog)) { ini_set("error_log", $phpLog); ini_set("log_errors", "1"); } } } if (!is_file(PIMCORE_LOG_DEBUG)) { if (is_writable(dirname(PIMCORE_LOG_DEBUG))) { File::put(PIMCORE_LOG_DEBUG, "AUTOCREATE\n"); } } $prioMapping = array("debug" => \Zend_Log::DEBUG, "info" => \Zend_Log::INFO, "notice" => \Zend_Log::NOTICE, "warning" => \Zend_Log::WARN, "error" => \Zend_Log::ERR, "critical" => \Zend_Log::CRIT, "alert" => \Zend_Log::ALERT, "emergency" => \Zend_Log::EMERG); $prios = array(); if ($conf && $conf->general->debugloglevel) { $prioMapping = array_reverse($prioMapping); foreach ($prioMapping as $level => $state) { $prios[] = $prioMapping[$level]; if ($level == $conf->general->debugloglevel) { break; } } } else { // log everything if config isn't loaded (eg. at the installer) foreach ($prioMapping as $p) { $prios[] = $p; } } \Logger::setPriorities($prios); if (is_writable(PIMCORE_LOG_DEBUG)) { // check for big logfile, empty it if it's bigger than about 200M if (filesize(PIMCORE_LOG_DEBUG) > 200000000) { rename(PIMCORE_LOG_DEBUG, PIMCORE_LOG_DEBUG . "-archive-" . date("m-d-Y-H-i")); // archive log (will be cleaned up by maintenance) File::put(PIMCORE_LOG_DEBUG, ""); } if (!empty($prios)) { $writerFile = new \Zend_Log_Writer_Stream(PIMCORE_LOG_DEBUG); $loggerFile = new \Zend_Log($writerFile); \Logger::addLogger($loggerFile); } $conf = Config::getSystemConfig(); if ($conf) { //email logger if (!empty($conf->general->logrecipient)) { $user = User::getById($conf->general->logrecipient); if ($user instanceof User && $user->isAdmin()) { $email = $user->getEmail(); if (!empty($email)) { $mail = Tool::getMail(array($email), "pimcore log notification"); $mail->setIgnoreDebugMode(true); if (!is_dir(PIMCORE_LOG_MAIL_TEMP)) { File::mkdir(PIMCORE_LOG_MAIL_TEMP); } $tempfile = PIMCORE_LOG_MAIL_TEMP . "/log-" . uniqid() . ".log"; $writerEmail = new \Pimcore\Log\Writer\Mail($tempfile, $mail); $loggerEmail = new \Zend_Log($writerEmail); \Logger::addLogger($loggerEmail); } } } } } else { // try to use syslog instead try { $writerSyslog = new \Zend_Log_Writer_Syslog(array('application' => 'pimcore')); $loggerSyslog = new \Zend_Log($writerSyslog); \Logger::addLogger($loggerSyslog); } catch (\Exception $e) { } } if (array_key_exists("pimcore_log", $_REQUEST) && self::inDebugMode()) { if (empty($_REQUEST["pimcore_log"])) { $requestLogName = date("Y-m-d_H-i-s"); } else { $requestLogName = $_REQUEST["pimcore_log"]; } $requestLogFile = dirname(PIMCORE_LOG_DEBUG) . "/request-" . $requestLogName . ".log"; if (!file_exists($requestLogFile)) { File::put($requestLogFile, ""); } $writerRequestLog = new \Zend_Log_Writer_Stream($requestLogFile); $loggerRequest = new \Zend_Log($writerRequestLog); \Logger::addLogger($loggerRequest); \Logger::setVerbosePriorities(); } }
/** * Imports translations from a csv file * The CSV file has to have the same format as an Pimcore translation-export-file * * @static * @param $file - path to the csv file * @param bool $replaceExistingTranslations * @throws \Exception */ public static function importTranslationsFromFile($file, $replaceExistingTranslations = true, $languages = null) { $delta = []; if (is_readable($file)) { if (!$languages || empty($languages) || !is_array($languages)) { $languages = Tool::getValidLanguages(); } //read import data $tmpData = file_get_contents($file); //replace magic excel bytes $tmpData = str_replace("", "", $tmpData); //convert to utf-8 if needed $tmpData = Tool\Text::convertToUTF8($tmpData); //store data for further usage $importFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations"; File::put($importFile, $tmpData); $importFileOriginal = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations_original"; File::put($importFileOriginal, $tmpData); // determine csv type $dialect = Tool\Admin::determineCsvDialect(PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations_original"); //read data if (($handle = fopen(PIMCORE_SYSTEM_TEMP_DIRECTORY . "/import_translations", "r")) !== false) { while (($rowData = fgetcsv($handle, 0, $dialect->delimiter, $dialect->quotechar, $dialect->escapechar)) !== false) { $data[] = $rowData; } fclose($handle); } //process translations if (is_array($data) and count($data) > 1) { $keys = $data[0]; // remove wrong quotes in some export/import constellations $keys = array_map(function ($value) { return trim($value, '""'); }, $keys); $data = array_slice($data, 1); foreach ($data as $row) { $keyValueArray = []; for ($counter = 0; $counter < count($row); $counter++) { $rd = str_replace(""", '"', $row[$counter]); $keyValueArray[$keys[$counter]] = $rd; } $textKey = $keyValueArray["key"]; if ($textKey) { $t = static::getByKey($textKey, true); $dirty = false; foreach ($keyValueArray as $key => $value) { if (in_array($key, $languages)) { $currentTranslation = $t->getTranslation($key); if ($replaceExistingTranslations) { $t->addTranslation($key, $value); if ($currentTranslation != $value) { $dirty = true; } } else { if (!$t->getTranslation($key)) { $t->addTranslation($key, $value); if ($currentTranslation != $value) { $dirty = true; } } elseif ($t->getTranslation($key) != $value && $value) { $delta[] = ["lg" => $key, "key" => $textKey, "text" => $t->getTranslation($key), "csv" => $value]; } } } } if ($dirty) { if ($keyValueArray['creationDate']) { $t->setCreationDate($keyValueArray['creationDate']); } $t->setModificationDate(time()); //ignore modificationDate from file $t->save(); } } } Model\Translation\AbstractTranslation::clearDependentCache(); } else { throw new \Exception("less than 2 rows of data - nothing to import"); } } else { throw new \Exception("{$file} is not readable"); } return $delta; }
public function robotsTxtAction() { $this->checkPermission("robots.txt"); $siteSuffix = ""; if ($this->getParam("site")) { $siteSuffix = "-" . $this->getParam("site"); } $robotsPath = PIMCORE_CONFIGURATION_DIRECTORY . "/robots" . $siteSuffix . ".txt"; if ($this->getParam("data") !== null) { // save data \Pimcore\File::put($robotsPath, $this->getParam("data")); $this->_helper->json(array("success" => true)); } else { // get data $data = ""; if (is_file($robotsPath)) { $data = file_get_contents($robotsPath); } $this->_helper->json(array("success" => true, "data" => $data, "onFileSystem" => file_exists(PIMCORE_DOCUMENT_ROOT . "/robots.txt"))); } }
protected function addAsset() { $success = false; if (array_key_exists("Filedata", $_FILES)) { $filename = $_FILES["Filedata"]["name"]; $sourcePath = $_FILES["Filedata"]["tmp_name"]; } else { if ($this->getParam("type") == "base64") { $filename = $this->getParam("filename"); $sourcePath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/upload-base64" . uniqid() . ".tmp"; $data = preg_replace("@^data:[^,]+;base64,@", "", $this->getParam("data")); File::put($sourcePath, base64_decode($data)); } } if ($this->getParam("dir") && $this->getParam("parentId")) { // this is for uploading folders with Drag&Drop // param "dir" contains the relative path of the file $parent = Asset::getById($this->getParam("parentId")); $newPath = $parent->getFullPath() . "/" . trim($this->getParam("dir"), "/ "); // check if the path is outside of the asset directory $newRealPath = PIMCORE_ASSET_DIRECTORY . $newPath; $newRealPath = resolvePath($newRealPath); if (strpos($newRealPath, PIMCORE_ASSET_DIRECTORY) !== 0) { throw new \Exception("not allowed"); } $maxRetries = 5; for ($retries = 0; $retries < $maxRetries; $retries++) { try { $newParent = Asset\Service::createFolderByPath($newPath); break; } catch (\Exception $e) { if ($retries < $maxRetries - 1) { $waitTime = rand(100000, 900000); // microseconds usleep($waitTime); // wait specified time until we restart the transaction } else { // if the transaction still fail after $maxRetries retries, we throw out the exception throw $e; } } } $this->setParam("parentId", $newParent->getId()); } else { if (!$this->getParam("parentId") && $this->getParam("parentPath")) { $parent = Asset::getByPath($this->getParam("parentPath")); if ($parent instanceof Asset\Folder) { $this->setParam("parentId", $parent->getId()); } else { $this->setParam("parentId", 1); } } else { if (!$this->getParam("parentId")) { // set the parent to the root folder $this->setParam("parentId", 1); } } } $filename = File::getValidFilename($filename); if (empty($filename)) { throw new \Exception("The filename of the asset is empty"); } $parentAsset = Asset::getById(intval($this->getParam("parentId"))); // check for duplicate filename $filename = $this->getSafeFilename($parentAsset->getFullPath(), $filename); if ($parentAsset->isAllowed("create")) { if (!is_file($sourcePath) || filesize($sourcePath) < 1) { throw new \Exception("Something went wrong, please check upload_max_filesize and post_max_size in your php.ini and write permissions of /website/var/"); } $asset = Asset::create($this->getParam("parentId"), array("filename" => $filename, "sourcePath" => $sourcePath, "userOwner" => $this->user->getId(), "userModification" => $this->user->getId())); $success = true; @unlink($sourcePath); } else { \Logger::debug("prevented creating asset because of missing permissions, parent asset is " . $parentAsset->getFullPath()); } return array("success" => $success, "asset" => $asset); }
/** * @throws \Exception * @throws \Zend_Db_Adapter_Exception */ public function update() { $class = get_object_vars($this->model); $data = array(); foreach ($class as $key => $value) { if (in_array($key, $this->getValidTableColumns("classes"))) { if (is_array($value) || is_object($value)) { $value = Serialize::serialize($value); } else { if (is_bool($value)) { $value = (int) $value; } } $data[$key] = $value; } } $this->db->update("classes", $data, $this->db->quoteInto("id = ?", $this->model->getId())); // save definition as a serialized file $definitionFile = PIMCORE_CLASS_DIRECTORY . "/definition_" . $this->model->getId() . ".psf"; if (!is_writable(dirname($definitionFile)) || is_file($definitionFile) && !is_writable($definitionFile)) { throw new \Exception("Cannot write definition file in: " . $definitionFile . " please check write permission on this directory."); } File::put($definitionFile, Serialize::serialize($this->model->layoutDefinitions)); $objectTable = "object_query_" . $this->model->getId(); $objectDatastoreTable = "object_store_" . $this->model->getId(); $objectDatastoreTableRelation = "object_relations_" . $this->model->getId(); $objectView = "object_" . $this->model->getId(); // create object table if not exists $protectedColums = array("oo_id", "oo_classId", "oo_className"); $protectedDatastoreColumns = array("oo_id"); $this->db->query("CREATE TABLE IF NOT EXISTS `" . $objectTable . "` (\n\t\t\t `oo_id` int(11) NOT NULL default '0',\n\t\t\t `oo_classId` int(11) default '" . $this->model->getId() . "',\n\t\t\t `oo_className` varchar(255) default '" . $this->model->getName() . "',\n\t\t\t PRIMARY KEY (`oo_id`)\n\t\t\t) DEFAULT CHARSET=utf8;"); // update default value of classname columns $this->db->query('ALTER TABLE `' . $objectTable . "` ALTER COLUMN `oo_className` SET DEFAULT '" . $this->model->getName() . "';"); $this->db->query("CREATE TABLE IF NOT EXISTS `" . $objectDatastoreTable . "` (\n\t\t\t `oo_id` int(11) NOT NULL default '0',\n\t\t\t PRIMARY KEY (`oo_id`)\n\t\t\t) DEFAULT CHARSET=utf8;"); $this->db->query("CREATE TABLE IF NOT EXISTS `" . $objectDatastoreTableRelation . "` (\n `src_id` int(11) NOT NULL DEFAULT '0',\n `dest_id` int(11) NOT NULL DEFAULT '0',\n `type` varchar(50) NOT NULL DEFAULT '',\n `fieldname` varchar(70) NOT NULL DEFAULT '0',\n `index` int(11) unsigned NOT NULL DEFAULT '0',\n `ownertype` enum('object','fieldcollection','localizedfield','objectbrick') NOT NULL DEFAULT 'object',\n `ownername` varchar(70) NOT NULL DEFAULT '',\n `position` varchar(70) NOT NULL DEFAULT '0',\n PRIMARY KEY (`src_id`,`dest_id`,`ownertype`,`ownername`,`fieldname`,`type`,`position`),\n KEY `index` (`index`),\n KEY `src_id` (`src_id`),\n KEY `dest_id` (`dest_id`),\n KEY `fieldname` (`fieldname`),\n KEY `position` (`position`),\n KEY `ownertype` (`ownertype`),\n KEY `type` (`type`),\n KEY `ownername` (`ownername`)\n ) DEFAULT CHARSET=utf8;"); $existingColumns = $this->getValidTableColumns($objectTable, false); // no caching of table definition $existingDatastoreColumns = $this->getValidTableColumns($objectDatastoreTable, false); // no caching of table definition $columnsToRemove = $existingColumns; $datastoreColumnsToRemove = $existingDatastoreColumns; Object\ClassDefinition\Service::updateTableDefinitions($this->tableDefinitions, array($objectTable, $objectDatastoreTable)); // add non existing columns in the table if (is_array($this->model->getFieldDefinitions()) && count($this->model->getFieldDefinitions())) { foreach ($this->model->getFieldDefinitions() as $key => $value) { // if a datafield requires more than one column in the query table if (is_array($value->getQueryColumnType())) { foreach ($value->getQueryColumnType() as $fkey => $fvalue) { $this->addModifyColumn($objectTable, $key . "__" . $fkey, $fvalue, "", "NULL"); $protectedColums[] = $key . "__" . $fkey; } } // if a datafield requires more than one column in the datastore table => only for non-relation types if (!$value->isRelationType() && is_array($value->getColumnType())) { foreach ($value->getColumnType() as $fkey => $fvalue) { $this->addModifyColumn($objectDatastoreTable, $key . "__" . $fkey, $fvalue, "", "NULL"); $protectedDatastoreColumns[] = $key . "__" . $fkey; } } // everything else // if (!is_array($value->getQueryColumnType()) && !is_array($value->getColumnType())) { if (!is_array($value->getQueryColumnType()) && $value->getQueryColumnType()) { $this->addModifyColumn($objectTable, $key, $value->getQueryColumnType(), "", "NULL"); $protectedColums[] = $key; } if (!is_array($value->getColumnType()) && $value->getColumnType() && !$value->isRelationType()) { $this->addModifyColumn($objectDatastoreTable, $key, $value->getColumnType(), "", "NULL"); $protectedDatastoreColumns[] = $key; } // } // add indices $this->addIndexToField($value, $objectTable); $this->addIndexToField($value, $objectDatastoreTable); } } // remove unused columns in the table $this->removeUnusedColumns($objectTable, $columnsToRemove, $protectedColums); $this->removeUnusedColumns($objectDatastoreTable, $datastoreColumnsToRemove, $protectedDatastoreColumns, true); // create view try { //$this->db->query('CREATE OR REPLACE VIEW `' . $objectView . '` AS SELECT * FROM `objects` left JOIN `' . $objectTable . '` ON `objects`.`o_id` = `' . $objectTable . '`.`oo_id` WHERE `objects`.`o_classId` = ' . $this->model->getId() . ';'); $this->db->query('CREATE OR REPLACE VIEW `' . $objectView . '` AS SELECT * FROM `' . $objectTable . '` JOIN `objects` ON `objects`.`o_id` = `' . $objectTable . '`.`oo_id`;'); } catch (\Exception $e) { \Logger::debug($e); } $this->tableDefinitions = null; }
/** * @param User $user * @return void */ public function save($user = null) { if ($this->getElement() instanceof Element\ElementInterface) { $this->setType(Element\Service::getElementType($this->getElement())); } $this->setSubtype($this->getElement()->getType()); $this->setPath($this->getElement()->getFullPath()); $this->setDate(time()); $this->loadChilds($this->getElement()); if ($user instanceof Model\User) { $this->setDeletedby($user->getName()); } // serialize data Element\Service::loadAllFields($this->element); $this->element->_fulldump = true; $data = Serialize::serialize($this->getElement()); $this->getResource()->save(); if (!is_dir(PIMCORE_RECYCLEBIN_DIRECTORY)) { File::mkdir(PIMCORE_RECYCLEBIN_DIRECTORY); } File::put($this->getStoreageFile(), $data); $saveBinaryData = function ($element, $rec, $scope) { // assets are kina special because they can contain massive amount of binary data which isn't serialized, we create separate files for them if ($element instanceof Asset) { if ($element->getType() != "folder") { $handle = fopen($scope->getStorageFileBinary($element), "w+"); $src = $element->getStream(); stream_copy_to_stream($src, $handle); fclose($handle); } $children = $element->getChilds(); foreach ($children as $child) { $rec($child, $rec, $scope); } } }; $saveBinaryData($this->getElement(), $saveBinaryData, $this); @chmod($this->getStoreageFile(), File::getDefaultMode()); }
public function fileexplorerAddAction() { $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::put($file, ""); $success = true; } } $this->_helper->json(["success" => $success]); }
/** * @return void */ public function save() { // check if versioning is disabled for this process if (self::$disabled) { return; } if (!$this->date) { $this->setDate(time()); } $data = $this->getData(); // if necessary convert the data to save it to filesystem if (is_object($data) or is_array($data)) { // this is because of lazy loaded element inside documents and objects (eg: multihref, objects, fieldcollections, ...) if ($data instanceof Element\ElementInterface) { Element\Service::loadAllFields($data); } $this->setSerialized(true); $data->_fulldump = true; $dataString = Serialize::serialize($data); // revert all changed made by __sleep() if (method_exists($data, "__wakeup")) { $data->__wakeup(); } unset($data->_fulldump); } else { $dataString = $data; } $this->id = $this->getDao()->save(); // check if directory exists $saveDir = dirname($this->getFilePath()); if (!is_dir($saveDir)) { File::mkdir($saveDir); } // save data to filesystem if (!is_writable(dirname($this->getFilePath())) || is_file($this->getFilePath()) && !is_writable($this->getFilePath())) { throw new \Exception("Cannot save version for element " . $this->getCid() . " with type " . $this->getCtype() . " because the file " . $this->getFilePath() . " is not writeable."); } else { File::put($this->getFilePath(), $dataString); // assets are kina special because they can contain massive amount of binary data which isn't serialized, we append it to the data file if ($data instanceof Asset && $data->getType() != "folder") { // append binary data to version file $handle = fopen($this->getBinaryFilePath(), "w+"); $src = $data->getStream(); stream_copy_to_stream($src, $handle); fclose($handle); } } }
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")); }
protected function writePid($file, $content) { \Pimcore\File::put($file, serialize($content)); }
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)); }
/** * Helper to quickly create a new asset * * @param integer $parentId * @param array $data * @return Asset */ public static function create($parentId, $data = array(), $save = true) { // create already the real class for the asset type, this is especially for images, because a system-thumbnail // (tree) is generated immediately after creating an image $class = "Asset"; if (array_key_exists("filename", $data) && (array_key_exists("data", $data) || array_key_exists("sourcePath", $data) || array_key_exists("stream", $data))) { if (array_key_exists("data", $data) || array_key_exists("stream", $data)) { $tmpFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/asset-create-tmp-file-" . uniqid() . "." . File::getFileExtension($data["filename"]); if (array_key_exists("data", $data)) { File::put($tmpFile, $data["data"]); } else { $streamMeta = stream_get_meta_data($data["stream"]); if (file_exists($streamMeta["uri"])) { // stream is a local file, so we don't have to write a tmp file $tmpFile = $streamMeta["uri"]; } else { // write a tmp file because the stream isn't a pointer to the local filesystem rewind($data["stream"]); $dest = fopen($tmpFile, "w+"); stream_copy_to_stream($data["stream"], $dest); fclose($dest); } } $mimeType = Mime::detect($tmpFile); unlink($tmpFile); } else { $mimeType = Mime::detect($data["sourcePath"], $data["filename"]); if (is_file($data["sourcePath"])) { $data["stream"] = fopen($data["sourcePath"], "r+"); } unset($data["sourcePath"]); } $type = self::getTypeFromMimeMapping($mimeType, $data["filename"]); $class = "\\Pimcore\\Model\\Asset\\" . ucfirst($type); if (array_key_exists("type", $data)) { unset($data["type"]); } } $asset = new $class(); $asset->setParentId($parentId); $asset->setValues($data); if ($save) { $asset->save(); } return $asset; }