Example #1
0
 /**
  * @param null $adapter
  * @return null|Adapter\GD|Adapter\Imagick
  * @throws \Exception
  */
 public static function getInstance($adapter = null)
 {
     // use the default adapter if set manually (!= null) and no specify adapter is given
     if (!$adapter && self::$defaultAdapter) {
         $adapter = self::$defaultAdapter;
     }
     try {
         if ($adapter) {
             $adapterClass = "\\Pimcore\\Image\\Adapter\\" . $adapter;
             if (Tool::classExists($adapterClass)) {
                 return new $adapterClass();
             } else {
                 if (Tool::classExists($adapter)) {
                     return new $adapter();
                 } else {
                     throw new \Exception("Image-transform adapter `" . $adapter . "ยด does not exist.");
                 }
             }
         } else {
             if (extension_loaded("imagick")) {
                 return new Adapter\Imagick();
             } else {
                 return new Adapter\GD();
             }
         }
     } catch (\Exception $e) {
         \Logger::crit("Unable to load image extensions: " . $e->getMessage());
         throw $e;
     }
     return null;
 }
Example #2
0
 /**
  * @param $type
  * @param $realName
  * @param array $options
  * @return Model\Document\Tag
  */
 public function tag($type, $realName, $options = array())
 {
     $type = strtolower($type);
     $document = $this->document;
     $name = Model\Document\Tag::buildTagName($type, $realName, $document);
     try {
         if ($document instanceof Model\Document\PageSnippet) {
             $tag = $document->getElement($name);
             if ($tag instanceof Model\Document\Tag && $tag->getType() == $type) {
                 // call the load() method if it exists to reinitialize the data (eg. from serializing, ...)
                 if (method_exists($tag, "load")) {
                     $tag->load();
                 }
                 // set view & controller, editmode
                 $tag->setController($this->controller);
                 $tag->setView($this);
                 $tag->setEditmode($this->editmode);
                 $tag->setOptions($options);
             } else {
                 $tag = Model\Document\Tag::factory($type, $name, $document->getId(), $options, $this->controller, $this, $this->editmode);
                 $document->setElement($name, $tag);
             }
             // set the real name of this editable, without the prefixes and suffixes from blocks and areablocks
             $tag->setRealName($realName);
         }
         return $tag;
     } catch (\Exception $e) {
         \Logger::warning($e);
     }
 }
Example #3
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // display error message
     if (!$input->getOption("mode")) {
         $this->writeError("Please specify the mode!");
         exit;
     }
     $db = \Pimcore\Db::get();
     if ($input->getOption("mode") == "optimize") {
         $tables = $db->fetchAll("SHOW TABLES");
         foreach ($tables as $table) {
             $t = current($table);
             try {
                 Logger::debug("Running: OPTIMIZE TABLE " . $t);
                 $db->query("OPTIMIZE TABLE " . $t);
             } catch (\Exception $e) {
                 Logger::error($e);
             }
         }
     } elseif ($input->getOption("mode") == "warmup") {
         $tables = $db->fetchAll("SHOW TABLES");
         foreach ($tables as $table) {
             $t = current($table);
             try {
                 Logger::debug("Running: SELECT COUNT(*) FROM {$t}");
                 $res = $db->fetchOne("SELECT COUNT(*) FROM {$t}");
                 Logger::debug("Result: " . $res);
             } catch (\Exception $e) {
                 Logger::error($e);
             }
         }
     }
 }
 /**
  * @static
  * @return bool
  */
 public static function stopCrawler()
 {
     \Pimcore\Logger::debug('LuceneSearch: forcing frontend crawler stop');
     self::setStopLock('frontend', FALSE);
     self::setCrawlerState('frontend', 'finished', FALSE);
     return TRUE;
 }
Example #5
0
 /**
  * Loads a list of entries for the specicifies parameters, returns an array of Search\Backend\Data
  *
  * @return array
  */
 public function load()
 {
     $entries = [];
     $data = $this->db->fetchAll("SELECT * FROM search_backend_data" . $this->getCondition() . $this->getGroupBy() . $this->getOrder() . $this->getOffsetLimit(), $this->model->getConditionVariables());
     foreach ($data as $entryData) {
         if ($entryData['maintype'] == 'document') {
             $element = Document::getById($entryData['id']);
         } elseif ($entryData['maintype'] == 'asset') {
             $element = Asset::getById($entryData['id']);
         } elseif ($entryData['maintype'] == 'object') {
             $element = Object::getById($entryData['id']);
         } else {
             Logger::err("unknown maintype ");
         }
         if ($element) {
             $entry = new Search\Backend\Data();
             $entry->setId(new Search\Backend\Data\Id($element));
             $entry->setFullPath($entryData['fullpath']);
             $entry->setType($entryData['type']);
             $entry->setSubtype($entryData['subtype']);
             $entry->setUserOwner($entryData['userowner']);
             $entry->setUserModification($entryData['usermodification']);
             $entry->setCreationDate($entryData['creationdate']);
             $entry->setModificationDate($entryData['modificationdate']);
             $entry->setPublished($entryData['published'] === 0 ? false : true);
             $entries[] = $entry;
         }
     }
     $this->model->setEntries($entries);
     return $entries;
 }
Example #6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $validJobs = [];
     if ($input->getOption("job")) {
         $validJobs = explode(",", $input->getOption("job"));
     }
     // create manager
     $manager = Schedule\Manager\Factory::getManager("maintenance.pid");
     $manager->setValidJobs($validJobs);
     $manager->setForce((bool) $input->getOption("force"));
     // register scheduled tasks
     $manager->registerJob(new Schedule\Maintenance\Job("scheduledtasks", new Schedule\Task\Executor(), "execute"));
     $manager->registerJob(new Schedule\Maintenance\Job("logmaintenance", new \Pimcore\Log\Maintenance(), "mail"));
     $manager->registerJob(new Schedule\Maintenance\Job("cleanuplogfiles", new \Pimcore\Log\Maintenance(), "cleanupLogFiles"));
     $manager->registerJob(new Schedule\Maintenance\Job("httperrorlog", new \Pimcore\Log\Maintenance(), "httpErrorLogCleanup"));
     $manager->registerJob(new Schedule\Maintenance\Job("usagestatistics", new \Pimcore\Log\Maintenance(), "usageStatistics"));
     $manager->registerJob(new Schedule\Maintenance\Job("checkErrorLogsDb", new \Pimcore\Log\Maintenance(), "checkErrorLogsDb"));
     $manager->registerJob(new Schedule\Maintenance\Job("archiveLogEntries", new \Pimcore\Log\Maintenance(), "archiveLogEntries"));
     $manager->registerJob(new Schedule\Maintenance\Job("sanitycheck", "\\Pimcore\\Model\\Element\\Service", "runSanityCheck"));
     $manager->registerJob(new Schedule\Maintenance\Job("versioncleanup", new \Pimcore\Model\Version(), "maintenanceCleanUp"));
     $manager->registerJob(new Schedule\Maintenance\Job("versioncompress", new \Pimcore\Model\Version(), "maintenanceCompress"));
     $manager->registerJob(new Schedule\Maintenance\Job("redirectcleanup", "\\Pimcore\\Model\\Redirect", "maintenanceCleanUp"));
     $manager->registerJob(new Schedule\Maintenance\Job("cleanupbrokenviews", "\\Pimcore\\Db", "cleanupBrokenViews"));
     $manager->registerJob(new Schedule\Maintenance\Job("downloadmaxminddb", "\\Pimcore\\Update", "updateMaxmindDb"));
     $manager->registerJob(new Schedule\Maintenance\Job("cleanupcache", "\\Pimcore\\Model\\Cache", "maintenance"));
     $manager->registerJob(new Schedule\Maintenance\Job("tmpstorecleanup", "\\Pimcore\\Model\\Tool\\TmpStore", "cleanup"));
     $manager->registerJob(new Schedule\Maintenance\Job("imageoptimize", "\\Pimcore\\Model\\Asset\\Image\\Thumbnail\\Processor", "processOptimizeQueue"));
     \Pimcore::getEventManager()->trigger("system.maintenance", $manager);
     $manager->run();
     Logger::info("All maintenance-jobs finished!");
 }
Example #7
0
 /**
  * @param Model\Document $document
  * @throws \Zend_Json_Exception
  */
 protected function addPropertiesToDocument(Model\Document $document)
 {
     // properties
     if ($this->getParam("properties")) {
         $properties = [];
         // assign inherited properties
         foreach ($document->getProperties() as $p) {
             if ($p->isInherited()) {
                 $properties[$p->getName()] = $p;
             }
         }
         $propertiesData = \Zend_Json::decode($this->getParam("properties"));
         if (is_array($propertiesData)) {
             foreach ($propertiesData as $propertyName => $propertyData) {
                 $value = $propertyData["data"];
                 try {
                     $property = new Property();
                     $property->setType($propertyData["type"]);
                     $property->setName($propertyName);
                     $property->setCtype("document");
                     $property->setDataFromEditmode($value);
                     $property->setInheritable($propertyData["inheritable"]);
                     $properties[$propertyName] = $property;
                 } catch (\Exception $e) {
                     Logger::warning("Can't add " . $propertyName . " to document " . $document->getRealFullPath());
                 }
             }
         }
         if ($document->isAllowed("properties")) {
             $document->setProperties($properties);
         }
     }
     // force loading of properties
     $document->getProperties();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $status = ["success" => true];
     $config = $input->getArgument("config");
     if ($config) {
         $job = json_decode($config, true);
         if (is_array($job)) {
             if (isset($job["dry-run"])) {
                 // do not do anything here
                 Logger::info("skipped update job because it is in dry-run mode", $job);
             } elseif ($job["type"] == "files") {
                 Update::installData($job["revision"]);
             } elseif ($job["type"] == "clearcache") {
                 \Pimcore\Cache::clearAll();
             } elseif ($job["type"] == "preupdate") {
                 $status = Update::executeScript($job["revision"], "preupdate");
             } elseif ($job["type"] == "postupdate") {
                 $status = Update::executeScript($job["revision"], "postupdate");
             } elseif ($job["type"] == "cleanup") {
                 Update::cleanup();
             }
         }
     }
     $this->output->write(json_encode($status));
 }
Example #9
0
 /**
  * Save document to database
  *
  * @return void
  */
 public function save()
 {
     $data = [];
     $emailLog = get_object_vars($this->model);
     foreach ($emailLog as $key => $value) {
         if (in_array($key, $this->getValidTableColumns(self::$dbTable))) {
             // check if the getter exists
             $getter = "get" . ucfirst($key);
             if (!method_exists($this->model, $getter)) {
                 continue;
             }
             // get the value from the getter
             $value = $this->model->{$getter}();
             if (is_bool($value)) {
                 $value = (int) $value;
             } elseif (is_array($value)) {
                 //converts the dynamic params to a basic json string
                 $preparedData = self::createJsonLoggingObject($value);
                 $value = \Zend_Json::encode($preparedData);
             }
             $data[$key] = $value;
         }
     }
     try {
         $this->db->update(self::$dbTable, $data, $this->db->quoteInto("id = ?", $this->model->getId()));
     } catch (\Exception $e) {
         Logger::emerg('Could not Save emailLog with the id "' . $this->model->getId() . '" ');
     }
 }
Example #10
0
 /**
  * @param $object
  * @param bool $disableMappingExceptions
  * @param null $idMapper
  * @throws \Exception
  */
 public function reverseMap($object, $disableMappingExceptions = false, $idMapper = null)
 {
     $keys = get_object_vars($this);
     foreach ($keys as $key => $value) {
         $method = "set" . $key;
         if (method_exists($object, $method)) {
             $object->{$method}($value);
         }
     }
     //must be after generic setters above!!
     parent::reverseMap($object, $disableMappingExceptions, $idMapper);
     if (is_array($this->elements)) {
         foreach ($this->elements as $element) {
             $class = $object->getClass();
             $setter = "set" . ucfirst($element->name);
             if (method_exists($object, $setter)) {
                 $tag = $class->getFieldDefinition($element->name);
                 if ($tag) {
                     if ($class instanceof Model\Object\ClassDefinition\Data\Fieldcollections) {
                         $object->{$setter}($tag->getFromWebserviceImport($element->fieldcollection, $object, [], $idMapper));
                     } else {
                         $object->{$setter}($tag->getFromWebserviceImport($element->value, $object, [], $idMapper));
                     }
                 } else {
                     Logger::error("tag for field " . $element->name . " not found");
                 }
             } else {
                 if (!$disableMappingExceptions) {
                     throw new \Exception("No element [ " . $element->name . " ] of type [ " . $element->type . " ] found in class definition [" . $class->getId() . "] | " . $class->getName());
                 }
             }
         }
     }
 }
Example #11
0
 public function saveAction()
 {
     try {
         if ($this->getParam("id")) {
             $link = Document\Hardlink::getById($this->getParam("id"));
             $this->setValuesToDocument($link);
             $link->setModificationDate(time());
             $link->setUserModification($this->getUser()->getId());
             if ($this->getParam("task") == "unpublish") {
                 $link->setPublished(false);
             }
             if ($this->getParam("task") == "publish") {
                 $link->setPublished(true);
             }
             // only save when publish or unpublish
             if ($this->getParam("task") == "publish" && $link->isAllowed("publish") || $this->getParam("task") == "unpublish" && $link->isAllowed("unpublish")) {
                 $link->save();
                 $this->_helper->json(["success" => true]);
             }
         }
     } catch (\Exception $e) {
         Logger::log($e);
         if (\Pimcore\Tool\Admin::isExtJS6() && $e instanceof Element\ValidationException) {
             $this->_helper->json(["success" => false, "type" => "ValidationException", "message" => $e->getMessage(), "stack" => $e->getTraceAsString(), "code" => $e->getCode()]);
         }
         throw $e;
     }
     $this->_helper->json(false);
 }
Example #12
0
 /**
  * Deletes from database
  *
  * @return void
  */
 public function delete()
 {
     if ($this->model->getId() instanceof Model\Search\Backend\Data\Id) {
         $this->db->delete("search_backend_data", "id='" . $this->model->getId()->getId() . "' AND maintype ='" . $this->model->getId()->getType() . "'");
     } else {
         Logger::alert("Cannot delete Search\\Backend\\Data, ID is empty");
     }
 }
Example #13
0
 /**
  *
  */
 public function save()
 {
     try {
         $this->db->insert("users_permission_definitions", ["key" => $this->model->getKey()]);
     } catch (\Exception $e) {
         Logger::warn($e);
     }
 }
Example #14
0
 /**
  * @deprecated
  * @param $level
  */
 public function setFilterPriority($level)
 {
     // legacy ZF method
     $zendLoggerPsr3Mapping = Logger::getZendLoggerPsr3Mapping();
     if (isset($zendLoggerPsr3Mapping[$level])) {
         $level = $zendLoggerPsr3Mapping[$level];
         $this->setLevel($level);
     }
 }
Example #15
0
 /**
  * @param \Zend_Controller_Request_Abstract $request
  * @throws mixed
  */
 protected function _handleError(\Zend_Controller_Request_Abstract $request)
 {
     // remove zend error handler
     $front = \Zend_Controller_Front::getInstance();
     $front->unregisterPlugin("Zend_Controller_Plugin_ErrorHandler");
     $response = $this->getResponse();
     if ($response->isException() && !$this->_isInsideErrorHandlerLoop) {
         // get errorpage
         try {
             // enable error handler
             $front->setParam('noErrorHandler', false);
             $errorPath = Config::getSystemConfig()->documents->error_pages->default;
             if (Site::isSiteRequest()) {
                 $site = Site::getCurrentSite();
                 $errorPath = $site->getErrorDocument();
             }
             if (empty($errorPath)) {
                 $errorPath = "/";
             }
             $document = Document::getByPath($errorPath);
             if (!$document instanceof Document\Page) {
                 // default is home
                 $document = Document::getById(1);
             }
             if ($document instanceof Document\Page) {
                 $params = Tool::getRoutingDefaults();
                 if ($module = $document->getModule()) {
                     $params["module"] = $module;
                 }
                 if ($controller = $document->getController()) {
                     $params["controller"] = $controller;
                     $params["action"] = "index";
                 }
                 if ($action = $document->getAction()) {
                     $params["action"] = $action;
                 }
                 $this->setErrorHandler($params);
                 $request->setParam("document", $document);
                 \Zend_Registry::set("pimcore_error_document", $document);
                 // ensure that a viewRenderer exists, and is enabled
                 if (!\Zend_Controller_Action_HelperBroker::hasHelper("viewRenderer")) {
                     $viewRenderer = new \Pimcore\Controller\Action\Helper\ViewRenderer();
                     \Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
                 }
                 $viewRenderer = \Zend_Controller_Action_HelperBroker::getExistingHelper("viewRenderer");
                 $viewRenderer->setNoRender(false);
                 if ($viewRenderer->view === null) {
                     $viewRenderer->initView(PIMCORE_WEBSITE_PATH . "/views");
                 }
             }
         } catch (\Exception $e) {
             Logger::emergency("error page not found");
         }
     }
     // call default ZF error handler
     parent::_handleError($request);
 }
Example #16
0
 /**
  * @param $name
  */
 public static function getByName($name)
 {
     try {
         $config = new self();
         $config->setName($name);
         $config->getDao()->getByName();
         return $config;
     } catch (\Exception $e) {
         Logger::warning($e);
     }
 }
 public function generateSitemap()
 {
     $this->prepareSiteMapFolder();
     if (!is_null($this->sitemapDir)) {
         $hosts = $this->getValidHosts();
         if (is_array($hosts)) {
             foreach ($hosts as $hostName) {
                 $query = new \Zend_Search_Lucene_Search_Query_Boolean();
                 $hostTerm = new \Zend_Search_Lucene_Index_Term($hostName, 'host');
                 $hostQuery = new \Zend_Search_Lucene_Search_Query_Term($hostTerm);
                 $query->addSubquery($hostQuery, TRUE);
                 $hostTerm = new \Zend_Search_Lucene_Index_Term(TRUE, 'restrictionGroup_default');
                 $hostQuery = new \Zend_Search_Lucene_Search_Query_Term($hostTerm);
                 $query->addSubquery($hostQuery, TRUE);
                 $hits = $this->index->find($query);
                 $name = str_replace('.', '-', $hostName);
                 $filePath = $this->sitemapDir . '/sitemap-' . $name . '.xml';
                 $fh = fopen($filePath, 'w');
                 fwrite($fh, '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n");
                 fwrite($fh, '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
                 fwrite($fh, "\r\n");
                 for ($i = 0; $i < count($hits); $i++) {
                     $url = $hits[$i]->getDocument()->getField('url');
                     $uri = str_replace(array('?pimcore_outputfilters_disabled=1', '&pimcore_outputfilters_disabled=1'), '', $url->value);
                     fwrite($fh, '<url>' . "\r\n");
                     fwrite($fh, '    <loc>' . htmlspecialchars($uri, ENT_QUOTES) . '</loc>' . "\r\n");
                     fwrite($fh, '</url>' . "\r\n");
                 }
                 fwrite($fh, '</urlset>' . "\r\n");
                 fclose($fh);
             }
             $filePath = $this->sitemapDir . '/sitemap.xml';
             $fh = fopen($filePath, 'w');
             fwrite($fh, '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n");
             fwrite($fh, '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">');
             fwrite($fh, "\r\n");
             foreach ($hosts as $hostName) {
                 $name = str_replace('.', '-', $hostName);
                 //first host must be main domain - see hint in plugin settings
                 $currenthost = $hosts[0];
                 fwrite($fh, '<sitemap>' . "\r\n");
                 fwrite($fh, '    <loc>http://' . $currenthost . '/plugin/LuceneSearch/frontend/sitemap/?sitemap=sitemap-' . $name . '.xml' . '</loc>' . "\r\n");
                 fwrite($fh, '</sitemap>' . "\r\n");
                 \Pimcore\Logger::debug('LuceneSearch: ' . $hostName . ' for sitemap.xml added.');
             }
             fwrite($fh, '</sitemapindex>' . "\r\n");
             fclose($fh);
         } else {
             \Pimcore\Logger::debug('LuceneSearch: could not generate sitemaps, did not find any hosts in index.');
         }
     } else {
         \Pimcore\Logger::emerg('LuceneSearch: Cannot generate sitemap. Sitemap directory [ ' . $this->sitemapDir . ' ]  not available/not writeable and cannot be created');
     }
 }
Example #18
0
 /**
  * @param string $name
  * @return WebsiteSetting
  */
 public static function getByName($name, $siteId = null)
 {
     // create a tmp object to obtain the id
     $setting = new self();
     try {
         $setting->getDao()->getByName($name, $siteId);
     } catch (\Exception $e) {
         Logger::error($e);
         return null;
     }
     return $setting;
 }
Example #19
0
 /**
  * @return null|Adapter\GD|Adapter\Imagick
  * @throws \Exception
  */
 public static function create()
 {
     try {
         if (extension_loaded("imagick")) {
             return new Adapter\Imagick();
         } else {
             return new Adapter\GD();
         }
     } catch (\Exception $e) {
         Logger::crit("Unable to load image extensions: " . $e->getMessage());
         throw $e;
     }
 }
Example #20
0
 /**
  * @param string $provider
  * @param array|null $params
  * @return \Hybrid_Provider_Adapter
  */
 public static function authenticate($provider, $params = null)
 {
     self::init();
     $adapter = null;
     try {
         static::initializeHybridAuth();
         $provider = @trim(strip_tags($provider));
         $adapter = \Hybrid_Auth::authenticate($provider, $params);
     } catch (\Exception $e) {
         Logger::info($e);
     }
     return $adapter;
 }
Example #21
0
 public static function getDataFromEditmode($data, $pimcoreTagName)
 {
     $tagClass = '\\Pimcore\\Model\\Object\\ClassDefinition\\Data\\' . ucfirst($pimcoreTagName);
     if (\Pimcore\Tool::classExists($tagClass)) {
         /**
          * @var \Pimcore\Model\Object\ClassDefinition\Data $tag
          */
         $tag = new $tagClass();
         return $tag->getDataFromEditmode($data);
     }
     //purposely return null if there is no valid class, log a warning
     Logger::warning("No valid pimcore tag found for fieldType ({$pimcoreTagName}), check 'fieldType' exists, and 'type' is not being used in config");
     return null;
 }
Example #22
0
 /**
  * @param $permission
  * @return mixed|static
  * @throws \Exception
  */
 public static function create($permission)
 {
     if (!$permission) {
         throw new \Exception("No permisson defined.");
     }
     $permissionDefinition = static::getByKey($permission);
     if ($permissionDefinition instanceof self) {
         Logger::info("Permission {$permission} allready exists. Skipping creation.");
         return $permissionDefinition;
     } else {
         $permissionDefinition = new static();
         $permissionDefinition->setKey($permission);
         $permissionDefinition->save();
         return $permissionDefinition;
     }
 }
Example #23
0
 /**
  * Save object to database
  *
  * @return void
  */
 public function save()
 {
     $version = get_object_vars($this->model);
     foreach ($version as $key => $value) {
         if (in_array($key, $this->getValidTableColumns("recyclebin"))) {
             $data[$key] = $value;
         }
     }
     try {
         $this->db->insert("recyclebin", $data);
         $this->model->setId($this->db->lastInsertId());
     } catch (\Exception $e) {
         Logger::error($e);
     }
     return true;
 }
Example #24
0
 /**
  *
  */
 public function writeLog()
 {
     $code = (string) $this->getResponse()->getHttpResponseCode();
     $db = \Pimcore\Db::get();
     try {
         $uri = $this->getRequest()->getScheme() . "://" . $this->getRequest()->getHttpHost() . $this->getRequest()->getRequestUri();
         $exists = $db->fetchOne("SELECT date FROM http_error_log WHERE uri = ?", $uri);
         if ($exists) {
             $db->query("UPDATE http_error_log SET `count` = `count` + 1, date = ? WHERE uri = ?", [time(), $uri]);
         } else {
             $db->insert("http_error_log", ["uri" => $uri, "code" => (int) $code, "parametersGet" => serialize($_GET), "parametersPost" => serialize($_POST), "cookies" => serialize($_COOKIE), "serverVars" => serialize($_SERVER), "date" => time(), "count" => 1]);
         }
     } catch (\Exception $e) {
         Logger::error("Unable to log http error");
         Logger::error($e);
     }
 }
Example #25
0
 /**
  * @return bool
  */
 public static function getDefaultAdapter()
 {
     $adapters = ["Ffmpeg"];
     foreach ($adapters as $adapter) {
         $adapterClass = "\\Pimcore\\Video\\Adapter\\" . $adapter;
         if (Tool::classExists($adapterClass)) {
             try {
                 $adapter = new $adapterClass();
                 if ($adapter->isAvailable()) {
                     return $adapter;
                 }
             } catch (\Exception $e) {
                 Logger::warning($e);
             }
         }
     }
     return null;
 }
Example #26
0
 /**
  * @return bool
  */
 public static function getDefaultAdapter()
 {
     $adapters = array("LibreOffice", "Ghostscript");
     foreach ($adapters as $adapter) {
         $adapterClass = "\\Pimcore\\Document\\Adapter\\" . $adapter;
         if (Tool::classExists($adapterClass)) {
             try {
                 $adapter = new $adapterClass();
                 if ($adapter->isAvailable()) {
                     return $adapter;
                 }
             } catch (\Exception $e) {
                 \Logger::warning($e);
             }
         }
     }
     return null;
 }
Example #27
0
 /**
  * Returns the children of the asset if the asset is a folder
  *
  * @return array
  */
 public function getChildren()
 {
     $children = [];
     if ($this->asset->hasChilds()) {
         foreach ($this->asset->getChilds() as $child) {
             if ($child->isAllowed("view")) {
                 try {
                     if ($child = $this->getChild($child)) {
                         $children[] = $child;
                     }
                 } catch (\Exception $e) {
                     Logger::warning($e);
                 }
             }
         }
     }
     return $children;
 }
Example #28
0
 protected function buildPdf(Document\PrintAbstract $document, $config)
 {
     $web2PrintConfig = Config::getWeb2PrintConfig();
     $params = [];
     $params['printermarks'] = $config->printermarks == "true";
     $params['screenResolutionImages'] = $config->screenResolutionImages == "true";
     $this->updateStatus($document->getId(), 10, "start_html_rendering");
     $html = $document->renderDocument($params);
     $this->updateStatus($document->getId(), 40, "finished_html_rendering");
     $filePath = PIMCORE_TEMPORARY_DIRECTORY . "/pdf-reactor-input-" . $document->getId() . ".html";
     file_put_contents($filePath, $html);
     $html = null;
     $this->updateStatus($document->getId(), 45, "saved_html_file");
     ini_set("default_socket_timeout", 3000);
     ini_set('max_input_time', -1);
     include_once 'Pimcore/Web2Print/Processor/api/v' . $web2PrintConfig->get('pdfreactorVersion', '8.0') . '/PDFreactor.class.php';
     $port = (string) $web2PrintConfig->pdfreactorServerPort ? (string) $web2PrintConfig->pdfreactorServerPort : "9423";
     $pdfreactor = new \PDFreactor("http://" . $web2PrintConfig->pdfreactorServer . ":" . $port . "/service/rest");
     $filePath = str_replace(PIMCORE_DOCUMENT_ROOT, "", $filePath);
     $reactorConfig = ["document" => (string) $web2PrintConfig->pdfreactorBaseUrl . $filePath, "baseURL" => (string) $web2PrintConfig->pdfreactorBaseUrl, "author" => $config->author ? $config->author : "", "title" => $config->title ? $config->title : "", "addLinks" => $config->links == "true", "addBookmarks" => $config->bookmarks == "true", "javaScriptMode" => $config->javaScriptMode, "viewerPreferences" => [$config->viewerPreference], "defaultColorSpace" => $config->colorspace, "encryption" => $config->encryption, "addTags" => $config->tags == "true", "logLevel" => $config->loglevel];
     if (trim($web2PrintConfig->pdfreactorLicence)) {
         $reactorConfig["licenseKey"] = trim($web2PrintConfig->pdfreactorLicence);
     }
     try {
         $progress = new \stdClass();
         $progress->finished = false;
         $processId = $pdfreactor->convertAsync($reactorConfig);
         while (!$progress->finished) {
             $progress = $pdfreactor->getProgress($processId);
             $this->updateStatus($document->getId(), 50 + $progress->progress / 2, "pdf_conversion");
             Logger::info("PDF converting progress: " . $progress->progress . "%");
             sleep(2);
         }
         $this->updateStatus($document->getId(), 100, "saving_pdf_document");
         $result = $pdfreactor->getDocument($processId);
         $pdf = base64_decode($result->document);
     } catch (\Exception $e) {
         Logger::error($e);
         $document->setLastGenerateMessage($e->getMessage());
         throw new \Exception("Error during REST-Request:" . $e->getMessage());
     }
     $document->setLastGenerateMessage("");
     return $pdf;
 }
Example #29
0
 /**
  * Moves a file/directory
  *
  * @param string $sourcePath
  * @param string $destinationPath
  * @return void
  */
 public function move($sourcePath, $destinationPath)
 {
     $nameParts = explode("/", $sourcePath);
     $nameParts[count($nameParts) - 1] = Element\Service::getValidKey($nameParts[count($nameParts) - 1], "asset");
     $sourcePath = implode("/", $nameParts);
     $nameParts = explode("/", $destinationPath);
     $nameParts[count($nameParts) - 1] = Element\Service::getValidKey($nameParts[count($nameParts) - 1], "asset");
     $destinationPath = implode("/", $nameParts);
     try {
         if (dirname($sourcePath) == dirname($destinationPath)) {
             $asset = null;
             if ($asset = Asset::getByPath("/" . $destinationPath)) {
                 // If we got here, this means the destination exists, and needs to be overwritten
                 $sourceAsset = Asset::getByPath("/" . $sourcePath);
                 $asset->setData($sourceAsset->getData());
                 $sourceAsset->delete();
             }
             // see: Asset\WebDAV\File::delete() why this is necessary
             $log = Asset\WebDAV\Service::getDeleteLog();
             if (!$asset && array_key_exists("/" . $destinationPath, $log)) {
                 $asset = \Pimcore\Tool\Serialize::unserialize($log["/" . $destinationPath]["data"]);
                 if ($asset) {
                     $sourceAsset = Asset::getByPath("/" . $sourcePath);
                     $asset->setData($sourceAsset->getData());
                     $sourceAsset->delete();
                 }
             }
             if (!$asset) {
                 $asset = Asset::getByPath("/" . $sourcePath);
             }
             $asset->setFilename(basename($destinationPath));
         } else {
             $asset = Asset::getByPath("/" . $sourcePath);
             $parent = Asset::getByPath("/" . dirname($destinationPath));
             $asset->setPath($parent->getRealFullPath() . "/");
             $asset->setParentId($parent->getId());
         }
         $user = \Pimcore\Tool\Admin::getCurrentUser();
         $asset->setUserModification($user->getId());
         $asset->save();
     } catch (\Exception $e) {
         Logger::error($e);
     }
 }
Example #30
0
 /**
  * @static
  * @throws \Exception
  * @return User
  */
 public static function authenticateHttpBasic()
 {
     // we're using Sabre\HTTP for basic auth
     $request = \Sabre\HTTP\Sapi::getRequest();
     $response = new \Sabre\HTTP\Response();
     $auth = new \Sabre\HTTP\Auth\Basic(Tool::getHostname(), $request, $response);
     $result = $auth->getCredentials();
     if (is_array($result)) {
         list($username, $password) = $result;
         $user = self::authenticatePlaintext($username, $password);
         if ($user) {
             return $user;
         }
     }
     $auth->requireLogin();
     $response->setBody("Authentication required");
     Logger::error("Authentication Basic (WebDAV) required");
     \Sabre\HTTP\Sapi::sendResponse($response);
     die;
 }