getById() публичный статический Метод

Static helper to get a Document by it's ID
public static getById ( integer $id ) : Document | Email | Folder | Hardlink | Link | Page | Printcontainer | Printpage | Snippet | Newsletter
$id integer
Результат Document | Email | Folder | Hardlink | Link | Page | Printcontainer | Printpage | Snippet | Newsletter
Пример #1
0
 /**
  * @param $document
  * @param null $language
  * @return Document|null
  */
 public function inotherlang($document, $language = null)
 {
     $documentInOtherLang = null;
     if (is_null($language)) {
         $language = CURRENT_LANGUAGE;
     }
     if ($document instanceof Document) {
         $id = $document->getId();
     } elseif (is_numeric($document)) {
         $id = $document;
     } else {
         $id = 0;
     }
     $otherLangId = null;
     try {
         if (class_exists('\\Multilingual\\Document')) {
             $otherLangId = \Multilingual\Document::getDocumentIdInOtherLanguage($id, $language);
         } else {
             $otherLangId = $id;
         }
     } catch (Exception $e) {
     }
     if ($otherLangId) {
         $documentInOtherLang = Document::getById($otherLangId);
     }
     return $documentInOtherLang;
 }
Пример #2
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();
     }
 }
Пример #3
0
 /**
  * @return Document\PageSnippet
  */
 public function getSourceDocument()
 {
     if ($this->getSourceId()) {
         return Document::getById($this->getSourceId());
     }
     return null;
 }
Пример #4
0
 public function codeAction()
 {
     $url = "";
     if ($this->getParam("name")) {
         $url = $this->getRequest()->getScheme() . "://" . $this->getRequest()->getHttpHost() . "/qr~-~code/" . $this->getParam("name");
     } elseif ($this->getParam("documentId")) {
         $doc = Document::getById($this->getParam("documentId"));
         $url = $this->getRequest()->getScheme() . "://" . $this->getRequest()->getHttpHost() . $doc->getFullPath();
     } elseif ($this->getParam("url")) {
         $url = $this->getParam("url");
     }
     $code = new \Endroid\QrCode\QrCode();
     $code->setText($url);
     $code->setPadding(0);
     $code->setSize(500);
     $hexToRGBA = function ($hex) {
         list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
         return ["r" => $r, "g" => $g, "b" => $b, "a" => 0];
     };
     if (strlen($this->getParam("foreColor", "")) == 7) {
         $code->setForegroundColor($hexToRGBA($this->getParam("foreColor")));
     }
     if (strlen($this->getParam("backgroundColor", "")) == 7) {
         $code->setBackgroundColor($hexToRGBA($this->getParam("backgroundColor")));
     }
     header("Content-Type: image/png");
     if ($this->getParam("download")) {
         $code->setSize(4000);
         header('Content-Disposition: attachment;filename="qrcode-' . $this->getParam("name", "preview") . '.png"', true);
     }
     $code->render();
     exit;
 }
Пример #5
0
 /**
  * Loads a list of entries for the specicifies parameters, returns an array of Search\Backend\Data
  *
  * @return array
  */
 public function load()
 {
     $entries = array();
     $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']);
         } else {
             if ($entryData['maintype'] == 'asset') {
                 $element = Asset::getById($entryData['id']);
             } else {
                 if ($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;
 }
Пример #6
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);
 }
Пример #7
0
 public function ruleGetAction()
 {
     $target = Targeting\Rule::getById($this->getParam("id"));
     $redirectUrl = $target->getActions()->getRedirectUrl();
     if (is_numeric($redirectUrl)) {
         $doc = Document::getById($redirectUrl);
         if ($doc instanceof Document) {
             $target->getActions()->redirectUrl = $doc->getFullPath();
         }
     }
     $this->_helper->json($target);
 }
Пример #8
0
 /**
  * Loads a list of objects (all are an instance of Document) for the given parameters an return them
  *
  * @return array
  */
 public function load()
 {
     $documents = array();
     $documentsData = $this->db->fetchAll("SELECT id,type FROM documents" . $this->getCondition() . $this->getOrder() . $this->getOffsetLimit(), $this->model->getConditionVariables());
     foreach ($documentsData as $documentData) {
         if ($documentData["type"]) {
             if ($doc = Document::getById($documentData["id"])) {
                 $documents[] = $doc;
             }
         }
     }
     $this->model->setDocuments($documents);
     return $documents;
 }
Пример #9
0
 /**
  * Loads a list of objects (all are an instance of Document) for the given parameters an return them
  *
  * @return array
  */
 public function load()
 {
     $documents = [];
     $select = (string) $this->getQuery(['id', "type"]);
     $documentsData = $this->db->fetchAll($select, $this->model->getConditionVariables());
     foreach ($documentsData as $documentData) {
         if ($documentData["type"]) {
             if ($doc = Document::getById($documentData["id"])) {
                 $documents[] = $doc;
             }
         }
     }
     $this->model->setDocuments($documents);
     return $documents;
 }
Пример #10
0
 /**
  * @param Document $document
  * @return array
  */
 public function getTranslations(Document $document)
 {
     $sourceId = $this->getTranslationSourceId($document);
     $data = $this->db->fetchAll("SELECT id,language FROM documents_translations WHERE sourceId = ?", [$sourceId]);
     $translations = [];
     foreach ($data as $translation) {
         $translations[$translation["language"]] = $translation["id"];
     }
     // add language from source document
     if (!empty($translations)) {
         $sourceDocument = Document::getById($sourceId);
         $translations[$sourceDocument->getProperty("language")] = $sourceDocument->getId();
     }
     return $translations;
 }
Пример #11
0
 /**
  * Original function
  * @see Admin_DocumentController::treeGetChildsByIdAction()
  */
 public function treeGetChildsByIdAction()
 {
     $languages = Tool::getValidLanguages();
     $language = $this->_getParam("language", reset($languages));
     $document = Document::getById($this->getParam("node"));
     $documents = array();
     if ($document->hasChilds()) {
         $limit = intval($this->getParam("limit"));
         if (!$this->getParam("limit")) {
             $limit = 100000000;
         }
         $offset = intval($this->getParam("start"));
         $list = new Document\Listing();
         if ($this->getUser()->isAdmin()) {
             $list->setCondition("parentId = ? ", $document->getId());
         } else {
             $userIds = $this->getUser()->getRoles();
             $userIds[] = $this->getUser()->getId();
             $list->setCondition("parentId = ? and\r\n                                        (\r\n                                        (select list from users_workspaces_document where userId in (" . implode(',', $userIds) . ") and LOCATE(CONCAT(path,`key`),cpath)=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1\r\n                                        or\r\n                                        (select list from users_workspaces_document where userId in (" . implode(',', $userIds) . ") and LOCATE(cpath,CONCAT(path,`key`))=1  ORDER BY LENGTH(cpath) DESC LIMIT 1)=1\r\n                                        )", $document->getId());
         }
         $list->setOrderKey("index");
         $list->setOrder("asc");
         $list->setLimit($limit);
         $list->setOffset($offset);
         $childsList = $list->load();
         foreach ($childsList as $childDocument) {
             // only display document if listing is allowed for the current user
             if ($childDocument->isAllowed("list")) {
                 if ($childDocument instanceof Document\Page && $childDocument->hasProperty('isLanguageRoot') && $childDocument->getProperty('isLanguageRoot') == 1) {
                     if ($childDocument->getKey() == $language) {
                         //                            $documents[] = $this->getTreeNodeConfig($childDocument);
                         $config = $this->getTreeNodeConfig($childDocument);
                         $config['expanded'] = true;
                         $documents[] = $config;
                     }
                 } else {
                     $documents[] = $this->getTreeNodeConfig($childDocument);
                 }
             }
         }
     }
     if ($this->getParam("limit")) {
         $this->_helper->json(array("offset" => $offset, "limit" => $limit, "total" => $document->getChildAmount($this->getUser()), "nodes" => $documents));
     } else {
         $this->_helper->json($documents);
     }
     $this->_helper->json(false);
 }
Пример #12
0
 protected function getFilterPath()
 {
     if ($this->getParam("type") == "document" && $this->getParam("id")) {
         $doc = Document::getById($this->getParam("id"));
         $path = $doc->getFullPath();
         if ($doc instanceof Document\Page && $doc->getPrettyUrl()) {
             $path = $doc->getPrettyUrl();
         }
         if ($this->getParam("site")) {
             $site = Site::getById($this->getParam("site"));
             $path = preg_replace("@^" . preg_quote($site->getRootPath(), "@") . "/@", "/", $path);
         }
         return $path;
     }
     return $this->getParam("path");
 }
Пример #13
0
 public function testAction()
 {
     /*
      * This is an example of a categorization of controllers
      * you can create folders to structure your controllers into sub-modules
      *
      * The controller name is then the name of the folder and the controller, separated by an underscore (_)
      * in this case this is "category_example"
      *
      * For this example there's a static route and a document defined
      * Name of static route: "category-example"
      * Path of document: /en/advanced-examples/sub-modules
      */
     $this->enableLayout();
     // this is needed so that the layout can be rendered
     $this->setDocument(\Pimcore\Model\Document::getById(1));
 }
Пример #14
0
 public function preDispatch()
 {
     parent::preDispatch();
     if ($this->getParam('ctype') === 'document') {
         $this->element = Document::getById((int) $this->getParam('cid', 0));
     } elseif ($this->getParam('ctype') === 'asset') {
         $this->element = Asset::getById((int) $this->getParam('cid', 0));
     } elseif ($this->getParam('ctype') === 'object') {
         $this->element = ConcreteObject::getById((int) $this->getParam('cid', 0));
     }
     if (!$this->element) {
         throw new \Exception('Cannot load element' . $this->getParam('cid') . ' of type \'' . $this->getParam('ctype') . '\'');
     }
     //get the latest available version of the element -
     //$this->element = $this->getLatestVersion($this->element);
     $this->element->setUserModification($this->getUser()->getId());
 }
Пример #15
0
 /**
  * @param $sourceDocument
  * @param $intendedLanguage
  * @return bool|\Pimcore\Model\Document
  */
 public static function getDocumentInOtherLanguage($sourceDocument, $intendedLanguage)
 {
     if ($sourceDocument instanceof \Pimcore\Model\Document) {
         $documentId = $sourceDocument->getId();
     } else {
         $documentId = $sourceDocument;
     }
     $tSource = new Keys();
     $tTarget = new Keys();
     $select = $tSource->select()->from(array("s" => $tSource->info("name")), array())->from(array("t" => $tTarget->info("name")), array("document_id"))->where("s.document_id = ?", $documentId)->where("s.sourcePath = t.sourcePath")->where("t.language = ?", $intendedLanguage);
     $row = $tSource->fetchRow($select);
     if (!empty($row)) {
         return \Pimcore\Model\Document::getById($row->document_id);
     } else {
         return false;
     }
 }
Пример #16
0
 /**
  * @param $id
  * @throws \Exception
  */
 public function getById($id)
 {
     $data = $this->db->fetchRow("SELECT * FROM notes WHERE id = ?", $id);
     if (!$data["id"]) {
         throw new \Exception("Note item with id " . $id . " not found");
     }
     $this->assignVariablesToModel($data);
     // get key-value data
     $keyValues = $this->db->fetchAll("SELECT * FROM notes_data WHERE id = ?", $id);
     $preparedData = array();
     foreach ($keyValues as $keyValue) {
         $data = $keyValue["data"];
         $type = $keyValue["type"];
         $name = $keyValue["name"];
         if ($type == "document") {
             if ($data) {
                 $data = Document::getById($data);
             }
         } else {
             if ($type == "asset") {
                 if ($data) {
                     $data = Asset::getById($data);
                 }
             } else {
                 if ($type == "object") {
                     if ($data) {
                         $data = Object\AbstractObject::getById($data);
                     }
                 } else {
                     if ($type == "date") {
                         if ($data > 0) {
                             $data = new \Zend_Date($data);
                         }
                     } else {
                         if ($type == "bool") {
                             $data = (bool) $data;
                         }
                     }
                 }
             }
         }
         $preparedData[$name] = array("data" => $data, "type" => $type);
     }
     $this->model->setData($preparedData);
 }
Пример #17
0
 public function codeAction()
 {
     if ($this->getParam("name")) {
         $url = $this->getRequest()->getScheme() . "://" . $this->getRequest()->getHttpHost() . "/qr~-~code/" . $this->getParam("name");
     } else {
         if ($this->getParam("documentId")) {
             $doc = Document::getById($this->getParam("documentId"));
             $url = $this->getRequest()->getScheme() . "://" . $this->getRequest()->getHttpHost() . $doc->getFullPath();
         } else {
             if ($this->getParam("url")) {
                 $url = $this->getParam("url");
             }
         }
     }
     $codeSettings = array('text' => $url, 'backgroundColor' => '#FFFFFF', 'foreColor' => '#000000', 'padding' => 0, 'moduleSize' => 10);
     $extension = $this->getParam("renderer");
     if ($extension == "image") {
         $extension = "png";
     }
     $renderSettings = array();
     if ($this->getParam("download")) {
         $renderSettings["sendResult"] = array('Content-Disposition: attachment;filename="qrcode-' . $this->getParam("name") . '.' . $extension . '"');
     }
     foreach ($this->getAllParams() as $key => $value) {
         if (array_key_exists($key, $codeSettings) && !empty($value)) {
             if (stripos($key, "color")) {
                 if (strlen($value) == 7) {
                     $value = strtoupper($value);
                     $codeSettings[$key] = $value;
                 }
             } else {
                 $codeSettings[$key] = $value;
             }
         }
         if (array_key_exists($key, $renderSettings) && !empty($value)) {
             $renderSettings[$key] = $value;
         }
     }
     $renderer = "image";
     if ($this->getParam("renderer") && in_array($this->getParam("renderer"), array("pdf", "image", "eps", "svg"))) {
         $renderer = $this->getParam("renderer");
     }
     $code = \Pimcore\Image\Matrixcode::render('qrcode', $codeSettings, $renderer, $renderSettings);
 }
Пример #18
0
 /**
  * @param Model\Tool\Newsletter\Config $newsletter
  * @param Object\Concrete $object
  */
 public static function sendMail($newsletter, $object, $emailAddress = null, $hostUrl = null)
 {
     $params = ["gender" => $object->getGender(), 'firstname' => $object->getFirstname(), 'lastname' => $object->getLastname(), "email" => $object->getEmail(), 'token' => $object->getProperty("token"), "object" => $object];
     $mail = new Mail();
     $mail->setIgnoreDebugMode(true);
     if (\Pimcore\Config::getSystemConfig()->newsletter->usespecific) {
         $mail->init("newsletter");
     }
     if (!Tool::getHostUrl() && $hostUrl) {
         $mail->setHostUrl($hostUrl);
     }
     if ($emailAddress) {
         $mail->addTo($emailAddress);
     } else {
         $mail->addTo($object->getEmail());
     }
     $mail->setDocument(Document::getById($newsletter->getDocument()));
     $mail->setParams($params);
     // render the document and rewrite the links (if analytics is enabled)
     if ($newsletter->getGoogleAnalytics()) {
         if ($content = $mail->getBodyHtmlRendered()) {
             include_once "simple_html_dom.php";
             $html = str_get_html($content);
             if ($html) {
                 $links = $html->find("a");
                 foreach ($links as $link) {
                     if (preg_match("/^(mailto)/", trim(strtolower($link->href)))) {
                         continue;
                     }
                     $glue = "?";
                     if (strpos($link->href, "?")) {
                         $glue = "&";
                     }
                     $link->href = $link->href . $glue . "utm_source=Newsletter&utm_medium=Email&utm_campaign=" . $newsletter->getName();
                 }
                 $content = $html->save();
                 $html->clear();
                 unset($html);
             }
             $mail->setBodyHtml($content);
         }
     }
     $mail->send();
 }
Пример #19
0
 /**
  * @param $parentId
  * @param $languageToAdd
  */
 protected function addDocuments($parentId, $languageToAdd)
 {
     $list = new Listing();
     $list->setCondition('parentId = ?', $parentId);
     $list = $list->load();
     foreach ($list as $document) {
         // Create new document
         $targetParent = \Pimcore\Model\Document::getById(\Multilingual\Document::getDocumentIdInOtherLanguage($document->getParentId(), $languageToAdd));
         /** @var Document_Page $target */
         $target = clone $document;
         $target->id = null;
         $target->setParent($targetParent);
         // Only sync properties when it is allowed
         if (!$target->hasProperty('doNotSyncProperties') && !$document->hasProperty('doNotSyncProperties')) {
             $editableDocumentTypes = array('page', 'email', 'snippet');
             if (in_array($document->getType(), $editableDocumentTypes)) {
                 $target->setContentMasterDocument($document);
             }
             // Set the properties the same
             $sourceProperties = $document->getProperties();
             /** @var string $key
              * @var Property $value
              */
             foreach ($sourceProperties as $key => $value) {
                 if (!$target->hasProperty($key)) {
                     $propertyValue = $value->getData();
                     if ($value->getType() == 'document') {
                         $propertyValue = \Multilingual\Document::getDocumentIdInOtherLanguage($value->getData()->getId(), $languageToAdd);
                     }
                     $target->setProperty($key, $value->getType(), $propertyValue, false, $value->getInheritable());
                 }
             }
         }
         $target->save();
         // Add Link to other languages
         $t = new Keys();
         $t->insert(array("document_id" => $target->getId(), "language" => $languageToAdd, "sourcePath" => $document->getFullPath()));
         // Check for children
         if (count($document->getChilds()) >= 1) {
             // Add the kids
             $this->addDocuments($document->getId(), $languageToAdd);
         }
     }
 }
Пример #20
0
 protected function updatePathFromInternal()
 {
     if ($this->data['internal']) {
         if ($this->data['internalType'] == 'document') {
             if ($doc = Document::getById($this->data['internalId'])) {
                 if (!Document::doHideUnpublished() || $doc->isPublished()) {
                     $path = $doc->getFullPath();
                     $this->data['path'] = \Toolbox\Tools\GlobalLink::parse($path);
                 }
             }
         } else {
             if ($this->data['internalType'] == 'asset') {
                 if ($asset = Asset::getById($this->data['internalId'])) {
                     $this->data['path'] = $asset->getFullPath();
                 }
             }
         }
     }
 }
Пример #21
0
 public function contactFormAction()
 {
     $success = false;
     if ($this->getParam("provider")) {
         $adapter = Tool\HybridAuth::authenticate($this->getParam("provider"));
         if ($adapter) {
             $user_data = $adapter->getUserProfile();
             if ($user_data) {
                 $this->setParam("firstname", $user_data->firstName);
                 $this->setParam("lastname", $user_data->lastName);
                 $this->setParam("email", $user_data->email);
                 $this->setParam("gender", $user_data->gender);
             }
         }
     }
     // getting parameters is very easy ... just call $this->getParam("yorParamKey"); regardless if's POST or GET
     if ($this->getParam("firstname") && $this->getParam("lastname") && $this->getParam("email") && $this->getParam("message")) {
         $success = true;
         $mail = new Mail();
         $mail->setIgnoreDebugMode(true);
         // To is used from the email document, but can also be set manually here (same for subject, CC, BCC, ...)
         //$mail->addTo("*****@*****.**");
         $emailDocument = $this->document->getProperty("email");
         if (!$emailDocument) {
             $emailDocument = Document::getById(38);
         }
         $mail->setDocument($emailDocument);
         $mail->setParams($this->getAllParams());
         $mail->send();
     }
     // do some validation & assign the parameters to the view
     foreach (["firstname", "lastname", "email", "message", "gender"] as $key) {
         if ($this->getParam($key)) {
             $this->view->{$key} = htmlentities(strip_tags($this->getParam($key)));
         }
     }
     // assign the status to the view
     $this->view->success = $success;
 }
Пример #22
0
 public function getAction()
 {
     $letter = Newsletter\Config::getByName($this->getParam("name"));
     if ($emailDoc = Document::getById($letter->getDocument())) {
         $letter->setDocument($emailDoc->getRealFullPath());
     }
     // get available classes
     $classList = new Object\ClassDefinition\Listing();
     $availableClasses = array();
     foreach ($classList->load() as $class) {
         $fieldCount = 0;
         foreach ($class->getFieldDefinitions() as $fd) {
             if ($fd instanceof Object\ClassDefinition\Data\NewsletterActive || $fd instanceof Object\ClassDefinition\Data\NewsletterConfirmed || $fd instanceof Object\ClassDefinition\Data\Email) {
                 $fieldCount++;
             }
         }
         if ($fieldCount >= 3) {
             $availableClasses[] = array($class->getName(), $class->getName());
         }
     }
     $letter->availableClasses = $availableClasses;
     $this->_helper->json($letter);
 }
Пример #23
0
 /**
  * @param $data
  * @return array
  */
 protected function prepareData($data)
 {
     $mappedData = array();
     // fix htmlentities issues
     $tmpData = array();
     foreach ($data as $d) {
         if ($d["text"] != htmlentities($d["text"], null, "UTF-8")) {
             $td = $d;
             $td["text"] = htmlentities($d["text"], null, "UTF-8");
             $tmpData[] = $td;
         }
         $tmpData[] = $d;
     }
     $data = $tmpData;
     // prepare data
     foreach ($data as $d) {
         if ($d["link"] || $d["abbr"] || $d["acronym"]) {
             $r = $d["text"];
             if ($d["abbr"]) {
                 $r = '<abbr class="pimcore_glossary" title="' . $d["abbr"] . '">' . $r . '</abbr>';
             } else {
                 if ($d["acronym"]) {
                     $r = '<acronym class="pimcore_glossary" title="' . $d["acronym"] . '">' . $r . '</acronym>';
                 }
             }
             $linkType = "";
             $linkTarget = "";
             if ($d["link"]) {
                 $linkType = "external";
                 $linkTarget = $d["link"];
                 if (intval($d["link"])) {
                     if ($doc = Model\Document::getById($d["link"])) {
                         $d["link"] = $doc->getFullPath();
                         $linkType = "internal";
                         $linkTarget = $doc->getId();
                     }
                 }
                 $r = '<a class="pimcore_glossary" href="' . $d["link"] . '">' . $r . '</a>';
             }
             // add PCRE delimiter and modifiers
             if ($d["exactmatch"]) {
                 $d["text"] = "/(?<!\\w)" . preg_quote($d["text"], "/") . "(?!\\w)/";
             } else {
                 $d["text"] = "/" . preg_quote($d["text"], "/") . "/";
             }
             if (!$d["casesensitive"]) {
                 $d["text"] .= "i";
             }
             $mappedData[] = array("replace" => $r, "search" => $d["text"], "linkType" => $linkType, "linkTarget" => $linkTarget);
         }
     }
     return $mappedData;
 }
Пример #24
0
 /**
  * @param $wsDocument
  * @throws \Exception
  */
 protected function updateDocument($wsDocument)
 {
     $document = Document::getById($wsDocument->id);
     if ($document === NULL) {
         throw new \Exception("Document with given ID (" . $wsDocument->id . ") does not exist.");
     }
     $this->setModificationParams($document, false);
     if ($document instanceof Document and strtolower($wsDocument->type) == $document->getType()) {
         $wsDocument->reverseMap($document);
         $document->save();
         return true;
     } else {
         throw new \Exception("Type mismatch for given document with ID [" . $wsDocument->id . "] and existing document with id [" . $document->getId() . "]");
     }
 }
Пример #25
0
 /**
  * @return Document
  */
 public function getDocument()
 {
     $docId = $this->getDocumentId();
     if ($docId) {
         $doc = Document::getById($docId);
         if ($doc instanceof Document\Hardlink) {
             $doc = Document\Hardlink\Service::wrap($doc);
         }
         return $doc;
     }
     return null;
 }
Пример #26
0
 /**
  * this is used for pages and snippets to change the master document (which is not saved with the normal save button)
  */
 public function changeMasterDocumentAction()
 {
     $doc = Model\Document::getById($this->getParam("id"));
     if ($doc instanceof Model\Document\PageSnippet) {
         $doc->setElements(array());
         $doc->setContentMasterDocumentId($this->getParam("contentMasterDocumentPath"));
         $doc->saveVersion(true, true, true);
     }
     $this->_helper->json(array("success" => true));
 }
Пример #27
0
 /**
  * @throws \Zend_Controller_Router_Exception
  */
 public function init()
 {
     // this is only executed once per request (first request)
     if (self::$isInitial) {
         \Pimcore::getEventManager()->trigger("frontend.controller.preInit", $this);
     }
     parent::init();
     // log exceptions if handled by error_handler
     $this->checkForErrors();
     // general definitions
     if (self::$isInitial) {
         \Pimcore::unsetAdminMode();
         Document::setHideUnpublished(true);
         Object\AbstractObject::setHideUnpublished(true);
         Object\AbstractObject::setGetInheritedValues(true);
         Object\Localizedfield::setGetFallbackValues(true);
     }
     // assign variables
     $this->view->controller = $this;
     // init website config
     $config = Config::getWebsiteConfig();
     $this->config = $config;
     $this->view->config = $config;
     $document = $this->getParam("document");
     if (!$document instanceof Document) {
         \Zend_Registry::set("pimcore_editmode", false);
         $this->editmode = false;
         $this->view->editmode = false;
         self::$isInitial = false;
         // check for a locale first, and set it if available
         if ($this->getParam("pimcore_parentDocument")) {
             // this is a special exception for renderlets in editmode (ajax request), because they depend on the locale of the parent document
             // otherwise there'll be notices like:  Notice: 'No translation for the language 'XX' available.'
             if ($parentDocument = Document::getById($this->getParam("pimcore_parentDocument"))) {
                 if ($parentDocument->getProperty("language")) {
                     $this->setLocaleFromDocument($parentDocument->getProperty("language"));
                 }
             }
         }
         // no document available, continue, ...
         return;
     } else {
         $this->setDocument($document);
         // register global locale if the document has the system property "language"
         if ($this->getDocument()->getProperty("language")) {
             $this->setLocaleFromDocument($this->getDocument()->getProperty("language"));
         }
         if (self::$isInitial) {
             // append meta-data to the headMeta() view helper,  if it is a document-request
             if (!Model\Staticroute::getCurrentRoute() && $this->getDocument() instanceof Document\Page) {
                 if (is_array($this->getDocument()->getMetaData())) {
                     foreach ($this->getDocument()->getMetaData() as $meta) {
                         // only name
                         if (!empty($meta["idName"]) && !empty($meta["idValue"]) && !empty($meta["contentValue"])) {
                             $method = "append" . ucfirst($meta["idName"]);
                             $this->view->headMeta()->{$method}($meta["idValue"], $meta["contentValue"]);
                         }
                     }
                 }
             }
         }
     }
     // this is only executed once per request (first request)
     if (self::$isInitial) {
         // contains the logged in user if necessary
         $user = null;
         // default is to set the editmode to false, is enabled later if necessary
         \Zend_Registry::set("pimcore_editmode", false);
         if (Tool::isFrontentRequestByAdmin()) {
             $this->disableBrowserCache();
             // start admin session & get logged in user
             $user = Authentication::authenticateSession();
         }
         if (\Pimcore::inDebugMode()) {
             $this->disableBrowserCache();
         }
         if (!$this->document->isPublished()) {
             if (Tool::isFrontentRequestByAdmin()) {
                 if (!$user) {
                     throw new \Zend_Controller_Router_Exception("access denied for " . $this->document->getFullPath());
                 }
             } else {
                 throw new \Zend_Controller_Router_Exception("access denied for " . $this->document->getFullPath());
             }
         }
         // logged in users only
         if ($user) {
             // set the user to registry so that it is available via \Pimcore\Tool\Admin::getCurrentUser();
             \Zend_Registry::set("pimcore_admin_user", $user);
             // document editmode
             if ($this->getParam("pimcore_editmode")) {
                 \Zend_Registry::set("pimcore_editmode", true);
                 // check if there is the document in the session
                 $docKey = "document_" . $this->getDocument()->getId();
                 $docSession = Session::getReadOnly("pimcore_documents");
                 if ($docSession->{$docKey}) {
                     // if there is a document in the session use it
                     $this->setDocument($docSession->{$docKey});
                 } else {
                     // set the latest available version for editmode if there is no doc in the session
                     $latestVersion = $this->getDocument()->getLatestVersion();
                     if ($latestVersion) {
                         $latestDoc = $latestVersion->loadData();
                         if ($latestDoc instanceof Document\PageSnippet) {
                             $this->setDocument($latestDoc);
                         }
                     }
                 }
                 // register editmode plugin
                 $front = \Zend_Controller_Front::getInstance();
                 $front->registerPlugin(new \Pimcore\Controller\Plugin\Frontend\Editmode($this), 1000);
             }
             // document preview
             if ($this->getParam("pimcore_preview")) {
                 // get document from session
                 $docKey = "document_" . $this->getParam("document")->getId();
                 $docSession = Session::getReadOnly("pimcore_documents");
                 if ($docSession->{$docKey}) {
                     $this->setDocument($docSession->{$docKey});
                 }
             }
             // object preview
             if ($this->getParam("pimcore_object_preview")) {
                 $key = "object_" . $this->getParam("pimcore_object_preview");
                 $session = Session::getReadOnly("pimcore_objects");
                 if ($session->{$key}) {
                     $object = $session->{$key};
                     // add the object to the registry so every call to Object::getById() will return this object instead of the real one
                     \Zend_Registry::set("object_" . $object->getId(), $object);
                 }
             }
             // for version preview
             if ($this->getParam("pimcore_version")) {
                 // only get version data at the first call || because of embedded Snippets ...
                 if (!\Zend_Registry::isRegistered("pimcore_version_active")) {
                     $version = Model\Version::getById($this->getParam("pimcore_version"));
                     $this->setDocument($version->getData());
                     \Zend_Registry::set("pimcore_version_active", true);
                 }
             }
         }
         // for public versions
         if ($this->getParam("v")) {
             try {
                 $version = Model\Version::getById($this->getParam("v"));
                 if ($version->getPublic()) {
                     $this->setDocument($version->getData());
                 }
             } catch (\Exception $e) {
             }
         }
         // check for persona
         if ($this->getDocument() instanceof Document\Page) {
             $this->getDocument()->setUsePersona(null);
             // reset because of preview and editmode (saved in session)
             if ($this->getParam("_ptp") && self::$isInitial) {
                 $this->getDocument()->setUsePersona($this->getParam("_ptp"));
             }
         }
         // check if document is a wrapped hardlink, if this is the case send a rel=canonical header to the source document
         if ($this->getDocument() instanceof Document\Hardlink\Wrapper\WrapperInterface) {
             // get the cononical (source) document
             $hardlinkCanonicalSourceDocument = Document::getById($this->getDocument()->getId());
             $request = $this->getRequest();
             if (\Pimcore\Tool\Frontend::isDocumentInCurrentSite($hardlinkCanonicalSourceDocument)) {
                 $this->getResponse()->setHeader("Link", '<' . $request->getScheme() . "://" . $request->getHttpHost() . $hardlinkCanonicalSourceDocument->getFullPath() . '>; rel="canonical"');
             }
         }
         \Pimcore::getEventManager()->trigger("frontend.controller.postInit", $this);
     }
     // set some parameters
     $this->editmode = \Zend_Registry::get("pimcore_editmode");
     $this->view->editmode = \Zend_Registry::get("pimcore_editmode");
     self::$isInitial = false;
 }
Пример #28
0
 /**
  * @param $activeDocument
  * @param null $navigationRootDocument
  * @param null $htmlMenuIdPrefix
  * @param null $pageCallback
  * @param bool|string $cache
  * @return mixed|\Zend_Navigation
  * @throws \Exception
  * @throws \Zend_Navigation_Exception
  */
 public function getNavigation($activeDocument, $navigationRootDocument = null, $htmlMenuIdPrefix = null, $pageCallback = null, $cache = true)
 {
     $cacheEnabled = (bool) $cache;
     $this->_htmlMenuIdPrefix = $htmlMenuIdPrefix;
     if (!$navigationRootDocument) {
         $navigationRootDocument = Document::getById(1);
     }
     $siteSuffix = "";
     if (Site::isSiteRequest()) {
         $site = Site::getCurrentSite();
         $siteSuffix = "__site_" . $site->getId();
     }
     $cacheId = $navigationRootDocument->getId();
     if (is_string($cache)) {
         $cacheId .= "_" . $cache;
     }
     $cacheKey = "navigation_" . $cacheId . $siteSuffix;
     $navigation = CacheManager::load($cacheKey);
     if (!$navigation || !$cacheEnabled) {
         $navigation = new \Zend_Navigation();
         if ($navigationRootDocument->hasChilds()) {
             $rootPage = $this->buildNextLevel($navigationRootDocument, true, $pageCallback);
             $navigation->addPages($rootPage);
         }
         // we need to force caching here, otherwise the active classes and other settings will be set and later
         // also written into cache (pass-by-reference) ... when serializing the data directly here, we don't have this problem
         if ($cacheEnabled) {
             CacheManager::save($navigation, $cacheKey, ["output", "navigation"], null, 999, true);
         }
     }
     // set active path
     $activePage = $navigation->findOneBy("realFullPath", $activeDocument->getRealFullPath());
     if (!$activePage) {
         // find by link target
         $activePage = $navigation->findOneBy("uri", $activeDocument->getRealFullPath());
     }
     if ($activePage) {
         // we found an active document, so we can build the active trail by getting respectively the parent
         $this->addActiveCssClasses($activePage, true);
     } else {
         // we don't have an active document, so we try to build the trail on our own
         $allPages = $navigation->findAllBy("uri", "/.*/", true);
         foreach ($allPages as $page) {
             $activeTrail = false;
             if (strpos($activeDocument->getRealFullPath(), $page->getRealFullPath() . "/") === 0) {
                 $activeTrail = true;
             }
             if ($page->getDocumentType() == "link") {
                 if (strpos($activeDocument->getFullPath(), $page->getUri() . "/") === 0) {
                     $activeTrail = true;
                 }
             }
             if ($activeTrail) {
                 $page->setActive(true);
                 $page->setClass($page->getClass() . " active active-trail");
             }
         }
     }
     return $navigation;
 }
Пример #29
0
 /**
  * @return void
  */
 public function setObjectFromId()
 {
     if ($this->internalType == "document") {
         $this->object = Document::getById($this->internal);
     } else {
         if ($this->internalType == "asset") {
             $this->object = Asset::getById($this->internal);
         }
     }
     return $this->object;
 }
 /** 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));
 }