mkdir() public static method

public static mkdir ( $path, null $mode = null, boolean $recursive = true ) : boolean
$path
$mode null
$recursive boolean
return boolean
Example #1
0
 /**
  * @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;
 }
Example #2
0
 /**
  * @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));
 }
 /**
  * @static
  * @return string
  */
 public static function getWorkingDir()
 {
     $dir = PIMCORE_CONFIGURATION_DIRECTORY . "/videopipelines";
     if (!is_dir($dir)) {
         \Pimcore\File::mkdir($dir);
     }
     return $dir;
 }
Example #4
0
 /**
  * @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);
 }
Example #5
0
 /**
  * @return array|mixed
  */
 protected function loadFile()
 {
     if (!is_dir($this->getConfigDir())) {
         File::mkdir($this->getConfigDir());
     }
     if (empty($this->dashboards)) {
         if (is_file($this->getConfigFile())) {
             $dashboards = Serialize::unserialize(file_get_contents($this->getConfigFile()));
             if (!empty($dashboards)) {
                 $this->dashboards = $dashboards;
             }
         }
         if (empty($this->dashboards)) {
             // if no configuration exists, return the base config
             $this->dashboards = array("welcome" => array("positions" => array(array(array("id" => 1, "type" => "pimcore.layout.portlets.modificationStatistic", "config" => null), array("id" => 2, "type" => "pimcore.layout.portlets.modifiedAssets", "config" => null)), array(array("id" => 3, "type" => "pimcore.layout.portlets.modifiedObjects", "config" => null), array("id" => 4, "type" => "pimcore.layout.portlets.modifiedDocuments", "config" => null)))));
         }
     }
     return $this->dashboards;
 }
Example #6
0
 /**
  * @return array|mixed
  */
 protected function loadFile()
 {
     if (!is_dir($this->getConfigDir())) {
         File::mkdir($this->getConfigDir());
     }
     if (empty($this->dashboards)) {
         if (is_file($this->getConfigFile())) {
             $dashboards = Serialize::unserialize(file_get_contents($this->getConfigFile()));
             if (!empty($dashboards)) {
                 $this->dashboards = $dashboards;
             }
         }
         if (empty($this->dashboards)) {
             $perspectiveCfg = Config::getRuntimePerspective();
             $dasboardCfg = $perspectiveCfg["dashboards"] ? $perspectiveCfg["dashboards"] : [];
             $this->dashboards = $dasboardCfg["predefined"] ? $dasboardCfg["predefined"] : [];
         }
     }
     return $this->dashboards;
 }
Example #7
0
 /**
  * @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();
 }
Example #8
0
 /**
  * returns the path to a temp file
  *
  * @return string
  */
 public function getTemporaryFile($fullPath = false)
 {
     $destinationPath = PIMCORE_TEMPORARY_DIRECTORY . "/asset-temporary/asset_" . $this->getId() . "_" . md5(microtime()) . "__" . $this->getFilename();
     if (!is_dir(dirname($destinationPath))) {
         File::mkdir(dirname($destinationPath));
     }
     $src = $this->getStream();
     $dest = fopen($destinationPath, "w+");
     stream_copy_to_stream($src, $dest);
     fclose($dest);
     @chmod($destinationPath, File::getDefaultMode());
     if ($fullPath) {
         return $destinationPath;
     }
     return str_replace(PIMCORE_DOCUMENT_ROOT, "", $destinationPath);
 }
Example #9
0
 /**
  * @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());
 }
Example #10
0
 /**
  * @param $thumbnailName
  * @param int $page
  * @param bool $deferred $deferred deferred means that the image will be generated on-the-fly (details see below)
  * @return mixed|string
  */
 public function getImageThumbnail($thumbnailName, $page = 1, $deferred = false)
 {
     // just 4 testing
     //$this->clearThumbnails(true);
     if (!\Pimcore\Document::isAvailable()) {
         \Logger::error("Couldn't create image-thumbnail of document " . $this->getFullPath() . " no document adapter is available");
         return "/pimcore/static/img/filetype-not-supported.png";
     }
     $thumbnail = Image\Thumbnail\Config::getByAutoDetect($thumbnailName);
     $thumbnail->setName("document_" . $thumbnail->getName() . "-" . $page);
     try {
         if (!$deferred) {
             $converter = \Pimcore\Document::getInstance();
             $converter->load($this->getFileSystemPath());
             $path = PIMCORE_TEMPORARY_DIRECTORY . "/document-image-cache/document_" . $this->getId() . "__thumbnail_" . $page . ".png";
             if (!is_dir(dirname($path))) {
                 \Pimcore\File::mkdir(dirname($path));
             }
             $lockKey = "document-thumbnail-" . $this->getId() . "-" . $page;
             if (!is_file($path) && !Model\Tool\Lock::isLocked($lockKey)) {
                 Model\Tool\Lock::lock($lockKey);
                 $converter->saveImage($path, $page);
                 Model\Tool\Lock::release($lockKey);
             } else {
                 if (Model\Tool\Lock::isLocked($lockKey)) {
                     return "/pimcore/static/img/please-wait.png";
                 }
             }
         }
         if ($thumbnail) {
             $path = Image\Thumbnail\Processor::process($this, $thumbnail, $path, $deferred);
         }
         return preg_replace("@^" . preg_quote(PIMCORE_DOCUMENT_ROOT) . "@", "", $path);
     } catch (\Exception $e) {
         \Logger::error("Couldn't create image-thumbnail of document " . $this->getFullPath());
         \Logger::error($e);
     }
     return "/pimcore/static/img/filetype-not-supported.png";
 }
 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"));
 }
Example #12
0
 /**
  *
  */
 public function generate()
 {
     $errorImage = PIMCORE_PATH . '/static6/img/filetype-not-supported.png';
     $deferred = false;
     $generated = false;
     if (!$this->asset) {
         $this->filesystemPath = $errorImage;
     } elseif (!$this->filesystemPath) {
         $cs = $this->asset->getCustomSetting("image_thumbnail_time");
         $im = $this->asset->getCustomSetting("image_thumbnail_asset");
         if ($im || $this->imageAsset) {
             if ($this->imageAsset) {
                 $im = $this->imageAsset;
             } else {
                 $im = Model\Asset::getById($im);
             }
             if ($im instanceof Image) {
                 $imageThumbnail = $im->getThumbnail($this->getConfig());
                 $this->filesystemPath = $imageThumbnail->getFileSystemPath();
             }
         }
         if (!$this->filesystemPath) {
             $timeOffset = $this->timeOffset;
             if (!$this->timeOffset && $cs) {
                 $timeOffset = $cs;
             }
             // fallback
             if (!$timeOffset) {
                 $timeOffset = ceil($this->asset->getDuration() / 3);
             }
             $converter = \Pimcore\Video::getInstance();
             $converter->load($this->asset->getFileSystemPath());
             $path = PIMCORE_TEMPORARY_DIRECTORY . "/video-image-cache/video_" . $this->asset->getId() . "__thumbnail_" . $timeOffset . ".png";
             if (!is_dir(dirname($path))) {
                 File::mkdir(dirname($path));
             }
             if (!is_file($path)) {
                 $lockKey = "video_image_thumbnail_" . $this->asset->getId() . "_" . $timeOffset;
                 Model\Tool\Lock::acquire($lockKey);
                 // after we got the lock, check again if the image exists in the meantime - if not - generate it
                 if (!is_file($path)) {
                     $converter->saveImage($path, $timeOffset);
                     $generated = true;
                 }
                 Model\Tool\Lock::release($lockKey);
             }
             if ($this->getConfig()) {
                 $this->getConfig()->setFilenameSuffix("time-" . $timeOffset);
                 try {
                     $path = Image\Thumbnail\Processor::process($this->asset, $this->getConfig(), $path, $deferred, true, $generated);
                 } catch (\Exception $e) {
                     Logger::error("Couldn't create image-thumbnail of video " . $this->asset->getRealFullPath());
                     Logger::error($e);
                     $path = $errorImage;
                 }
             }
             $this->filesystemPath = $path;
         }
         \Pimcore::getEventManager()->trigger("asset.video.image-thumbnail", $this, ["deferred" => $deferred, "generated" => $generated]);
     }
 }
Example #13
0
 /**
  * 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());
         }
     }
 }
 public function fileexplorerAddFolderAction()
 {
     $this->checkPermission("fileexplorer");
     $success = false;
     if ($this->getParam("filename") && $this->getParam("path")) {
         $path = $this->getFileexplorerPath("path");
         $file = $path . "/" . $this->getParam("filename");
         if (is_writeable(dirname($file))) {
             File::mkdir($file);
             $success = true;
         }
     }
     $this->_helper->json(array("success" => $success));
 }
 public function generateScreenshotAction()
 {
     $success = false;
     if ($this->getParam("id")) {
         $doc = Document::getById($this->getParam("id"));
         $url = Tool::getHostUrl() . $doc->getRealFullPath() . "?pimcore_preview=true";
         $config = \Pimcore\Config::getSystemConfig();
         if ($config->general->http_auth) {
             $username = $config->general->http_auth->username;
             $password = $config->general->http_auth->password;
             if ($username && $password) {
                 $url = str_replace("://", "://" . $username . ":" . $password . "@", $url);
             }
         }
         $tmpFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/screenshot_tmp_" . $doc->getId() . ".png";
         $file = PIMCORE_TEMPORARY_DIRECTORY . "/document-page-previews/document-page-screenshot-" . $doc->getId() . ".jpg";
         $dir = dirname($file);
         if (!is_dir($dir)) {
             File::mkdir($dir);
         }
         try {
             if (\Pimcore\Image\HtmlToImage::convert($url, $tmpFile)) {
                 $im = \Pimcore\Image::getInstance();
                 $im->load($tmpFile);
                 $im->scaleByWidth(400);
                 $im->save($file, "jpeg", 85);
                 unlink($tmpFile);
                 $success = true;
             }
         } catch (\Exception $e) {
             \Logger::error($e);
         }
     }
     $this->_helper->json(array("success" => $success));
 }
Example #16
0
 /**
  * @param null $path
  * @return null|string|void
  * @throws \Exception
  */
 public function getPdf($path = null)
 {
     if ($path) {
         $path = $this->preparePath($path);
     }
     $pdfPath = null;
     if (!$path && $this->path) {
         $path = $this->path;
     }
     try {
         // if the document is already an PDF, delegate the call directly to parent::getPdf() (Ghostscript)
         $pdfPath = parent::getPdf($path);
         return $pdfPath;
     } catch (\Exception $e) {
         // nothing to do, delegate to libreoffice
     }
     $pdfFile = PIMCORE_TEMPORARY_DIRECTORY . "/document-pdf-cache/document_" . md5($path . filemtime($path)) . "__libreoffice.pdf";
     if (!is_dir(dirname($pdfFile))) {
         File::mkdir(dirname($pdfFile));
     }
     $lockKey = "soffice";
     if (!file_exists($pdfFile)) {
         // a list of all available filters is here:
         // http://cgit.freedesktop.org/libreoffice/core/tree/filter/source/config/fragments/filters
         $cmd = self::getLibreOfficeCli() . " --headless --nologo --nofirststartwizard --norestore --convert-to pdf:writer_web_pdf_Export --outdir " . escapeshellarg(PIMCORE_SYSTEM_TEMP_DIRECTORY) . " " . escapeshellarg($path);
         Model\Tool\Lock::acquire($lockKey);
         // avoid parallel conversions
         $out = Console::exec($cmd, PIMCORE_LOG_DIRECTORY . "/libreoffice-pdf-convert.log", 240);
         Model\Tool\Lock::release($lockKey);
         Logger::debug("LibreOffice Output was: " . $out);
         $tmpName = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/" . preg_replace("/\\." . File::getFileExtension($path) . "\$/", ".pdf", basename($path));
         if (file_exists($tmpName)) {
             File::rename($tmpName, $pdfFile);
             $pdfPath = $pdfFile;
         } else {
             $message = "Couldn't convert document to PDF: " . $path . " with the command: '" . $cmd . "'";
             Logger::error($message);
             throw new \Exception($message);
         }
     } else {
         $pdfPath = $pdfFile;
     }
     return $pdfPath;
 }
Example #17
0
 /**
  * @throws \Exception
  */
 private function createContainerClasses()
 {
     $containerDefinition = array();
     if (!empty($this->classDefinitions)) {
         foreach ($this->classDefinitions as $cl) {
             $containerDefinition[$cl['classname']][$cl['fieldname']][] = $this->key;
             $class = Object\ClassDefinition::getById($cl['classname']);
             $fd = $class->getFieldDefinition($cl['fieldname']);
             if (!$fd) {
                 throw new \Exception("Could not resolve field definition for " . $cl['fieldname']);
             }
             $allowedTypes = $fd->getAllowedTypes();
             if (!in_array($this->key, $allowedTypes)) {
                 $allowedTypes[] = $this->key;
             }
             $fd->setAllowedTypes($allowedTypes);
             $class->save();
         }
     }
     $list = new Object\Objectbrick\Definition\Listing();
     $list = $list->load();
     foreach ($list as $def) {
         if ($this->key != $def->getKey()) {
             $classDefinitions = $def->getClassDefinitions();
             if (!empty($classDefinitions)) {
                 foreach ($classDefinitions as $cl) {
                     $containerDefinition[$cl['classname']][$cl['fieldname']][] = $def->getKey();
                 }
             }
         }
     }
     foreach ($containerDefinition as $classId => $cd) {
         $class = Object\ClassDefinition::getById($classId);
         if (!$class) {
             continue;
         }
         foreach ($cd as $fieldname => $brickKeys) {
             $className = $this->getContainerClassName($class->getName(), $fieldname);
             $namespace = $this->getContainerNamespace($class->getName(), $fieldname);
             $cd = '<?php ';
             $cd .= "\n\n";
             $cd .= "namespace " . $namespace . ";";
             $cd .= "\n\n";
             $cd .= "class " . $className . " extends \\Pimcore\\Model\\Object\\Objectbrick {";
             $cd .= "\n\n";
             $cd .= "\n\n";
             $cd .= 'protected $brickGetters = array(' . "'" . implode("','", $brickKeys) . "');\n";
             $cd .= "\n\n";
             foreach ($brickKeys as $brickKey) {
                 $cd .= 'public $' . $brickKey . " = null;\n\n";
                 $cd .= '/**' . "\n";
                 $cd .= '* @return \\Pimcore\\Model\\Object\\Objectbrick\\Data\\' . $brickKey . "\n";
                 $cd .= '*/' . "\n";
                 $cd .= "public function get" . ucfirst($brickKey) . "() { \n";
                 if ($class->getAllowInherit()) {
                     $cd .= "\t" . 'if(!$this->' . $brickKey . ' && \\Pimcore\\Model\\Object\\AbstractObject::doGetInheritedValues($this->getObject())) { ' . "\n";
                     $cd .= "\t\t" . '$brick = $this->getObject()->getValueFromParent("' . $fieldname . '");' . "\n";
                     $cd .= "\t\t" . 'if(!empty($brick)) {' . "\n";
                     $cd .= "\t\t\t" . 'return $this->getObject()->getValueFromParent("' . $fieldname . '")->get' . ucfirst($brickKey) . "(); \n";
                     $cd .= "\t\t" . "}\n";
                     $cd .= "\t" . "}\n";
                 }
                 $cd .= '   return $this->' . $brickKey . "; \n";
                 $cd .= "}\n\n";
                 $cd .= '/**' . "\n";
                 $cd .= '* @param \\Pimcore\\Model\\Object\\Objectbrick\\Data\\' . $brickKey . ' $' . $brickKey . "\n";
                 $cd .= "* @return void\n";
                 $cd .= '*/' . "\n";
                 $cd .= "public function set" . ucfirst($brickKey) . " (" . '$' . $brickKey . ") {\n";
                 $cd .= "\t" . '$this->' . $brickKey . " = " . '$' . $brickKey . ";\n";
                 $cd .= "\t" . 'return $this;' . ";\n";
                 $cd .= "}\n\n";
             }
             $cd .= "}\n";
             $cd .= "\n";
             $folder = $this->getContainerClassFolder($class->getName());
             if (!is_dir($folder)) {
                 File::mkdir($folder);
             }
             $file = $folder . "/" . ucfirst($fieldname) . ".php";
             File::put($file, $cd);
         }
     }
 }
Example #18
0
 /**
  * @param Model\Asset\Video $asset
  * @param $config
  * @param array $onlyFormats
  * @return Processor
  * @throws \Exception
  */
 public static function process(Model\Asset\Video $asset, $config, $onlyFormats = [])
 {
     if (!\Pimcore\Video::isAvailable()) {
         throw new \Exception("No ffmpeg executable found, please configure the correct path in the system settings");
     }
     $instance = new self();
     $formats = empty($onlyFormats) ? ["mp4"] : $onlyFormats;
     $instance->setProcessId(uniqid());
     $instance->setAssetId($asset->getId());
     $instance->setConfig($config);
     // check for running or already created thumbnails
     $customSetting = $asset->getCustomSetting("thumbnails");
     $existingFormats = [];
     if (is_array($customSetting) && array_key_exists($config->getName(), $customSetting)) {
         if ($customSetting[$config->getName()]["status"] == "inprogress") {
             if (TmpStore::get($instance->getJobStoreId($customSetting[$config->getName()]["processId"]))) {
                 return;
             }
         } elseif ($customSetting[$config->getName()]["status"] == "finished") {
             // check if the files are there
             $formatsToConvert = [];
             foreach ($formats as $f) {
                 if (!is_file($asset->getVideoThumbnailSavePath() . $customSetting[$config->getName()]["formats"][$f])) {
                     $formatsToConvert[] = $f;
                 } else {
                     $existingFormats[$f] = $customSetting[$config->getName()]["formats"][$f];
                     $existingFormats[$f] = $customSetting[$config->getName()]["formats"][$f];
                 }
             }
             if (!empty($formatsToConvert)) {
                 $formats = $formatsToConvert;
             } else {
                 return;
             }
         } elseif ($customSetting[$config->getName()]["status"] == "error") {
             throw new \Exception("Unable to convert video, see logs for details.");
         }
     }
     foreach ($formats as $format) {
         $thumbDir = $asset->getVideoThumbnailSavePath() . "/thumb__" . $config->getName();
         $filename = preg_replace("/\\." . preg_quote(File::getFileExtension($asset->getFilename())) . "/", "", $asset->getFilename()) . "." . $format;
         $fsPath = $thumbDir . "/" . $filename;
         $tmpPath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/" . $filename;
         if (!is_dir(dirname($fsPath))) {
             File::mkdir(dirname($fsPath));
         }
         if (is_file($fsPath)) {
             @unlink($fsPath);
         }
         $converter = \Pimcore\Video::getInstance();
         $converter->load($asset->getFileSystemPath());
         $converter->setAudioBitrate($config->getAudioBitrate());
         $converter->setVideoBitrate($config->getVideoBitrate());
         $converter->setFormat($format);
         $converter->setDestinationFile($tmpPath);
         $converter->setStorageFile($fsPath);
         $transformations = $config->getItems();
         if (is_array($transformations) && count($transformations) > 0) {
             foreach ($transformations as $transformation) {
                 if (!empty($transformation)) {
                     $arguments = [];
                     $mapping = self::$argumentMapping[$transformation["method"]];
                     if (is_array($transformation["arguments"])) {
                         foreach ($transformation["arguments"] as $key => $value) {
                             $position = array_search($key, $mapping);
                             if ($position !== false) {
                                 $arguments[$position] = $value;
                             }
                         }
                     }
                     ksort($arguments);
                     if (count($mapping) == count($arguments)) {
                         call_user_func_array([$converter, $transformation["method"]], $arguments);
                     } else {
                         $message = "Video Transform failed: cannot call method `" . $transformation["method"] . "´ with arguments `" . implode(",", $arguments) . "´ because there are too few arguments";
                         Logger::error($message);
                     }
                 }
             }
         }
         $instance->queue[] = $converter;
     }
     $customSetting = $asset->getCustomSetting("thumbnails");
     $customSetting = is_array($customSetting) ? $customSetting : [];
     $customSetting[$config->getName()] = ["status" => "inprogress", "formats" => $existingFormats, "processId" => $instance->getProcessId()];
     $asset->setCustomSetting("thumbnails", $customSetting);
     $asset->save();
     $instance->convert();
     return $instance;
 }
Example #19
0
 public function createAction()
 {
     $success = false;
     $name = ucfirst($this->getParam("name"));
     $examplePluginPath = realpath(PIMCORE_PATH . "/modules/extensionmanager/example-plugin");
     $pluginDestinationPath = realpath(PIMCORE_PLUGINS_PATH) . DIRECTORY_SEPARATOR . $name;
     if (preg_match("/^[a-zA-Z0-9_]+\$/", $name, $matches) && !is_dir($pluginDestinationPath)) {
         $pluginExampleFiles = rscandir($examplePluginPath);
         foreach ($pluginExampleFiles as $pluginExampleFile) {
             if (!is_file($pluginExampleFile)) {
                 continue;
             }
             $newPath = $pluginDestinationPath . str_replace($examplePluginPath . DIRECTORY_SEPARATOR . 'Example', '', $pluginExampleFile);
             $newPath = str_replace(DIRECTORY_SEPARATOR . "Example" . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR . $name . DIRECTORY_SEPARATOR, $newPath);
             $content = file_get_contents($pluginExampleFile);
             // do some modifications in the content of the file
             $content = str_replace("/Example/", "/" . $name . "/", $content);
             $content = str_replace(">Example<", ">" . $name . "<", $content);
             $content = str_replace(".example", "." . strtolower($name), $content);
             $content = str_replace("examplePlugin", strtolower($name) . "Plugin", $content);
             $content = str_replace("Example Plugin", $name . " Plugin", $content);
             $content = str_replace("Example", $name, $content);
             if (!file_exists(dirname($newPath))) {
                 File::mkdir(dirname($newPath));
             }
             File::put($newPath, $content);
         }
         $success = true;
     }
     $this->_helper->json(array("success" => $success));
 }
Example #20
0
 /**
  * @return void
  */
 public function save()
 {
     $isUpdate = false;
     if ($this->getId()) {
         $isUpdate = true;
         \Pimcore::getEventManager()->trigger("object.customLayout.preUpdate", $this);
     } else {
         \Pimcore::getEventManager()->trigger("object.customLayout.preAdd", $this);
     }
     $this->setModificationDate(time());
     // create directory if not exists
     if (!is_dir(PIMCORE_CUSTOMLAYOUT_DIRECTORY)) {
         \Pimcore\File::mkdir(PIMCORE_CUSTOMLAYOUT_DIRECTORY);
     }
     $this->getDao()->save();
     // empty custom layout cache
     try {
         Cache::clearTag("customlayout_" . $this->getId());
     } catch (\Exception $e) {
     }
 }
Example #21
0
 /**
  * Returns the path on the file system
  *
  * @return string
  */
 protected function getFilePath()
 {
     $group = floor($this->getCid() / 10000) * 10000;
     $path = PIMCORE_VERSION_DIRECTORY . "/" . $this->getCtype() . "/g" . $group . "/" . $this->getCid() . "/" . $this->getId();
     if (!is_dir(dirname($path))) {
         \Pimcore\File::mkdir(dirname($path));
     }
     return $path;
 }
Example #22
0
 /**
  * @throws \Exception
  */
 public function save()
 {
     $isUpdate = false;
     if ($this->getId()) {
         $isUpdate = true;
         \Pimcore::getEventManager()->trigger("object.class.preUpdate", $this);
     } else {
         \Pimcore::getEventManager()->trigger("object.class.preAdd", $this);
     }
     $this->setModificationDate(time());
     $this->getDao()->save();
     // create class for object
     $extendClass = "Concrete";
     if ($this->getParentClass()) {
         $extendClass = $this->getParentClass();
         $extendClass = "\\" . ltrim($extendClass, "\\");
     }
     // creaste directory if not exists
     if (!is_dir(PIMCORE_CLASS_DIRECTORY . "/Object")) {
         File::mkdir(PIMCORE_CLASS_DIRECTORY . "/Object");
     }
     $cd = '<?php ';
     $cd .= "\n\n";
     $cd .= "/** Generated at " . date('c') . " */";
     $cd .= "\n\n";
     $cd .= "/**\n";
     if ($this->getDescription()) {
         $description = str_replace(array("/**", "*/", "//"), "", $this->getDescription());
         $description = str_replace("\n", "\n* ", $description);
         $cd .= "* " . $description . "\n";
     }
     $cd .= "* Inheritance: " . ($this->getAllowInherit() ? "yes" : "no") . "\n";
     $cd .= "* Variants   : " . ($this->getAllowVariants() ? "yes" : "no") . "\n";
     $user = Model\User::getById($this->getUserModification());
     if ($user) {
         $cd .= "* Changed by : " . $user->getName() . " (" . $user->getId() . ")" . "\n";
     }
     if ($_SERVER["REMOTE_ADDR"]) {
         $cd .= "* IP:          " . $_SERVER["REMOTE_ADDR"] . "\n";
     }
     $cd .= "*/\n";
     $cd .= "\n\n";
     $cd .= "namespace Pimcore\\Model\\Object;";
     $cd .= "\n\n";
     $cd .= "\n\n";
     $cd .= "/**\n";
     if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) {
         foreach ($this->getFieldDefinitions() as $key => $def) {
             if (!(method_exists($def, "isRemoteOwner") and $def->isRemoteOwner())) {
                 $cd .= "* @method static \\Pimcore\\Model\\Object\\" . ucfirst($this->getName()) . '\\Listing getBy' . ucfirst($def->getName()) . ' ($value, $limit = 0) ' . "\n";
             }
         }
     }
     $cd .= "*/\n\n";
     $cd .= "class " . ucfirst($this->getName()) . " extends " . $extendClass . " {";
     $cd .= "\n\n";
     if ($this->getUseTraits()) {
         $cd .= 'use ' . $this->getUseTraits() . ";\n";
         $cd .= "\n";
     }
     $cd .= 'public $o_classId = ' . $this->getId() . ";\n";
     $cd .= 'public $o_className = "' . $this->getName() . '"' . ";\n";
     if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) {
         foreach ($this->getFieldDefinitions() as $key => $def) {
             if (!(method_exists($def, "isRemoteOwner") && $def->isRemoteOwner()) && !$def instanceof Object\ClassDefinition\Data\CalculatedValue) {
                 $cd .= "public \$" . $key . ";\n";
             }
         }
     }
     $cd .= "\n\n";
     $cd .= '/**' . "\n";
     $cd .= '* @param array $values' . "\n";
     $cd .= '* @return \\Pimcore\\Model\\Object\\' . ucfirst($this->getName()) . "\n";
     $cd .= '*/' . "\n";
     $cd .= 'public static function create($values = array()) {';
     $cd .= "\n";
     $cd .= "\t" . '$object = new static();' . "\n";
     $cd .= "\t" . '$object->setValues($values);' . "\n";
     $cd .= "\t" . 'return $object;' . "\n";
     $cd .= "}";
     $cd .= "\n\n";
     if (is_array($this->getFieldDefinitions()) && count($this->getFieldDefinitions())) {
         $relationTypes = array();
         foreach ($this->getFieldDefinitions() as $key => $def) {
             if (method_exists($def, "isRemoteOwner") and $def->isRemoteOwner()) {
                 continue;
             }
             // get setter and getter code
             $cd .= $def->getGetterCode($this);
             $cd .= $def->getSetterCode($this);
             // call the method "classSaved" if exists, this is used to create additional data tables or whatever which depends on the field definition, for example for localizedfields
             if (method_exists($def, "classSaved")) {
                 $def->classSaved($this);
             }
             if ($def->isRelationType()) {
                 $relationTypes[$key] = array("type" => $def->getFieldType());
             }
             // collect lazyloaded fields
             if (method_exists($def, "getLazyLoading") and $def->getLazyLoading()) {
                 $lazyLoadedFields[] = $key;
             }
         }
         $cd .= 'protected static $_relationFields = ' . var_export($relationTypes, true) . ";\n\n";
         $cd .= 'public $lazyLoadedFields = ' . var_export($lazyLoadedFields, true) . ";\n\n";
     }
     $cd .= "}\n";
     $cd .= "\n";
     $classFile = PIMCORE_CLASS_DIRECTORY . "/Object/" . ucfirst($this->getName()) . ".php";
     if (!is_writable(dirname($classFile)) || is_file($classFile) && !is_writable($classFile)) {
         throw new \Exception("Cannot write class file in " . $classFile . " please check the rights on this directory");
     }
     File::put($classFile, $cd);
     // create list class
     $cd = '<?php ';
     $cd .= "\n\n";
     $cd .= "namespace Pimcore\\Model\\Object\\" . ucfirst($this->getName()) . ";";
     $cd .= "\n\n";
     $cd .= "use Pimcore\\Model\\Object;";
     $cd .= "\n\n";
     $cd .= "/**\n";
     $cd .= " * @method Object\\" . ucfirst($this->getName()) . " current()\n";
     $cd .= " */";
     $cd .= "\n\n";
     $cd .= "class Listing extends Object\\Listing\\Concrete {";
     $cd .= "\n\n";
     $cd .= 'public $classId = ' . $this->getId() . ";\n";
     $cd .= 'public $className = "' . $this->getName() . '"' . ";\n";
     $cd .= "\n\n";
     $cd .= "}\n";
     /*$cd .= "?>";*/
     File::mkdir(PIMCORE_CLASS_DIRECTORY . "/Object/" . ucfirst($this->getName()));
     $classListFile = PIMCORE_CLASS_DIRECTORY . "/Object/" . ucfirst($this->getName()) . "/Listing.php";
     if (!is_writable(dirname($classListFile)) || is_file($classListFile) && !is_writable($classListFile)) {
         throw new \Exception("Cannot write class file in " . $classListFile . " please check the rights on this directory");
     }
     File::put($classListFile, $cd);
     // empty object cache
     try {
         Cache::clearTag("class_" . $this->getId());
     } catch (\Exception $e) {
     }
     if ($isUpdate) {
         \Pimcore::getEventManager()->trigger("object.class.postUpdate", $this);
     } else {
         \Pimcore::getEventManager()->trigger("object.class.postAdd", $this);
     }
 }
Example #23
0
 /**
  * @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;
                     }
                 }
             }
         }
     }
 }
 public function importZipFilesAction()
 {
     $jobId = $this->getParam("jobId");
     $limit = (int) $this->getParam("limit");
     $offset = (int) $this->getParam("offset");
     $importAsset = Asset::getById($this->getParam("parentId"));
     $zipFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/" . $jobId . ".zip";
     $tmpDir = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/zip-import";
     if (!is_dir($tmpDir)) {
         File::mkdir($tmpDir, 0777, true);
     }
     $zip = new \ZipArchive();
     if ($zip->open($zipFile) === true) {
         for ($i = $offset; $i < $offset + $limit; $i++) {
             $path = $zip->getNameIndex($i);
             if ($path !== false) {
                 if ($zip->extractTo($tmpDir . "/", $path)) {
                     $tmpFile = $tmpDir . "/" . preg_replace("@^/@", "", $path);
                     $filename = File::getValidFilename(basename($path));
                     $relativePath = "";
                     if (dirname($path) != ".") {
                         $relativePath = dirname($path);
                     }
                     $parentPath = $importAsset->getFullPath() . "/" . preg_replace("@^/@", "", $relativePath);
                     $parent = Asset\Service::createFolderByPath($parentPath);
                     // check for duplicate filename
                     $filename = $this->getSafeFilename($parent->getFullPath(), $filename);
                     if ($parent->isAllowed("create")) {
                         $asset = Asset::create($parent->getId(), array("filename" => $filename, "sourcePath" => $tmpFile, "userOwner" => $this->user->getId(), "userModification" => $this->user->getId()));
                         @unlink($tmpFile);
                     } else {
                         \Logger::debug("prevented creating asset because of missing permissions");
                     }
                 }
             }
         }
         $zip->close();
     }
     if ($this->getParam("last")) {
         unlink($zipFile);
     }
     $this->_helper->json(array("success" => true));
 }
Example #25
0
 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]);
 }
Example #26
0
 /**
  * returns the path to a temp file
  * @return string
  */
 public function getTemporaryFile()
 {
     $destinationPath = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/asset-temporary/asset_" . $this->getId() . "_" . md5(microtime()) . "__" . $this->getFilename();
     if (!is_dir(dirname($destinationPath))) {
         File::mkdir(dirname($destinationPath));
     }
     $src = $this->getStream();
     $dest = fopen($destinationPath, "w+", false, File::getContext());
     stream_copy_to_stream($src, $dest);
     fclose($dest);
     @chmod($destinationPath, File::getDefaultMode());
     return $destinationPath;
 }
Example #27
0
 /**
  * @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;
 }
Example #28
0
 /**
  * @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();
     }
 }
Example #29
0
 /**
  * @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);
 }
Example #30
0
/**
 * @param $source
 * @param $destination
 * @return bool
 */
function recursiveCopy($source, $destination)
{
    if (is_dir($source)) {
        if (!is_dir($destination)) {
            \Pimcore\File::mkdir($destination);
        }
        foreach ($iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item) {
            if ($item->isDir()) {
                \Pimcore\File::mkdir($destination . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
            } else {
                copy($item, $destination . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
            }
        }
    } elseif (is_file($source)) {
        if (is_dir(dirname($destination))) {
            \Pimcore\File::mkdir(dirname($destination));
        }
        copy($source, $destination);
    }
    return true;
}