상속: extends Pimcore\Model\Element\Service
예제 #1
0
 public function importDocuments()
 {
     $file = sprintf('%s/documents.json', $this->baseDir);
     $docs = new \Zend_Config_Json($file);
     foreach ($docs as $def) {
         $def = $def->toArray();
         $parent = Document::getByPath($def['parent']);
         unset($def['parent']);
         if (!$parent) {
             $parent = Document::getById(1);
         }
         $path = $parent->getFullPath() . '/' . $def['key'];
         if (Document\Service::pathExists($path)) {
             $doc = Document::getByPath($path);
         } else {
             $docClass = '\\Pimcore\\Model\\Document\\' . ucfirst($def['type']);
             /** @var Document $doc */
             $doc = $docClass::create($parent->getId(), $def, false);
             $doc->setUserOwner(self::getUser()->getId());
             $doc->setUserModification(self::getUser()->getId());
         }
         $doc->setValues($def);
         $doc->setPublished(true);
         $doc->save();
     }
 }
예제 #2
0
 public function copyAction()
 {
     $success = false;
     $sourceId = intval($this->getParam("sourceId"));
     $source = Document::getById($sourceId);
     $session = Session::get("pimcore_copy");
     $targetId = intval($this->getParam("targetId"));
     if ($this->getParam("targetParentId")) {
         $sourceParent = Document::getById($this->getParam("sourceParentId"));
         // this is because the key can get the prefix "_copy" if the target does already exists
         if ($session->{$this->getParam("transactionId")}["parentId"]) {
             $targetParent = Document::getById($session->{$this->getParam("transactionId")}["parentId"]);
         } else {
             $targetParent = Document::getById($this->getParam("targetParentId"));
         }
         $targetPath = preg_replace("@^" . $sourceParent->getFullPath() . "@", $targetParent . "/", $source->getPath());
         $target = Document::getByPath($targetPath);
     } else {
         $target = Document::getById($targetId);
     }
     if ($target instanceof Document) {
         if ($target->isAllowed("create")) {
             if ($source != null) {
                 if ($this->getParam("type") == "child") {
                     $enableInheritance = $this->getParam("enableInheritance") == "true" ? true : false;
                     $resetIndex = $this->getParam("resetIndex") == "true" ? true : false;
                     $newDocument = $this->_documentService->copyAsChild($target, $source, $enableInheritance, $resetIndex);
                     $session->{$this->getParam("transactionId")}["idMapping"][(int) $source->getId()] = (int) $newDocument->getId();
                     // this is because the key can get the prefix "_copy" if the target does already exists
                     if ($this->getParam("saveParentId")) {
                         $session->{$this->getParam("transactionId")}["parentId"] = $newDocument->getId();
                     }
                     Session::writeClose();
                 } else {
                     if ($this->getParam("type") == "replace") {
                         $this->_documentService->copyContents($target, $source);
                     }
                 }
                 $success = true;
             } else {
                 \Logger::error("prevended copy/paste because document with same path+key already exists in this location");
             }
         } else {
             \Logger::error("could not execute copy/paste because of missing permissions on target [ " . $targetId . " ]");
             $this->_helper->json(array("success" => false, "message" => "missing_permission"));
         }
     }
     $this->_helper->json(array("success" => $success));
 }
예제 #3
0
    /**
     * @param \Zend_Controller_Request_Abstract $request
     */
    public function postDispatch(\Zend_Controller_Request_Abstract $request)
    {
        $conf = Config::getSystemConfig();
        // add scripts to editmode
        if (\Pimcore\Tool\Admin::isExtJS6()) {
            $editmodeLibraries = array("/pimcore/static6/js/pimcore/namespace.js", "/pimcore/static6/js/lib/prototype-light.js", "/pimcore/static6/js/lib/jquery.min.js", "/pimcore/static6/js/lib/ext/ext-all.js", "/pimcore/static6/js/lib/ckeditor/ckeditor.js");
            $editmodeScripts = array("/pimcore/static6/js/pimcore/functions.js", "/pimcore/static6/js/pimcore/element/tag/imagehotspotmarkereditor.js", "/pimcore/static6/js/pimcore/element/tag/imagecropper.js", "/pimcore/static6/js/pimcore/document/edit/helper.js", "/pimcore/static6/js/pimcore/document/edit/dnd.js", "/pimcore/static6/js/pimcore/document/tag.js", "/pimcore/static6/js/pimcore/document/tags/block.js", "/pimcore/static6/js/pimcore/document/tags/date.js", "/pimcore/static6/js/pimcore/document/tags/href.js", "/pimcore/static6/js/pimcore/document/tags/multihref.js", "/pimcore/static6/js/pimcore/document/tags/checkbox.js", "/pimcore/static6/js/pimcore/document/tags/image.js", "/pimcore/static6/js/pimcore/document/tags/input.js", "/pimcore/static6/js/pimcore/document/tags/link.js", "/pimcore/static6/js/pimcore/document/tags/select.js", "/pimcore/static6/js/pimcore/document/tags/snippet.js", "/pimcore/static6/js/pimcore/document/tags/textarea.js", "/pimcore/static6/js/pimcore/document/tags/numeric.js", "/pimcore/static6/js/pimcore/document/tags/wysiwyg.js", "/pimcore/static6/js/pimcore/document/tags/renderlet.js", "/pimcore/static6/js/pimcore/document/tags/table.js", "/pimcore/static6/js/pimcore/document/tags/video.js", "/pimcore/static6/js/pimcore/document/tags/multiselect.js", "/pimcore/static6/js/pimcore/document/tags/areablock.js", "/pimcore/static6/js/pimcore/document/tags/area.js", "/pimcore/static6/js/pimcore/document/tags/pdf.js", "/pimcore/static6/js/pimcore/document/edit/helper.js");
            $editmodeStylesheets = array("/pimcore/static6/css/icons.css", "/pimcore/static6/css/editmode.css?_dc=" . time());
        } else {
            $editmodeLibraries = array("/pimcore/static/js/pimcore/namespace.js", "/pimcore/static/js/lib/prototype-light.js", "/pimcore/static/js/lib/jquery.min.js", "/pimcore/static/js/lib/ext/adapter/jquery/ext-jquery-adapter-debug.js", "/pimcore/static/js/lib/ext/ext-all-debug.js", "/pimcore/static/js/lib/ext-plugins/ux/Spinner.js", "/pimcore/static/js/lib/ext-plugins/ux/SpinnerField.js", "/pimcore/static/js/lib/ext-plugins/ux/MultiSelect.js", "/pimcore/static/js/lib/ext-plugins/GridRowOrder/roworder.js", "/pimcore/static/js/lib/ckeditor/ckeditor.js", "/pimcore/static/js/pimcore/libfixes.js");
            $editmodeScripts = array("/pimcore/static/js/pimcore/functions.js", "/pimcore/static/js/pimcore/element/tag/imagehotspotmarkereditor.js", "/pimcore/static/js/pimcore/element/tag/imagecropper.js", "/pimcore/static/js/pimcore/document/edit/helper.js", "/pimcore/static/js/pimcore/document/edit/dnd.js", "/pimcore/static/js/pimcore/document/tag.js", "/pimcore/static/js/pimcore/document/tags/block.js", "/pimcore/static/js/pimcore/document/tags/date.js", "/pimcore/static/js/pimcore/document/tags/href.js", "/pimcore/static/js/pimcore/document/tags/multihref.js", "/pimcore/static/js/pimcore/document/tags/checkbox.js", "/pimcore/static/js/pimcore/document/tags/image.js", "/pimcore/static/js/pimcore/document/tags/input.js", "/pimcore/static/js/pimcore/document/tags/link.js", "/pimcore/static/js/pimcore/document/tags/select.js", "/pimcore/static/js/pimcore/document/tags/snippet.js", "/pimcore/static/js/pimcore/document/tags/textarea.js", "/pimcore/static/js/pimcore/document/tags/numeric.js", "/pimcore/static/js/pimcore/document/tags/wysiwyg.js", "/pimcore/static/js/pimcore/document/tags/renderlet.js", "/pimcore/static/js/pimcore/document/tags/table.js", "/pimcore/static/js/pimcore/document/tags/video.js", "/pimcore/static/js/pimcore/document/tags/multiselect.js", "/pimcore/static/js/pimcore/document/tags/areablock.js", "/pimcore/static/js/pimcore/document/tags/area.js", "/pimcore/static/js/pimcore/document/tags/pdf.js", "/pimcore/static/js/pimcore/document/edit/helper.js");
            $editmodeStylesheets = array("/pimcore/static/css/icons.css", "/pimcore/static/css/editmode.css?asd=" . time());
        }
        //add plugin editmode JS and CSS
        try {
            $pluginConfigs = ExtensionManager::getPluginConfigs();
            $jsPaths = array();
            $cssPaths = array();
            if (!empty($pluginConfigs)) {
                //registering plugins
                foreach ($pluginConfigs as $p) {
                    $pluginJsPaths = array();
                    if (array_key_exists("pluginDocumentEditmodeJsPaths", $p['plugin']) && is_array($p['plugin']['pluginDocumentEditmodeJsPaths']) && isset($p['plugin']['pluginDocumentEditmodeJsPaths']['path'])) {
                        if (is_array($p['plugin']['pluginDocumentEditmodeJsPaths']['path'])) {
                            $pluginJsPaths = $p['plugin']['pluginDocumentEditmodeJsPaths']['path'];
                        } else {
                            if ($p['plugin']['pluginDocumentEditmodeJsPaths']['path'] != null) {
                                $pluginJsPaths[] = $p['plugin']['pluginDocumentEditmodeJsPaths']['path'];
                            }
                        }
                    }
                    //manipulate path for frontend
                    if (is_array($pluginJsPaths) and count($pluginJsPaths) > 0) {
                        for ($i = 0; $i < count($pluginJsPaths); $i++) {
                            if (is_file(PIMCORE_PLUGINS_PATH . $pluginJsPaths[$i])) {
                                $jsPaths[] = "/plugins" . $pluginJsPaths[$i];
                            }
                        }
                    }
                    $pluginCssPaths = array();
                    if (array_key_exists("pluginDocumentEditmodeCssPaths", $p['plugin']) && is_array($p['plugin']['pluginDocumentEditmodeCssPaths']) && isset($p['plugin']['pluginDocumentEditmodeCssPaths']['path'])) {
                        if (is_array($p['plugin']['pluginDocumentEditmodeCssPaths']['path'])) {
                            $pluginCssPaths = $p['plugin']['pluginDocumentEditmodeCssPaths']['path'];
                        } else {
                            if ($p['plugin']['pluginDocumentEditmodeCssPaths']['path'] != null) {
                                $pluginCssPaths[] = $p['plugin']['pluginDocumentEditmodeCssPaths']['path'];
                            }
                        }
                    }
                    //manipulate path for frontend
                    if (is_array($pluginCssPaths) and count($pluginCssPaths) > 0) {
                        for ($i = 0; $i < count($pluginCssPaths); $i++) {
                            if (is_file(PIMCORE_PLUGINS_PATH . $pluginCssPaths[$i])) {
                                $cssPaths[] = "/plugins" . $pluginCssPaths[$i];
                            }
                        }
                    }
                }
            }
            $editmodeScripts = array_merge($editmodeScripts, $jsPaths);
            $editmodeStylesheets = array_merge($editmodeStylesheets, $cssPaths);
        } catch (\Exception $e) {
            \Logger::alert("there is a problem with the plugin configuration");
            \Logger::alert($e);
        }
        $editmodeHeadHtml = "\n\n\n<!-- pimcore editmode -->\n";
        // include stylesheets
        foreach ($editmodeStylesheets as $sheet) {
            $editmodeHeadHtml .= '<link rel="stylesheet" type="text/css" href="' . $sheet . '?_dc=' . Version::$revision . '" />';
            $editmodeHeadHtml .= "\n";
        }
        $editmodeHeadHtml .= "\n\n";
        $editmodeHeadHtml .= '<script type="text/javascript">var jQueryPreviouslyLoaded = (typeof jQuery == "undefined") ? false : true;</script>' . "\n";
        // include script libraries
        foreach ($editmodeLibraries as $script) {
            $editmodeHeadHtml .= '<script type="text/javascript" src="' . $script . '?_dc=' . Version::$revision . '"></script>';
            $editmodeHeadHtml .= "\n";
        }
        // combine the pimcore scripts in non-devmode
        if ($conf->general->devmode) {
            foreach ($editmodeScripts as $script) {
                $editmodeHeadHtml .= '<script type="text/javascript" src="' . $script . '?_dc=' . Version::$revision . '"></script>';
                $editmodeHeadHtml .= "\n";
            }
        } else {
            $scriptContents = "";
            foreach ($editmodeScripts as $scriptUrl) {
                $scriptContents .= file_get_contents(PIMCORE_DOCUMENT_ROOT . $scriptUrl) . "\n\n\n";
            }
            $editmodeHeadHtml .= '<script type="text/javascript" src="' . \Pimcore\Tool\Admin::getMinimizedScriptPath($scriptContents) . '?_dc=' . Version::$revision . '"></script>' . "\n";
        }
        $user = \Pimcore\Tool\Authentication::authenticateSession();
        $lang = $user->getLanguage();
        $editmodeHeadHtml .= '<script type="text/javascript" src="/admin/misc/json-translations-system/language/' . $lang . '/?_dc=' . Version::$revision . '"></script>' . "\n";
        $editmodeHeadHtml .= '<script type="text/javascript" src="/admin/misc/json-translations-admin/language/' . $lang . '/?_dc=' . Version::$revision . '"></script>' . "\n";
        $editmodeHeadHtml .= "\n\n";
        // set var for editable configurations which is filled by Document\Tag::admin()
        $editmodeHeadHtml .= '<script type="text/javascript">
            var editableConfigurations = new Array();
            var pimcore_document_id = ' . $request->getParam("document")->getId() . ';

            if(jQueryPreviouslyLoaded) {
                jQuery.noConflict( true );
            }
        </script>';
        $editmodeHeadHtml .= "\n\n<!-- /pimcore editmode -->\n\n\n";
        // add scripts in html header for pages in editmode
        if ($this->controller->editmode && Document\Service::isValidType($this->controller->document->getType())) {
            //ckogler
            include_once "simple_html_dom.php";
            $body = $this->getResponse()->getBody();
            $html = str_get_html($body);
            if ($html) {
                $htmlElement = $html->find("html", 0);
                $head = $html->find("head", 0);
                $bodyElement = $html->find("body", 0);
                // if there's no head and no body, create a wrapper including these elements
                // add html headers for snippets in editmode, so there is no problem with javascript
                if (!$head && !$bodyElement && !$htmlElement) {
                    $body = "<!DOCTYPE html>\n<html>\n<head></head><body>" . $body . "</body></html>";
                    $html = str_get_html($body);
                    // get them again with the updated html markup
                    $htmlElement = $html->find("html", 0);
                    $head = $html->find("head", 0);
                    $bodyElement = $html->find("body", 0);
                }
                if ($head && $bodyElement && $htmlElement) {
                    $head->innertext = $head->innertext . "\n\n" . $editmodeHeadHtml;
                    $bodyElement->onunload = "pimcoreOnUnload();";
                    if (\Pimcore\Tool\Admin::isExtJS6()) {
                        $bodyElement->innertext = $bodyElement->innertext . "\n\n" . '<script type="text/javascript" src="/pimcore/static6/js/pimcore/document/edit/startup.js?_dc=' . Version::$revision . '"></script>' . "\n\n";
                    } else {
                        $bodyElement->innertext = $bodyElement->innertext . "\n\n" . '<script type="text/javascript" src="/pimcore/static/js/pimcore/document/edit/startup.js?_dc=' . Version::$revision . '"></script>' . "\n\n";
                    }
                    $body = $html->save();
                    $this->getResponse()->setBody($body);
                } else {
                    $this->getResponse()->setBody('<div style="font-size:30px; font-family: Arial; font-weight:bold; color:red; text-align: center; margin: 40px 0">You have to define a &lt;html&gt;, &lt;head&gt;, &lt;body&gt;<br />HTML-tag in your view/layout markup!</div>');
                }
                $html->clear();
                unset($html);
            }
        }
        // IE compatibility
        //$this->getResponse()->setHeader("X-UA-Compatible", "IE=8; IE=9", true);
    }
 /** end point for document related data.
  * - get document by id
  *      GET http://[YOUR-DOMAIN]/webservice/rest/document/id/1281?apikey=[API-KEY]
  *      returns json-encoded document data.
  * - delete document by id
  *      DELETE http://[YOUR-DOMAIN]/webservice/rest/document/id/1281?apikey=[API-KEY]
  *      returns json encoded success value
  * - create document
  *      PUT or POST http://[YOUR-DOMAIN]/webservice/rest/document?apikey=[API-KEY]
  *      body: json-encoded document data in the same format as returned by get document by id
  *              but with missing id field or id set to 0
  *      returns json encoded document id
  * - update document
  *      PUT or POST http://[YOUR-DOMAIN]/webservice/rest/document?apikey=[API-KEY]
  *      body: same as for create document but with object id
  *      returns json encoded success value
  * @throws \Exception
  */
 public function documentAction()
 {
     $id = $this->getParam("id");
     $success = false;
     try {
         if ($this->isGet()) {
             $doc = Document::getById($id);
             if (!$doc) {
                 $this->encoder->encode(array("success" => false, "msg" => "Document does not exist", "code" => self::ELEMENT_DOES_NOT_EXIST));
                 return;
             }
             $this->checkPermission($doc, "get");
             if ($doc) {
                 $type = $doc->getType();
                 $getter = "getDocument" . ucfirst($type) . "ById";
                 if (method_exists($this->service, $getter)) {
                     $object = $this->service->{$getter}($id);
                 } else {
                     // check if the getter is implemented by a plugin
                     $class = "\\Pimcore\\Model\\Webservice\\Data\\Document\\" . ucfirst($type) . "\\Out";
                     if (Tool::classExists($class)) {
                         Document\Service::loadAllDocumentFields($doc);
                         $object = Webservice\Data\Mapper::map($doc, $class, "out");
                     } else {
                         throw new \Exception("unknown type");
                     }
                 }
             }
             if (!$object) {
                 throw new \Exception("could not find document");
             }
             @$this->encoder->encode(array("success" => true, "data" => $object));
             return;
         } else {
             if ($this->isDelete()) {
                 $doc = Document::getById($id);
                 if ($doc) {
                     $this->checkPermission($doc, "delete");
                 }
                 $success = $this->service->deleteDocument($id);
                 $this->encoder->encode(array("success" => $success));
                 return;
             } else {
                 if ($this->isPost() || $this->isPut()) {
                     $data = file_get_contents("php://input");
                     $data = \Zend_Json::decode($data);
                     $type = $data["type"];
                     $id = null;
                     $typeUpper = ucfirst($type);
                     $className = "\\Pimcore\\Model\\Webservice\\Data\\Document\\" . $typeUpper . "\\In";
                     if ($data["id"]) {
                         $doc = Document::getById($data["id"]);
                         if ($doc) {
                             $this->checkPermission($doc, "update");
                         }
                         $isUpdate = true;
                         $setter = "updateDocument" . $typeUpper;
                         if (!method_exists($this->service, $setter)) {
                             throw new \Exception("method does not exist " . $setter);
                         }
                         $wsData = self::fillWebserviceData($className, $data);
                         $success = $this->service->{$setter}($wsData);
                     } else {
                         $setter = "createDocument" . $typeUpper;
                         if (!method_exists($this->service, $setter)) {
                             throw new \Exception("method does not exist " . $setter);
                         }
                         $wsData = self::fillWebserviceData($className, $data);
                         $doc = new Document();
                         $doc->setId($wsData->parentId);
                         $this->checkPermission($doc, "create");
                         $id = $this->service->{$setter}($wsData);
                     }
                     if (!$isUpdate) {
                         $success = $id != null;
                     }
                     if ($success && !$isUpdate) {
                         $this->encoder->encode(array("success" => $success, "id" => $id));
                     } else {
                         $this->encoder->encode(array("success" => $success));
                     }
                     return;
                 }
             }
         }
     } catch (\Exception $e) {
         $this->encoder->encode(array("success" => false, "msg" => (string) $e));
     }
     $this->encoder->encode(array("success" => false));
 }
예제 #5
0
 public function replaceAssignmentsAction()
 {
     $success = false;
     $message = "";
     $element = Element\Service::getElementById($this->getParam("type"), $this->getParam("id"));
     $sourceEl = Element\Service::getElementById($this->getParam("sourceType"), $this->getParam("sourceId"));
     $targetEl = Element\Service::getElementById($this->getParam("targetType"), $this->getParam("targetId"));
     if ($element && $sourceEl && $targetEl && $this->getParam("sourceType") == $this->getParam("targetType") && $sourceEl->getType() == $targetEl->getType()) {
         $rewriteConfig = [$this->getParam("sourceType") => [$sourceEl->getId() => $targetEl->getId()]];
         if ($element instanceof Document) {
             $element = Document\Service::rewriteIds($element, $rewriteConfig);
         } elseif ($element instanceof Object\AbstractObject) {
             $element = Object\Service::rewriteIds($element, $rewriteConfig);
         } elseif ($element instanceof Asset) {
             $element = Asset\Service::rewriteIds($element, $rewriteConfig);
         }
         $element->setUserModification($this->getUser()->getId());
         $element->save();
         $success = true;
     } else {
         $message = "source-type and target-type do not match";
     }
     $this->_helper->json(["success" => $success, "message" => $message]);
 }
예제 #6
0
 /**
  * Returns the full path of the document including the key (path+key)
  *
  * @return string
  */
 public function getFullPath()
 {
     // check if this document is also the site root, if so return /
     try {
         if (Site::isSiteRequest()) {
             $site = Site::getCurrentSite();
             if ($site instanceof Site) {
                 if ($site->getRootDocument()->getId() == $this->getId()) {
                     return "/";
                 }
             }
         }
     } catch (\Exception $e) {
         \Logger::error($e);
     }
     // @TODO please forgive me, this is the dirtiest hack I've ever made :(
     // if you got confused by this functionality drop me a line and I'll buy you some beers :)
     // this is for the case that a link points to a document outside of the current site
     // in this case we look for a hardlink in the current site which points to the current document
     // why this could happen: we have 2 sites, in one site there's a hardlink to the other site and on a page inside
     // the hardlink there are snippets embedded and this snippets have links pointing to a document which is also
     // inside the hardlink scope, but this is an ID link, so we cannot rewrite the link the usual way because in the
     // snippet / link we don't know anymore that whe a inside a hardlink wrapped document
     if (!\Pimcore::inAdmin() && Site::isSiteRequest() && !FrontendTool::isDocumentInCurrentSite($this)) {
         $documentService = new Document\Service();
         $parent = $this;
         while ($parent) {
             if ($hardlinkId = $documentService->getDocumentIdFromHardlinkInSameSite(Site::getCurrentSite(), $parent)) {
                 $hardlink = Document::getById($hardlinkId);
                 if (FrontendTool::isDocumentInCurrentSite($hardlink)) {
                     $siteRootPath = Site::getCurrentSite()->getRootPath();
                     $siteRootPath = preg_quote($siteRootPath);
                     $hardlinkPath = preg_replace("@^" . $siteRootPath . "@", "", $hardlink->getRealFullPath());
                     return preg_replace("@^" . preg_quote($parent->getRealFullPath()) . "@", $hardlinkPath, $this->getRealFullPath());
                     break;
                 }
             }
             $parent = $parent->getParent();
         }
         $config = \Pimcore\Config::getSystemConfig();
         $front = \Zend_Controller_Front::getInstance();
         $scheme = ($front->getRequest()->isSecure() ? "https" : "http") . "://";
         if ($site = FrontendTool::getSiteForDocument($this)) {
             if ($site->getMainDomain()) {
                 // check if current document is the root of the different site, if so, preg_replace below doesn't work, so just return /
                 if ($site->getRootDocument()->getId() == $this->getId()) {
                     return $scheme . $site->getMainDomain() . "/";
                 }
                 return $scheme . $site->getMainDomain() . preg_replace("@^" . $site->getRootPath() . "/@", "/", $this->getRealFullPath());
             }
         }
         if ($config->general->domain) {
             return $scheme . $config->general->domain . $this->getRealFullPath();
         }
     }
     $path = $this->getPath() . $this->getKey();
     return $path;
 }
예제 #7
0
 /**
  * @return void
  */
 public function findAction()
 {
     $user = $this->getUser();
     $query = $this->getParam("query");
     if ($query == "*") {
         $query = "";
     }
     $query = str_replace("%", "*", $query);
     $types = explode(",", $this->getParam("type"));
     $subtypes = explode(",", $this->getParam("subtype"));
     $classnames = explode(",", $this->getParam("class"));
     if ($this->getParam("type") == "object" && is_array($classnames) && empty($classnames[0])) {
         $subtypes = array("object", "variant", "folder");
     }
     $offset = intval($this->getParam("start"));
     $limit = intval($this->getParam("limit"));
     $offset = $offset ? $offset : 0;
     $limit = $limit ? $limit : 50;
     $searcherList = new Data\Listing();
     $conditionParts = array();
     $db = \Pimcore\Db::get();
     //exclude forbidden assets
     if (in_array("asset", $types)) {
         if (!$user->isAllowed("assets")) {
             $forbiddenConditions[] = " `type` != 'asset' ";
         } else {
             $forbiddenAssetPaths = Element\Service::findForbiddenPaths("asset", $user);
             if (count($forbiddenAssetPaths) > 0) {
                 for ($i = 0; $i < count($forbiddenAssetPaths); $i++) {
                     $forbiddenAssetPaths[$i] = " (maintype = 'asset' AND fullpath not like " . $db->quote($forbiddenAssetPaths[$i] . "%") . ")";
                 }
                 $forbiddenConditions[] = implode(" AND ", $forbiddenAssetPaths);
             }
         }
     }
     //exclude forbidden documents
     if (in_array("document", $types)) {
         if (!$user->isAllowed("documents")) {
             $forbiddenConditions[] = " `type` != 'document' ";
         } else {
             $forbiddenDocumentPaths = Element\Service::findForbiddenPaths("document", $user);
             if (count($forbiddenDocumentPaths) > 0) {
                 for ($i = 0; $i < count($forbiddenDocumentPaths); $i++) {
                     $forbiddenDocumentPaths[$i] = " (maintype = 'document' AND fullpath not like " . $db->quote($forbiddenDocumentPaths[$i] . "%") . ")";
                 }
                 $forbiddenConditions[] = implode(" AND ", $forbiddenDocumentPaths);
             }
         }
     }
     //exclude forbidden objects
     if (in_array("object", $types)) {
         if (!$user->isAllowed("objects")) {
             $forbiddenConditions[] = " `type` != 'object' ";
         } else {
             $forbiddenObjectPaths = Element\Service::findForbiddenPaths("object", $user);
             if (count($forbiddenObjectPaths) > 0) {
                 for ($i = 0; $i < count($forbiddenObjectPaths); $i++) {
                     $forbiddenObjectPaths[$i] = " (maintype = 'object' AND fullpath not like " . $db->quote($forbiddenObjectPaths[$i] . "%") . ")";
                 }
                 $forbiddenConditions[] = implode(" AND ", $forbiddenObjectPaths);
             }
         }
     }
     if ($forbiddenConditions) {
         $conditionParts[] = "(" . implode(" AND ", $forbiddenConditions) . ")";
     }
     if (!empty($query)) {
         $queryCondition = "( MATCH (`data`,`properties`) AGAINST (" . $db->quote($query) . " IN BOOLEAN MODE) )";
         // the following should be done with an exact-search now "ID", because the Element-ID is now in the fulltext index
         // if the query is numeric the user might want to search by id
         //if(is_numeric($query)) {
         //$queryCondition = "(" . $queryCondition . " OR id = " . $db->quote($query) ." )";
         //}
         $conditionParts[] = $queryCondition;
     }
     //For objects - handling of bricks
     $fields = array();
     $bricks = array();
     if ($this->getParam("fields")) {
         $fields = $this->getParam("fields");
         foreach ($fields as $f) {
             $parts = explode("~", $f);
             if (substr($f, 0, 1) == "~") {
                 //                    $type = $parts[1];
                 //                    $field = $parts[2];
                 //                    $keyid = $parts[3];
                 // key value, ignore for now
             } else {
                 if (count($parts) > 1) {
                     $bricks[$parts[0]] = $parts[0];
                 }
             }
         }
     }
     // filtering for objects
     if ($this->getParam("filter") && $this->getParam("class")) {
         $class = Object\ClassDefinition::getByName($this->getParam("class"));
         $conditionFilters = Object\Service::getFilterCondition($this->getParam("filter"), $class);
         $join = "";
         foreach ($bricks as $ob) {
             $join .= " LEFT JOIN object_brick_query_" . $ob . "_" . $class->getId();
             $join .= " `" . $ob . "`";
             $join .= " ON `" . $ob . "`.o_id = `object_" . $class->getId() . "`.o_id";
         }
         $conditionParts[] = "( id IN (SELECT `object_" . $class->getId() . "`.o_id FROM object_" . $class->getId() . $join . " WHERE " . $conditionFilters . ") )";
     }
     if (is_array($types) and !empty($types[0])) {
         foreach ($types as $type) {
             $conditionTypeParts[] = $db->quote($type);
         }
         if (in_array("folder", $subtypes)) {
             $conditionTypeParts[] = $db->quote('folder');
         }
         $conditionParts[] = "( maintype IN (" . implode(",", $conditionTypeParts) . ") )";
     }
     if (is_array($subtypes) and !empty($subtypes[0])) {
         foreach ($subtypes as $subtype) {
             $conditionSubtypeParts[] = $db->quote($subtype);
         }
         $conditionParts[] = "( type IN (" . implode(",", $conditionSubtypeParts) . ") )";
     }
     if (is_array($classnames) and !empty($classnames[0])) {
         if (in_array("folder", $subtypes)) {
             $classnames[] = "folder";
         }
         foreach ($classnames as $classname) {
             $conditionClassnameParts[] = $db->quote($classname);
         }
         $conditionParts[] = "( subtype IN (" . implode(",", $conditionClassnameParts) . ") )";
     }
     if (count($conditionParts) > 0) {
         $condition = implode(" AND ", $conditionParts);
         //echo $condition; die();
         $searcherList->setCondition($condition);
     }
     $searcherList->setOffset($offset);
     $searcherList->setLimit($limit);
     // do not sort per default, it is VERY SLOW
     //$searcherList->setOrder("desc");
     //$searcherList->setOrderKey("modificationdate");
     if ($this->getParam("sort")) {
         // we need a special mapping for classname as this is stored in subtype column
         $sortMapping = ["classname" => "subtype"];
         $sort = $this->getParam("sort");
         if (array_key_exists($this->getParam("sort"), $sortMapping)) {
             $sort = $sortMapping[$this->getParam("sort")];
         }
         $searcherList->setOrderKey($sort);
     }
     if ($this->getParam("dir")) {
         $searcherList->setOrder($this->getParam("dir"));
     }
     $hits = $searcherList->load();
     $elements = array();
     foreach ($hits as $hit) {
         $element = Element\Service::getElementById($hit->getId()->getType(), $hit->getId()->getId());
         if ($element->isAllowed("list")) {
             if ($element instanceof Object\AbstractObject) {
                 $data = Object\Service::gridObjectData($element, $fields);
             } else {
                 if ($element instanceof Document) {
                     $data = Document\Service::gridDocumentData($element);
                 } else {
                     if ($element instanceof Asset) {
                         $data = Asset\Service::gridAssetData($element);
                     }
                 }
             }
             $elements[] = $data;
         } else {
             //TODO: any message that view is blocked?
             //$data = Element\Service::gridElementData($element);
         }
     }
     // only get the real total-count when the limit parameter is given otherwise use the default limit
     if ($this->getParam("limit")) {
         $totalMatches = $searcherList->getTotalCount();
     } else {
         $totalMatches = count($elements);
     }
     $this->_helper->json(array("data" => $elements, "success" => true, "total" => $totalMatches));
     $this->removeViewRenderer();
 }
예제 #8
0
 public function renderDocument($params)
 {
     $html = Document\Service::render($this, $params, true);
     return $html;
 }
예제 #9
0
 /**
  * @static
  * @param ElementInterface $element
  * @return ElementInterface
  */
 public static function loadAllFields(ElementInterface $element)
 {
     if ($element instanceof Document) {
         Document\Service::loadAllDocumentFields($element);
     } else {
         if ($element instanceof Object\Concrete) {
             Object\Service::loadAllObjectFields($element);
         } else {
             if ($element instanceof Asset) {
                 Asset\Service::loadAllFields($element);
             }
         }
     }
     return $element;
 }
예제 #10
0
 /**
  * @param Model\Document $document
  */
 protected function addTranslationsData(Model\Document $document)
 {
     $service = new Model\Document\Service();
     $translations = $service->getTranslations($document);
     $language = $document->getProperty("language");
     unset($translations[$language]);
     $document->translations = $translations;
 }
예제 #11
0
 public function wordExportAction()
 {
     //error_reporting(E_ERROR);
     //ini_set("display_errors", "off");
     $id = $this->getParam("id");
     $data = \Zend_Json::decode($this->getParam("data"));
     $source = $this->getParam("source");
     $exportFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/" . $id . ".html";
     if (!is_file($exportFile)) {
         /*file_put_contents($exportFile, '<!DOCTYPE html>' . "\n" . '<html>
               <head>
                   <style type="text/css">' . file_get_contents(PIMCORE_PATH . "/static/css/word-export.css") . '</style>
               </head>
               <body>
           ');*/
         File::put($exportFile, '<style type="text/css">' . file_get_contents(PIMCORE_PATH . "/static6/css/word-export.css") . '</style>');
     }
     foreach ($data as $el) {
         try {
             $element = Element\Service::getElementById($el["type"], $el["id"]);
             $output = "";
             // check supported types (subtypes)
             if (!in_array($element->getType(), array("page", "snippet", "email", "object"))) {
                 continue;
             }
             if ($element instanceof Element\ElementInterface) {
                 $output .= '<h1 class="element-headline">' . ucfirst($element->getType()) . " - " . $element->getFullPath() . ' (ID: ' . $element->getId() . ')</h1>';
             }
             if ($element instanceof Document\PageSnippet) {
                 if ($element instanceof Document\Page) {
                     $structuredDataEmpty = true;
                     $structuredData = '
                         <table border="1" cellspacing="0" cellpadding="5">
                             <tr>
                                 <td colspan="2"><span style="color:#cc2929;font-weight: bold;">Structured Data</span></td>
                             </tr>
                     ';
                     if ($element->getTitle()) {
                         $structuredData .= '<tr>
                                 <td><span style="color:#cc2929;">Title</span></td>
                                 <td>' . $element->getTitle() . '&nbsp;</td>
                             </tr>';
                         $structuredDataEmpty = false;
                     }
                     if ($element->getDescription()) {
                         $structuredData .= '<tr>
                                 <td><span style="color:#cc2929;">Description</span></td>
                                 <td>' . $element->getDescription() . '&nbsp;</td>
                             </tr>';
                         $structuredDataEmpty = false;
                     }
                     if ($element->getKeywords()) {
                         $structuredData .= '<tr>
                                 <td><span style="color:#cc2929;">Keywords</span></td>
                                 <td>' . $element->getKeywords() . '&nbsp;</td>
                             </tr>';
                         $structuredDataEmpty = false;
                     }
                     if ($element->getProperty("navigation_name")) {
                         $structuredData .= '<tr>
                                 <td><span style="color:#cc2929;">Navigation</span></td>
                                 <td>' . $element->getProperty("navigation_name") . '&nbsp;</td>
                             </tr>';
                         $structuredDataEmpty = false;
                     }
                     $structuredData .= '</table>';
                     if (!$structuredDataEmpty) {
                         $output .= $structuredData;
                     }
                 }
                 // we need to set the parameter "pimcore_admin" here to be able to render unpublished documents
                 $reqBak = $_REQUEST;
                 $_REQUEST["pimcore_admin"] = true;
                 $html = Document\Service::render($element, array(), false);
                 $_REQUEST = $reqBak;
                 // set the request back to original
                 $html = preg_replace("@</?(img|meta|div|section|aside|article|body|bdi|bdo|canvas|embed|footer|head|header|html)([^>]+)?>@", "", $html);
                 $html = preg_replace('/<!--(.*)-->/Uis', '', $html);
                 include_once "simple_html_dom.php";
                 $dom = str_get_html($html);
                 if ($dom) {
                     // remove containers including their contents
                     $elements = $dom->find("form,script,style,noframes,noscript,object,area,mapm,video,audio,iframe,textarea,input,select,button,");
                     if ($elements) {
                         foreach ($elements as $el) {
                             $el->outertext = "";
                         }
                     }
                     $clearText = function ($string) {
                         $string = str_replace("\r\n", "", $string);
                         $string = str_replace("\n", "", $string);
                         $string = str_replace("\r", "", $string);
                         $string = str_replace("\t", "", $string);
                         $string = preg_replace('/&[a-zA-Z0-9]+;/', '', $string);
                         // remove html entities
                         $string = preg_replace('#[ ]+#', '', $string);
                         return $string;
                     };
                     // remove empty tags (where it matters)
                     $elements = $dom->find("a, li");
                     if ($elements) {
                         foreach ($elements as $el) {
                             $string = $clearText($el->plaintext);
                             if (empty($string)) {
                                 $el->outertext = "";
                             }
                         }
                     }
                     // replace links => links get [Linktext]
                     $elements = $dom->find("a");
                     if ($elements) {
                         foreach ($elements as $el) {
                             $string = $clearText($el->plaintext);
                             if (!empty($string)) {
                                 $el->outertext = "[" . $el->plaintext . "]";
                             } else {
                                 $el->outertext = "";
                             }
                         }
                     }
                     $html = $dom->save();
                     $dom->clear();
                     unset($dom);
                     // force closing tags (simple_html_dom doesn't seem to support this anymore)
                     $doc = new \DOMDocument();
                     libxml_use_internal_errors(true);
                     $doc->loadHTML('<?xml encoding="UTF-8"><article>' . $html . "</article>");
                     libxml_clear_errors();
                     $html = $doc->saveHTML();
                     $bodyStart = strpos($html, "<body>") + 6;
                     $bodyEnd = strpos($html, "</body>");
                     if ($bodyStart && $bodyEnd) {
                         $html = substr($html, $bodyStart, $bodyEnd - $bodyStart);
                     }
                     $output .= $html;
                 }
             } else {
                 if ($element instanceof Object\Concrete) {
                     $hasContent = false;
                     if ($fd = $element->getClass()->getFieldDefinition("localizedfields")) {
                         $definitions = $fd->getFielddefinitions();
                         $locale = new \Zend_Locale(str_replace("-", "_", $source));
                         if (Tool::isValidLanguage((string) $locale)) {
                             $locale = (string) $locale;
                         } else {
                             $locale = $locale->getLanguage();
                         }
                         $output .= '
                         <table border="1" cellspacing="0" cellpadding="2">
                             <tr>
                                 <td colspan="2"><span style="color:#cc2929;font-weight: bold;">Localized Data</span></td>
                             </tr>
                     ';
                         foreach ($definitions as $definition) {
                             // check allowed datatypes
                             if (!in_array($definition->getFieldtype(), array("input", "textarea", "wysiwyg"))) {
                                 continue;
                             }
                             $content = $element->{"get" . ucfirst($definition->getName())}($locale);
                             if (!empty($content)) {
                                 $output .= '
                             <tr>
                                 <td><span style="color:#cc2929;">' . $definition->getTitle() . ' (' . $definition->getName() . ')<span></td>
                                 <td>' . $content . '&nbsp;</td>
                             </tr>
                             ';
                                 $hasContent = true;
                             }
                         }
                         $output .= '</table>';
                     }
                     if (!$hasContent) {
                         $output = "";
                         // there's no content in the object, so reset all contents and do not inclide it in the export
                     }
                 }
             }
             // append contents
             if (!empty($output)) {
                 $f = fopen($exportFile, "a+");
                 fwrite($f, $output);
                 fclose($f);
             }
         } catch (\Exception $e) {
             \Logger::error("Word Export: " . $e->getMessage());
             \Logger::error($e);
         }
     }
     $this->_helper->json(array("success" => true));
 }
예제 #12
0
 public function translationAddAction()
 {
     $sourceDocument = Document::getById($this->getParam("sourceId"));
     $targetDocument = Document::getByPath($this->getParam("targetPath"));
     if ($sourceDocument && $targetDocument) {
         $service = new Document\Service();
         $service->addTranslation($sourceDocument, $targetDocument);
     }
     $this->_helper->json(["success" => true]);
 }
예제 #13
0
 /** end point for document related data.
  * - get document by id
  *      GET http://[YOUR-DOMAIN]/webservice/rest/document/id/1281?apikey=[API-KEY]
  *      returns json-encoded document data.
  * - delete document by id
  *      DELETE http://[YOUR-DOMAIN]/webservice/rest/document/id/1281?apikey=[API-KEY]
  *      returns json encoded success value
  * - create document
  *      PUT or POST http://[YOUR-DOMAIN]/webservice/rest/document?apikey=[API-KEY]
  *      body: json-encoded document data in the same format as returned by get document by id
  *              but with missing id field or id set to 0
  *      returns json encoded document id
  * - update document
  *      PUT or POST http://[YOUR-DOMAIN]/webservice/rest/document?apikey=[API-KEY]
  *      body: same as for create document but with object id
  *      returns json encoded success value
  * @throws \Exception
  */
 public function documentAction()
 {
     $id = $this->getParam("id");
     $success = false;
     try {
         if ($this->isGet()) {
             /**
              * @api {get} /document Get document
              * @apiName getDocument
              * @apiGroup Document
              * @apiSampleRequest off
              * @apiParam {int} id The id of document you search
              * @apiParamExample {json} Request-Example:
              *     {
              *       "id": 4711
              *       "apikey": '2132sdf2321rwefdcvvce22'
              *     }
              * @apiParam {string} apikey your access token
              * @apiSuccess {boolean} success Returns true if finished successfully
              * @apiSuccessExample {json} Succes-Response:
              *                    HTTP/1.1 200 OK
              *                    {
              *                        "success":true
              *                    }
              * @apiError {boolean} success Returns false if failed
              * @apiErrorExample {json} Error-Response:
              *                  {"success":false,"msg":"exception 'Exception' with message 'Document with given ID (712131243) does not exist.'"}
              */
             $doc = Document::getById($id);
             if (!$doc) {
                 $this->encoder->encode(["success" => false, "msg" => "Document does not exist", "code" => self::ELEMENT_DOES_NOT_EXIST]);
                 return;
             }
             $this->checkPermission($doc, "get");
             if ($doc) {
                 $type = $doc->getType();
                 $getter = "getDocument" . ucfirst($type) . "ById";
                 if (method_exists($this->service, $getter)) {
                     $object = $this->service->{$getter}($id);
                 } else {
                     // check if the getter is implemented by a plugin
                     $class = "\\Pimcore\\Model\\Webservice\\Data\\Document\\" . ucfirst($type) . "\\Out";
                     if (Tool::classExists($class)) {
                         Document\Service::loadAllDocumentFields($doc);
                         $object = Webservice\Data\Mapper::map($doc, $class, "out");
                     } else {
                         throw new \Exception("unknown type");
                     }
                 }
             }
             if (!$object) {
                 throw new \Exception("could not find document");
             }
             @$this->encoder->encode(["success" => true, "data" => $object]);
             return;
         } elseif ($this->isDelete()) {
             /**
              * @api {delete} /document Delete document
              * @apiName deleteDocument
              * @apiGroup Document
              * @apiParam {int} id The id of document you delete
              * @apiSampleRequest off
              * @apiParamExample {json} Request-Example:
              *     {
              *       "id": 4711
              *       "apikey": '2132sdf2321rwefdcvvce22'
              *     }
              * @apiParam {string} apikey your access token
              * @apiSuccess {boolean} success Returns true if finished successfully
              * @apiSuccessExample {json} Succes-Response:
              *                    HTTP/1.1 200 OK
              *                    {
              *                        "success":true
              *                    }
              * @apiError {boolean} success Returns false if failed
              * @apiErrorExample {json} Error-Response:
              *                  {"success":false,"msg":"exception 'Exception' with message 'Document with given ID (712131243) does not exist.'"}
              */
             $doc = Document::getById($id);
             if ($doc) {
                 $this->checkPermission($doc, "delete");
             }
             $success = $this->service->deleteDocument($id);
             $this->encoder->encode(["success" => $success]);
             return;
         } elseif ($this->isPost() || $this->isPut()) {
             /**
              * @api {post} /document Update document
              * @apiName updateDocument
              * @apiGroup Document
              * @apiParam {int} id The id of document you delete
              * @apiSampleRequest off
              * @apiParamExample {json} Request-Example:
              *     {
              *       "id": 4711
              *       "apikey": '2132sdf2321rwefdcvvce22'
              *     }
              * @apiParam {string} apikey your access token
              * @apiSuccess {boolean} success Returns true if finished successfully
              * @apiSuccessExample {json} Succes-Response:
              *                    HTTP/1.1 200 OK
              *                    {
              *                        "success":true
              *                    }
              * @apiError {boolean} success Returns false if failed
              * @apiErrorExample {json} Error-Response:
              *                  {"success":false,"msg":"exception 'Exception' with message 'Document with given ID (712131243) does not exist.'"}
              */
             $data = file_get_contents("php://input");
             $data = \Zend_Json::decode($data);
             $type = $data["type"];
             $id = null;
             $typeUpper = ucfirst($type);
             $className = "\\Pimcore\\Model\\Webservice\\Data\\Document\\" . $typeUpper . "\\In";
             if ($data["id"]) {
                 $doc = Document::getById($data["id"]);
                 if ($doc) {
                     $this->checkPermission($doc, "update");
                 }
                 $isUpdate = true;
                 $setter = "updateDocument" . $typeUpper;
                 if (!method_exists($this->service, $setter)) {
                     throw new \Exception("method does not exist " . $setter);
                 }
                 $wsData = self::fillWebserviceData($className, $data);
                 $success = $this->service->{$setter}($wsData);
             } else {
                 $setter = "createDocument" . $typeUpper;
                 if (!method_exists($this->service, $setter)) {
                     throw new \Exception("method does not exist " . $setter);
                 }
                 $wsData = self::fillWebserviceData($className, $data);
                 $doc = new Document();
                 $doc->setId($wsData->parentId);
                 $this->checkPermission($doc, "create");
                 $id = $this->service->{$setter}($wsData);
             }
             if (!$isUpdate) {
                 $success = $id != null;
             }
             if ($success && !$isUpdate) {
                 $this->encoder->encode(["success" => $success, "id" => $id]);
             } else {
                 $this->encoder->encode(["success" => $success]);
             }
             return;
         }
     } catch (\Exception $e) {
         $this->encoder->encode(["success" => false, "msg" => (string) $e]);
     }
     $this->encoder->encode(["success" => false]);
 }
예제 #14
0
파일: Service.php 프로젝트: pimcore/pimcore
 /**
  * returns a unique key for an element
  *
  * @param $element
  * @return string
  */
 public static function getUniqueKey($element)
 {
     if ($element instanceof Object\AbstractObject) {
         return Object\Service::getUniqueKey($element);
     } elseif ($element instanceof Document) {
         return Document\Service::getUniqueKey($element);
     } elseif ($element instanceof Asset) {
         return Asset\Service::getUniqueKey($element);
     }
 }
예제 #15
0
 /**
  * @param $id
  * @throws \Exception
  */
 public function getDocumentSnippetById($id)
 {
     try {
         $snippet = Document::getById($id);
         if ($snippet instanceof Document\Snippet) {
             // load all data (eg. href, snippet, ... which are lazy loaded)
             Document\Service::loadAllDocumentFields($snippet);
             $className = Webservice\Data\Mapper::findWebserviceClass($snippet, "out");
             $apiSnippet = Webservice\Data\Mapper::map($snippet, $className, "out");
             return $apiSnippet;
         }
         throw new \Exception("Document Snippet with given ID (" . $id . ") does not exist.");
     } catch (\Exception $e) {
         \Logger::error($e);
         throw $e;
     }
 }
예제 #16
0
 /**
  * @param $path
  * @param bool $ignoreHardlinks
  * @param array $types
  * @return Document|Document\PageSnippet|null|string
  */
 protected function getNearestDocumentByPath($path, $ignoreHardlinks = false, $types = array())
 {
     if ($this->nearestDocumentByPath instanceof Document) {
         $document = $this->nearestDocumentByPath;
     } else {
         $pathes = array();
         $pathes[] = "/";
         $pathParts = explode("/", $path);
         $tmpPathes = array();
         foreach ($pathParts as $pathPart) {
             $tmpPathes[] = $pathPart;
             $t = implode("/", $tmpPathes);
             if (!empty($t)) {
                 $pathes[] = $t;
             }
         }
         $pathes = array_reverse($pathes);
         foreach ($pathes as $p) {
             if ($document = Document::getByPath($p)) {
                 if (empty($types) || in_array($document->getType(), $types)) {
                     $this->nearestDocumentByPath = $document;
                     break;
                 }
             } else {
                 if (Site::isSiteRequest()) {
                     // also check for a pretty url in a site
                     $site = Site::getCurrentSite();
                     $documentService = new Document\Service();
                     // undo the changed made by the site detection in self::match()
                     $originalPath = preg_replace("@^" . $site->getRootPath() . "@", "", $p);
                     $sitePrettyDocId = $documentService->getDocumentIdByPrettyUrlInSite($site, $originalPath);
                     if ($sitePrettyDocId) {
                         if ($sitePrettyDoc = Document::getById($sitePrettyDocId)) {
                             $this->nearestDocumentByPath = $sitePrettyDoc;
                             break;
                         }
                     }
                 }
             }
         }
     }
     if ($document) {
         if (!$ignoreHardlinks) {
             if ($document instanceof Document\Hardlink) {
                 if ($hardLinkedDocument = Document\Hardlink\Service::getNearestChildByPath($document, $path)) {
                     $document = $hardLinkedDocument;
                 } else {
                     $document = Document\Hardlink\Service::wrap($document);
                 }
             }
         }
         return $document;
     }
     return null;
 }
예제 #17
0
 /**
  * Helper to simply replace the placeholders with their value
  *
  * @param string | Model\Document $mixed
  * @param array $params
  * @param null | Model\Document $document
  * @return string
  */
 public function replacePlaceholders($mixed, $params = [], $document = null, $enableLayoutOnPlaceholderReplacement = true)
 {
     if (is_string($mixed)) {
         $contentString = $mixed;
     } elseif ($mixed instanceof Model\Document) {
         $contentString = Model\Document\Service::render($mixed, $params, $enableLayoutOnPlaceholderReplacement);
     }
     if ($document instanceof Model\Document === false) {
         $document = null;
     }
     //detects the placeholders
     $placeholderStack = $this->detectPlaceholders($contentString, $params, $document);
     //replaces the placeholders if any were found
     if (!empty($placeholderStack)) {
         $replacedString = $this->replacePlaceholdersFromStack($placeholderStack);
         return $replacedString;
     } else {
         return $contentString;
     }
 }
예제 #18
0
 /**
  * @return void
  */
 public function findAction()
 {
     $user = $this->getUser();
     $query = $this->getParam("query");
     if ($query == "*") {
         $query = "";
     }
     $query = str_replace("%", "*", $query);
     $query = preg_replace("@([^ ])\\-@", "\$1 ", $query);
     $types = explode(",", $this->getParam("type"));
     $subtypes = explode(",", $this->getParam("subtype"));
     $classnames = explode(",", $this->getParam("class"));
     if ($this->getParam("type") == "object" && is_array($classnames) && empty($classnames[0])) {
         $subtypes = ["object", "variant", "folder"];
     }
     $offset = intval($this->getParam("start"));
     $limit = intval($this->getParam("limit"));
     $offset = $offset ? $offset : 0;
     $limit = $limit ? $limit : 50;
     $searcherList = new Data\Listing();
     $conditionParts = [];
     $db = \Pimcore\Db::get();
     //exclude forbidden assets
     if (in_array("asset", $types)) {
         if (!$user->isAllowed("assets")) {
             $forbiddenConditions[] = " `type` != 'asset' ";
         } else {
             $forbiddenAssetPaths = Element\Service::findForbiddenPaths("asset", $user);
             if (count($forbiddenAssetPaths) > 0) {
                 for ($i = 0; $i < count($forbiddenAssetPaths); $i++) {
                     $forbiddenAssetPaths[$i] = " (maintype = 'asset' AND fullpath not like " . $db->quote($forbiddenAssetPaths[$i] . "%") . ")";
                 }
                 $forbiddenConditions[] = implode(" AND ", $forbiddenAssetPaths);
             }
         }
     }
     //exclude forbidden documents
     if (in_array("document", $types)) {
         if (!$user->isAllowed("documents")) {
             $forbiddenConditions[] = " `type` != 'document' ";
         } else {
             $forbiddenDocumentPaths = Element\Service::findForbiddenPaths("document", $user);
             if (count($forbiddenDocumentPaths) > 0) {
                 for ($i = 0; $i < count($forbiddenDocumentPaths); $i++) {
                     $forbiddenDocumentPaths[$i] = " (maintype = 'document' AND fullpath not like " . $db->quote($forbiddenDocumentPaths[$i] . "%") . ")";
                 }
                 $forbiddenConditions[] = implode(" AND ", $forbiddenDocumentPaths);
             }
         }
     }
     //exclude forbidden objects
     if (in_array("object", $types)) {
         if (!$user->isAllowed("objects")) {
             $forbiddenConditions[] = " `type` != 'object' ";
         } else {
             $forbiddenObjectPaths = Element\Service::findForbiddenPaths("object", $user);
             if (count($forbiddenObjectPaths) > 0) {
                 for ($i = 0; $i < count($forbiddenObjectPaths); $i++) {
                     $forbiddenObjectPaths[$i] = " (maintype = 'object' AND fullpath not like " . $db->quote($forbiddenObjectPaths[$i] . "%") . ")";
                 }
                 $forbiddenConditions[] = implode(" AND ", $forbiddenObjectPaths);
             }
         }
     }
     if ($forbiddenConditions) {
         $conditionParts[] = "(" . implode(" AND ", $forbiddenConditions) . ")";
     }
     if (!empty($query)) {
         $queryCondition = "( MATCH (`data`,`properties`) AGAINST (" . $db->quote($query) . " IN BOOLEAN MODE) )";
         // the following should be done with an exact-search now "ID", because the Element-ID is now in the fulltext index
         // if the query is numeric the user might want to search by id
         //if(is_numeric($query)) {
         //$queryCondition = "(" . $queryCondition . " OR id = " . $db->quote($query) ." )";
         //}
         $conditionParts[] = $queryCondition;
     }
     //For objects - handling of bricks
     $fields = [];
     $bricks = [];
     if ($this->getParam("fields")) {
         $fields = $this->getParam("fields");
         foreach ($fields as $f) {
             $parts = explode("~", $f);
             if (substr($f, 0, 1) == "~") {
                 //                    $type = $parts[1];
                 //                    $field = $parts[2];
                 //                    $keyid = $parts[3];
                 // key value, ignore for now
             } elseif (count($parts) > 1) {
                 $bricks[$parts[0]] = $parts[0];
             }
         }
     }
     // filtering for objects
     if ($this->getParam("filter") && $this->getParam("class")) {
         $class = Object\ClassDefinition::getByName($this->getParam("class"));
         // add Localized Fields filtering
         $params = \Zend_Json::decode($this->getParam('filter'));
         $unlocalizedFieldsFilters = [];
         $localizedFieldsFilters = [];
         foreach ($params as $paramConditionObject) {
             //this loop divides filter parameters to localized and unlocalized groups
             $definitionExists = in_array('o_' . $paramConditionObject['property'], Object\Service::getSystemFields()) || $class->getFieldDefinition($paramConditionObject['property']);
             if ($definitionExists) {
                 //TODO: for sure, we can add additional condition like getLocalizedFieldDefinition()->getFieldDefiniton(...
                 $unlocalizedFieldsFilters[] = $paramConditionObject;
             } else {
                 $localizedFieldsFilters[] = $paramConditionObject;
             }
         }
         //get filter condition only when filters array is not empty
         //string statements for divided filters
         $conditionFilters = count($unlocalizedFieldsFilters) ? Object\Service::getFilterCondition(\Zend_Json::encode($unlocalizedFieldsFilters), $class) : null;
         $localizedConditionFilters = count($localizedFieldsFilters) ? Object\Service::getFilterCondition(\Zend_Json::encode($localizedFieldsFilters), $class) : null;
         $join = "";
         foreach ($bricks as $ob) {
             $join .= " LEFT JOIN object_brick_query_" . $ob . "_" . $class->getId();
             $join .= " `" . $ob . "`";
             $join .= " ON `" . $ob . "`.o_id = `object_" . $class->getId() . "`.o_id";
         }
         if (null !== $conditionFilters) {
             //add condition query for non localised fields
             $conditionParts[] = "( id IN (SELECT `object_" . $class->getId() . "`.o_id FROM object_" . $class->getId() . $join . " WHERE " . $conditionFilters . ") )";
         }
         if (null !== $localizedConditionFilters) {
             //add condition query for localised fields
             $conditionParts[] = "( id IN (SELECT `object_localized_data_" . $class->getId() . "`.ooo_id FROM object_localized_data_" . $class->getId() . $join . " WHERE " . $localizedConditionFilters . " GROUP BY ooo_id " . ") )";
         }
     }
     if (is_array($types) and !empty($types[0])) {
         foreach ($types as $type) {
             $conditionTypeParts[] = $db->quote($type);
         }
         if (in_array("folder", $subtypes)) {
             $conditionTypeParts[] = $db->quote('folder');
         }
         $conditionParts[] = "( maintype IN (" . implode(",", $conditionTypeParts) . ") )";
     }
     if (is_array($subtypes) and !empty($subtypes[0])) {
         foreach ($subtypes as $subtype) {
             $conditionSubtypeParts[] = $db->quote($subtype);
         }
         $conditionParts[] = "( type IN (" . implode(",", $conditionSubtypeParts) . ") )";
     }
     if (is_array($classnames) and !empty($classnames[0])) {
         if (in_array("folder", $subtypes)) {
             $classnames[] = "folder";
         }
         foreach ($classnames as $classname) {
             $conditionClassnameParts[] = $db->quote($classname);
         }
         $conditionParts[] = "( subtype IN (" . implode(",", $conditionClassnameParts) . ") )";
     }
     //filtering for tags
     $tagIds = $this->getParam("tagIds");
     if ($tagIds) {
         foreach ($tagIds as $tagId) {
             foreach ($types as $type) {
                 if ($this->getParam("considerChildTags") == "true") {
                     $tag = Pimcore\Model\Element\Tag::getById($tagId);
                     if ($tag) {
                         $tagPath = $tag->getFullIdPath();
                         $conditionParts[] = "id IN (SELECT cId FROM tags_assignment INNER JOIN tags ON tags.id = tags_assignment.tagid WHERE ctype = " . $db->quote($type) . " AND (id = " . intval($tagId) . " OR idPath LIKE " . $db->quote($tagPath . "%") . "))";
                     }
                 } else {
                     $conditionParts[] = "id IN (SELECT cId FROM tags_assignment WHERE ctype = " . $db->quote($type) . " AND tagid = " . intval($tagId) . ")";
                 }
             }
         }
     }
     if (count($conditionParts) > 0) {
         $condition = implode(" AND ", $conditionParts);
         //echo $condition; die();
         $searcherList->setCondition($condition);
     }
     $searcherList->setOffset($offset);
     $searcherList->setLimit($limit);
     // do not sort per default, it is VERY SLOW
     //$searcherList->setOrder("desc");
     //$searcherList->setOrderKey("modificationdate");
     $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams());
     if ($sortingSettings['orderKey']) {
         // we need a special mapping for classname as this is stored in subtype column
         $sortMapping = ["classname" => "subtype"];
         $sort = $sortingSettings['orderKey'];
         if (array_key_exists($sortingSettings['orderKey'], $sortMapping)) {
             $sort = $sortMapping[$sortingSettings['orderKey']];
         }
         $searcherList->setOrderKey($sortingSettings['orderKey']);
     }
     if ($sortingSettings['order']) {
         $searcherList->setOrder($sortingSettings['order']);
     }
     $hits = $searcherList->load();
     $elements = [];
     foreach ($hits as $hit) {
         $element = Element\Service::getElementById($hit->getId()->getType(), $hit->getId()->getId());
         if ($element->isAllowed("list")) {
             if ($element instanceof Object\AbstractObject) {
                 $data = Object\Service::gridObjectData($element, $fields);
             } elseif ($element instanceof Document) {
                 $data = Document\Service::gridDocumentData($element);
             } elseif ($element instanceof Asset) {
                 $data = Asset\Service::gridAssetData($element);
             }
             $elements[] = $data;
         } else {
             //TODO: any message that view is blocked?
             //$data = Element\Service::gridElementData($element);
         }
     }
     // only get the real total-count when the limit parameter is given otherwise use the default limit
     if ($this->getParam("limit")) {
         $totalMatches = $searcherList->getTotalCount();
     } else {
         $totalMatches = count($elements);
     }
     $this->_helper->json(["data" => $elements, "success" => true, "total" => $totalMatches]);
     $this->removeViewRenderer();
 }