public function subscribeAction() { $this->enableLayout(); $newsletter = new Newsletter("person"); // replace "crm" with the class name you have used for your class above (mailing list) $params = $this->getAllParams(); $this->view->success = false; if ($newsletter->checkParams($params)) { try { $params["parentId"] = 1; // default folder (home) where we want to save our subscribers $newsletterFolder = Model\Object::getByPath("/crm/newsletter"); if ($newsletterFolder) { $params["parentId"] = $newsletterFolder->getId(); } $user = $newsletter->subscribe($params); // user and email document // parameters available in the email: gender, firstname, lastname, email, token, object // ==> see mailing framework $newsletter->sendConfirmationMail($user, Model\Document::getByPath("/en/advanced-examples/newsletter/confirmation-email"), ["additional" => "parameters"]); // do some other stuff with the new user $user->setDateRegister(new \DateTime()); $user->save(); $this->view->success = true; } catch (\Exception $e) { echo $e->getMessage(); } } }
/** * 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; }
/** * Set auth_PayerID - PayerID * @return string */ public function getAuth_PayerID() { $data = $this->auth_PayerID; if (\Pimcore\Model\Object::doGetInheritedValues($this->getObject()) && $this->getDefinition()->getFieldDefinition("auth_PayerID")->isEmpty($data)) { return $this->getValueFromParent("auth_PayerID"); } return $data; }
/** * Set size - Size * @return string */ public function getSize() { $data = $this->size; if (\Pimcore\Model\Object::doGetInheritedValues($this->getObject()) && $this->getDefinition()->getFieldDefinition("size")->isEmpty($data)) { return $this->getValueFromParent("size"); } return $data; }
/** * Set identificationShortId - IdentificationShortId * @return string */ public function getIdentificationShortId() { $data = $this->identificationShortId; if (\Pimcore\Model\Object::doGetInheritedValues($this->getObject()) && $this->getDefinition()->getFieldDefinition("identificationShortId")->isEmpty($data)) { return $this->getValueFromParent("identificationShortId"); } return $data; }
/** * Loads a list of objects for the specicifies parameters, returns an array of Object\AbstractObject elements * * @return array */ public function load() { $objects = array(); $objectsData = $this->db->fetchAll("SELECT o_id,o_type FROM objects" . $this->getCondition() . $this->getGroupBy() . $this->getOrder() . $this->getOffsetLimit(), $this->model->getConditionVariables()); foreach ($objectsData as $objectData) { if ($object = Object::getById($objectData["o_id"])) { $objects[] = $object; } } $this->model->setObjects($objects); return $objects; }
/** * Loads a list of objects for the specicifies parameters, returns an array of Object\AbstractObject elements * * @return array */ public function load() { // load id's $list = $this->loadIdList(); $objects = array(); foreach ($list as $o_id) { if ($object = Object::getById($o_id)) { $objects[] = $object; } } $this->model->setObjects($objects); return $objects; }
/** * Loads a list of objects for the specified parameters, returns an array of Object\AbstractObject elements * * @return array */ public function load() { $objects = array(); try { $field = $this->getTableName() . ".o_id"; $sql = "SELECT " . $this->getSelectPart($field, $field) . " AS o_id,o_type FROM `" . $this->getTableName() . "`" . $this->getJoins() . $this->getCondition() . $this->getGroupBy() . $this->getOrder() . $this->getOffsetLimit(); $objectsData = $this->db->fetchAll($sql, $this->model->getConditionVariables()); } catch (\Exception $e) { return $this->exceptionHandler($e); } foreach ($objectsData as $objectData) { if ($object = Object::getById($objectData["o_id"])) { $objects[] = Object::getById($objectData["o_id"]); } } $this->model->setObjects($objects); return $objects; }
public function batchAction() { $success = true; try { $object = Object::getById($this->getParam("job")); if ($object) { $className = $object->getClassName(); $class = Object\ClassDefinition::getByName($className); $value = $this->getParam("value"); if ($this->getParam("valueType") == "object") { $value = \Zend_Json::decode($value); } $name = $this->getParam("name"); $parts = explode("~", $name); if (substr($name, 0, 1) == "~") { $type = $parts[1]; $field = $parts[2]; $keyid = $parts[3]; $getter = "get" . ucfirst($field); $setter = "set" . ucfirst($field); $keyValuePairs = $object->{$getter}(); if (!$keyValuePairs) { $keyValuePairs = new Object\Data\KeyValue(); $keyValuePairs->setObjectId($object->getId()); $keyValuePairs->setClass($object->getClass()); } $keyValuePairs->setPropertyWithId($keyid, $value, true); $object->{$setter}($keyValuePairs); } else { if (count($parts) > 1) { // check for bricks $brickType = $parts[0]; $brickKey = $parts[1]; $brickField = Object\Service::getFieldForBrickType($object->getClass(), $brickType); $fieldGetter = "get" . ucfirst($brickField); $brickGetter = "get" . ucfirst($brickType); $valueSetter = "set" . ucfirst($brickKey); $brick = $object->{$fieldGetter}()->{$brickGetter}(); if (empty($brick)) { $classname = "\\Pimcore\\Model\\Object\\Objectbrick\\Data\\" . ucfirst($brickType); $brickSetter = "set" . ucfirst($brickType); $brick = new $classname($object); $object->{$fieldGetter}()->{$brickSetter}($brick); } $brickClass = Object\Objectbrick\Definition::getByKey($brickType); $field = $brickClass->getFieldDefinition($brickKey); $brick->{$valueSetter}($field->getDataFromEditmode($value, $object)); } else { // everything else $field = $class->getFieldDefinition($name); if ($field) { $object->setValue($name, $field->getDataFromEditmode($value, $object)); } else { // check if it is a localized field if ($this->getParam("language")) { $localizedField = $class->getFieldDefinition("localizedfields"); if ($localizedField) { $field = $localizedField->getFieldDefinition($name); if ($field) { $object->{"set" . $name}($value, $this->getParam("language")); } } } // seems to be a system field, this is actually only possible for the "published" field yet if ($name == "published") { if ($value == "false" || empty($value)) { $object->setPublished(false); } else { $object->setPublished(true); } } } } } try { // don't check for mandatory fields here $object->setOmitMandatoryCheck(true); $object->setUserModification($this->getUser()->getId()); $object->save(); $success = true; } catch (\Exception $e) { $this->_helper->json(array("success" => false, "message" => $e->getMessage())); } } else { \Logger::debug("ObjectController::batchAction => There is no object left to update."); $this->_helper->json(array("success" => false, "message" => "ObjectController::batchAction => There is no object left to update.")); } } catch (\Exception $e) { \Logger::err($e); $this->_helper->json(array("success" => false, "message" => $e->getMessage())); } $this->_helper->json(array("success" => $success)); }
/** * @param Object\Concrete $object * @param array $toDelete * @param array $toAdd * @param string $ownerFieldName * @return void */ protected function processRemoteOwnerRelations($object, $toDelete, $toAdd, $ownerFieldName) { $getter = "get" . ucfirst($ownerFieldName); $setter = "set" . ucfirst($ownerFieldName); foreach ($toDelete as $id) { $owner = Object::getById($id); //TODO: lock ?! if (method_exists($owner, $getter)) { $currentData = $owner->{$getter}(); if (is_array($currentData)) { for ($i = 0; $i < count($currentData); $i++) { if ($currentData[$i]->getId() == $object->getId()) { unset($currentData[$i]); $owner->{$setter}($currentData); $owner->setUserModification($this->getUser()->getId()); $owner->save(); \Logger::debug("Saved object id [ " . $owner->getId() . " ] by remote modification through [" . $object->getId() . "], Action: deleted [ " . $object->getId() . " ] from [ {$ownerFieldName}]"); break; } } } } } foreach ($toAdd as $id) { $owner = Object::getById($id); //TODO: lock ?! if (method_exists($owner, $getter)) { $currentData = $owner->{$getter}(); $currentData[] = $object; $owner->{$setter}($currentData); $owner->setUserModification($this->getUser()->getId()); $owner->save(); \Logger::debug("Saved object id [ " . $owner->getId() . " ] by remote modification through [" . $object->getId() . "], Action: added [ " . $object->getId() . " ] to [ {$ownerFieldName} ]"); } } }
/** * @param $currentParentId * @param string $fields * @return array */ protected function buildTree($currentParentId, $fields = "", $parentIdGroups = null) { if (!$parentIdGroups) { $object = Object::getById($currentParentId); $result = $this->db->fetchAll("SELECT b.o_id AS id {$fields}, b.o_type AS type, b.o_parentId AS parentId, CONCAT(o_path,o_key) as fullpath FROM objects b LEFT JOIN " . $this->storetable . " a ON b.o_id = a." . $this->idField . " WHERE o_path LIKE ? GROUP BY b.o_id ORDER BY LENGTH(o_path) ASC", $object->getFullPath() . "/%"); $objects = array(); // group the results together based on the parent id's $parentIdGroups = []; foreach ($result as $r) { if (!isset($parentIdGroups[$r["parentId"]])) { $parentIdGroups[$r["parentId"]] = []; } $parentIdGroups[$r["parentId"]][] = $r; } } if (isset($parentIdGroups[$currentParentId])) { foreach ($parentIdGroups[$currentParentId] as $r) { $o = new \stdClass(); $o->id = $r['id']; $o->values = $r; $o->type = $r["type"]; $o->childs = $this->buildTree($r['id'], $fields, $parentIdGroups); $objects[] = $o; } } return $objects; }
/** end point for object related data. * - get object by id * GET http://[YOUR-DOMAIN]/webservice/rest/object/id/1281?apikey=[API-KEY] * returns json-encoded object data. * - delete object by id * DELETE http://[YOUR-DOMAIN]/webservice/rest/object/id/1281?apikey=[API-KEY] * returns json encoded success value * - create object * PUT or POST http://[YOUR-DOMAIN]/webservice/rest/object?apikey=[API-KEY] * body: json-encoded object data in the same format as returned by get object by id * but with missing id field or id set to 0 * returns json encoded object id * - update object * PUT or POST http://[YOUR-DOMAIN]/webservice/rest/object?apikey=[API-KEY] * body: same as for create object but with object id * returns json encoded success value * @throws \Exception */ public function objectAction() { $id = $this->getParam("id"); $success = false; try { if ($this->isGet()) { if ($id) { $profile = $this->getParam("profiling"); if ($profile) { $startTs = microtime(true); } $object = Object::getById($id); if (!$object) { $this->encoder->encode(array("success" => false, "msg" => "Object does not exist", "code" => self::ELEMENT_DOES_NOT_EXIST)); return; } if ($profile) { $timeConsumedGet = round(microtime(true) - $startTs, 3) * 1000; $startTs = microtime(true); } $this->checkPermission($object, "get"); if ($profile) { $timeConsumedPerm = round(microtime(true) - $startTs, 3) * 1000; $startTs = microtime(true); } if ($object instanceof Object\Folder) { $object = $this->service->getObjectFolderById($id); } else { $object = $this->service->getObjectConcreteById($id); } if ($profile) { $timeConsumedGetWebservice = round(microtime(true) - $startTs, 3) * 1000; } if ($profile) { $profiling = array(); $profiling["get"] = $timeConsumedGet; $profiling["perm"] = $timeConsumedPerm; $profiling["ws"] = $timeConsumedGetWebservice; $profiling["init"] = $this->timeConsumedInit; $result = array("success" => true, "profiling" => $profiling, "data" => $object); } else { $result = array("success" => true, "data" => $object); } $this->encoder->encode($result); return; } } else { if ($this->isDelete()) { $object = Object::getById($id); if ($object) { $this->checkPermission($object, "delete"); } $success = $this->service->deleteObject($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; if ($data["id"]) { $obj = Object::getById($data["id"]); if ($obj) { $this->checkPermission($obj, "update"); } $isUpdate = true; if ($type == "folder") { $wsData = self::fillWebserviceData("\\Pimcore\\Model\\Webservice\\Data\\Object\\Folder\\In", $data); $success = $this->service->updateObjectFolder($wsData); } else { $wsData = self::fillWebserviceData("\\Pimcore\\Model\\Webservice\\Data\\Object\\Concrete\\In", $data); $success = $this->service->updateObjectConcrete($wsData); } } else { if ($type == "folder") { $class = "\\Pimcore\\Model\\Webservice\\Data\\Object\\Folder\\In"; $method = "createObjectFolder"; } else { $class = "\\Pimcore\\Model\\Webservice\\Data\\Object\\Concrete\\In"; $method = "createObjectConcrete"; } $wsData = self::fillWebserviceData($class, $data); $obj = new Object(); $obj->setId($wsData->parentId); $this->checkPermission($obj, "create"); $id = $this->service->{$method}($wsData); } if (!$isUpdate) { $success = $id != null; } $result = array("success" => $success); if ($success && !$isUpdate) { $result["id"] = $id; } $this->encoder->encode($result); return; } } } } catch (\Exception $e) { \Logger::error($e); $this->encoder->encode(array("success" => false, "msg" => (string) $e)); } throw new \Exception("not implemented"); }
/** * */ public function restore() { $raw = file_get_contents($this->getStoreageFile()); $element = Serialize::unserialize($raw); // check for element with the same name if ($element instanceof Document) { $indentElement = Document::getByPath($element->getFullpath()); if ($indentElement) { $element->setKey($element->getKey() . "_restore"); } } else { if ($element instanceof Asset) { $indentElement = Asset::getByPath($element->getFullpath()); if ($indentElement) { $element->setFilename($element->getFilename() . "_restore"); } } else { if ($element instanceof Object\AbstractObject) { $indentElement = Object::getByPath($element->getFullpath()); if ($indentElement) { $element->setKey($element->getKey() . "_restore"); } } } } $this->restoreChilds($element); $this->delete(); }
public function getVariantsAction() { // get list of variants if ($this->getParam("language")) { $this->setLanguage($this->getParam("language"), true); } if ($this->getParam("xaction") == "update") { $data = \Zend_Json::decode($this->getParam("data")); // save $object = Object::getById($data["id"]); if ($object->isAllowed("publish")) { $objectData = []; foreach ($data as $key => $value) { $parts = explode("~", $key); if (substr($key, 0, 1) == "~") { $type = $parts[1]; $field = $parts[2]; $keyid = $parts[3]; $getter = "get" . ucfirst($field); $setter = "set" . ucfirst($field); $keyValuePairs = $object->{$getter}(); if (!$keyValuePairs) { $keyValuePairs = new Object\Data\KeyValue(); $keyValuePairs->setObjectId($object->getId()); $keyValuePairs->setClass($object->getClass()); } $keyValuePairs->setPropertyWithId($keyid, $value, true); $object->{$setter}($keyValuePairs); } elseif (count($parts) > 1) { $brickType = $parts[0]; $brickKey = $parts[1]; $brickField = Object\Service::getFieldForBrickType($object->getClass(), $brickType); $fieldGetter = "get" . ucfirst($brickField); $brickGetter = "get" . ucfirst($brickType); $valueSetter = "set" . ucfirst($brickKey); $brick = $object->{$fieldGetter}()->{$brickGetter}(); if (empty($brick)) { $classname = "\\Pimcore\\Model\\Object\\Objectbrick\\Data\\" . ucfirst($brickType); $brickSetter = "set" . ucfirst($brickType); $brick = new $classname($object); $object->{$fieldGetter}()->{$brickSetter}($brick); } $brick->{$valueSetter}($value); } else { $objectData[$key] = $value; } } $object->setValues($objectData); try { $object->save(); $this->_helper->json(["data" => Object\Service::gridObjectData($object, $this->getParam("fields")), "success" => true]); } catch (\Exception $e) { $this->_helper->json(["success" => false, "message" => $e->getMessage()]); } } else { throw new \Exception("Permission denied"); } } else { $parentObject = Object\Concrete::getById($this->getParam("objectId")); if (empty($parentObject)) { throw new \Exception("No Object found with id " . $this->getParam("objectId")); } if ($parentObject->isAllowed("view")) { $class = $parentObject->getClass(); $className = $parentObject->getClass()->getName(); $start = 0; $limit = 15; $orderKey = "o_id"; $order = "ASC"; $fields = []; $bricks = []; if ($this->getParam("fields")) { $fields = $this->getParam("fields"); foreach ($fields as $f) { $parts = explode("~", $f); if (count($parts) > 1) { $bricks[$parts[0]] = $parts[0]; } } } if ($this->getParam("limit")) { $limit = $this->getParam("limit"); } if ($this->getParam("start")) { $start = $this->getParam("start"); } $orderKey = "o_id"; $order = "ASC"; $colMappings = ["filename" => "o_key", "fullpath" => ["o_path", "o_key"], "id" => "o_id", "published" => "o_published", "modificationDate" => "o_modificationDate", "creationDate" => "o_creationDate"]; $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams()); if ($sortingSettings['orderKey'] && $sortingSettings['order']) { $orderKey = $sortingSettings['orderKey']; if (array_key_exists($orderKey, $colMappings)) { $orderKey = $colMappings[$orderKey]; } $order = $sortingSettings['order']; } if ($this->getParam("dir")) { $order = $this->getParam("dir"); } $listClass = "\\Pimcore\\Model\\Object\\" . ucfirst($className) . "\\Listing"; $conditionFilters = ["o_parentId = " . $parentObject->getId()]; // create filter condition if ($this->getParam("filter")) { $conditionFilters[] = Object\Service::getFilterCondition($this->getParam("filter"), $class); } if ($this->getParam("condition")) { $conditionFilters[] = "(" . $this->getParam("condition") . ")"; } $list = new $listClass(); if (!empty($bricks)) { foreach ($bricks as $b) { $list->addObjectbrick($b); } } $list->setCondition(implode(" AND ", $conditionFilters)); $list->setLimit($limit); $list->setOffset($start); $list->setOrder($order); $list->setOrderKey($orderKey); $list->setObjectTypes([Object\AbstractObject::OBJECT_TYPE_VARIANT]); $list->load(); $objects = []; foreach ($list->getObjects() as $object) { if ($object->isAllowed("view")) { $o = Object\Service::gridObjectData($object, $fields); $objects[] = $o; } } $this->_helper->json(["data" => $objects, "success" => true, "total" => $list->getTotalCount()]); } else { throw new \Exception("Permission denied"); } } }
/** * */ public static function execute() { $list = new Listing(); $list->setCondition("active = 1 AND date < ?", time()); $tasks = $list->load(); foreach ($tasks as $task) { try { if ($task->getCtype() == "document") { $document = Document::getById($task->getCid()); if ($document instanceof Document) { if ($task->getAction() == "publish-version" && $task->getVersion()) { try { $version = Version::getById($task->getVersion()); $document = $version->getData(); if ($document instanceof Document) { $document->setPublished(true); $document->save(); } else { \Logger::err("Schedule\\Task\\Executor: Could not restore document from version data."); } } catch (\Exception $e) { \Logger::err("Schedule\\Task\\Executor: Version [ " . $task->getVersion() . " ] does not exist."); } } else { if ($task->getAction() == "publish") { $document->setPublished(true); $document->save(); } else { if ($task->getAction() == "unpublish") { $document->setPublished(false); $document->save(); } else { if ($task->getAction() == "delete") { $document->delete(); } } } } } } else { if ($task->getCtype() == "asset") { $asset = Asset::getById($task->getCid()); if ($asset instanceof Asset) { if ($task->getAction() == "publish-version" && $task->getVersion()) { try { $version = Version::getById($task->getVersion()); $asset = $version->getData(); if ($asset instanceof Asset) { $asset->save(); } else { \Logger::err("Schedule\\Task\\Executor: Could not restore asset from version data."); } } catch (\Exception $e) { \Logger::err("Schedule\\Task\\Executor: Version [ " . $task->getVersion() . " ] does not exist."); } } else { if ($task->getAction() == "delete") { $asset->delete(); } } } } else { if ($task->getCtype() == "object") { $object = Object::getById($task->getCid()); if ($object instanceof Object) { if ($task->getAction() == "publish-version" && $task->getVersion()) { try { $version = Version::getById($task->getVersion()); $object = $version->getData(); if ($object instanceof Object\AbstractObject) { $object->setPublished(true); $object->save(); } else { \Logger::err("Schedule\\Task\\Executor: Could not restore object from version data."); } } catch (\Exception $e) { \Logger::err("Schedule\\Task\\Executor: Version [ " . $task->getVersion() . " ] does not exist."); } } else { if ($task->getAction() == "publish") { $object->setPublished(true); $object->save(); } else { if ($task->getAction() == "unpublish") { $object->setPublished(false); $object->save(); } else { if ($task->getAction() == "delete") { $object->delete(); } } } } } } } } $task->setActive(false); $task->save(); } catch (\Exception $e) { \Logger::err("There was a problem with the scheduled task ID: " . $task->getId()); \Logger::err($e); } } }
public function objectFormAction() { $success = false; // 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("terms")) { $success = true; // for this example the class "person" and "inquiry" is used // first we create a person, then we create an inquiry object and link them together // check for an existing person with this name $person = Object\Person::getByEmail($this->getParam("email"), 1); if (!$person) { // if there isn't an existing, ... create one $filename = \Pimcore\File::getValidFilename($this->getParam("email")); // first we need to create a new object, and fill some system-related information $person = new Object\Person(); $person->setParent(Object::getByPath("/crm/inquiries")); // we store all objects in /crm $person->setKey($filename); // the filename of the object $person->setPublished(true); // yep, it should be published :) // of course this needs some validation here in production... $person->setGender($this->getParam("gender")); $person->setFirstname($this->getParam("firstname")); $person->setLastname($this->getParam("lastname")); $person->setEmail($this->getParam("email")); $person->setDateRegister(new \DateTime()); $person->save(); } // now we create the inquiry object and link the person in it $inquiryFilename = \Pimcore\File::getValidFilename(date("Y-m-d") . "~" . $person->getEmail()); $inquiry = new Object\Inquiry(); $inquiry->setParent(Object::getByPath("/inquiries")); // we store all objects in /inquiries $inquiry->setKey($inquiryFilename); // the filename of the object $inquiry->setPublished(true); // yep, it should be published :) // now we fill in the data $inquiry->setMessage($this->getParam("message")); $inquiry->setPerson($person); $inquiry->setDate(new \DateTime()); $inquiry->setTerms((bool) $this->getParam("terms")); $inquiry->save(); } elseif ($this->getRequest()->isPost()) { $this->view->error = true; } // do some validation & assign the parameters to the view foreach (["firstname", "lastname", "email", "message", "terms"] 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; }
/** * @static * @param string $type * @param int $id * @return ElementInterface */ public static function getElementById($type, $id) { $element = null; if ($type == "asset") { $element = Asset::getById($id); } else { if ($type == "object") { $element = Object::getById($id); } else { if ($type == "document") { $element = Document::getById($id); } } } return $element; }
/** * @param Document\Webservice\Data\Document\Element $wsElement * @param null $idMapper * @throws \Exception */ public function getFromWebserviceImport($wsElement, $idMapper = null) { $data = $wsElement->value; if ($data->id !== null) { $this->type = $data->type; $this->subtype = $data->subtype; if (is_numeric($this->id)) { if ($idMapper) { $id = $idMapper->getMappedId($this->type, $this->id); } if ($this->type == "asset") { $this->o = Asset::getById($id); if (!$this->o instanceof Asset) { if ($idMapper && $idMapper->ignoreMappingFailures()) { $idMapper->recordMappingFailure($this->getDocumentId(), $this->type, $this->id); } else { throw new \Exception("cannot get values from web service import - referenced asset with id [ " . $this->id . " ] is unknown"); } } } else { if ($this->type == "document") { $this->o = Document::getById($id); if (!$this->o instanceof Document) { if ($idMapper && $idMapper->ignoreMappingFailures()) { $idMapper->recordMappingFailure($this->getDocumentId(), $this->type, $this->id); } else { throw new \Exception("cannot get values from web service import - referenced document with id [ " . $this->id . " ] is unknown"); } } } else { if ($this->type == "object") { $this->o = Object::getById($id); if (!$this->o instanceof Object\AbstractObject) { if ($idMapper && $idMapper->ignoreMappingFailures()) { $idMapper->recordMappingFailure($this->getDocumentId(), $this->type, $this->id); } else { throw new \Exception("cannot get values from web service import - referenced object with id [ " . $this->id . " ] is unknown"); } } } else { p_r($this); throw new \Exception("cannot get values from web service import - type is not valid"); } } } } else { throw new \Exception("cannot get values from web service import - id is not valid"); } } }
public function typePathAction() { $id = $this->getParam("id"); $type = $this->getParam("type"); $data = []; if ($type == "asset") { $element = Asset::getById($id); } elseif ($type == "document") { $element = Document::getById($id); $data["index"] = $element->getIndex(); } else { $element = Object::getById($id); } $typePath = Element\Service::getTypePath($element); $data["success"] = true; $data["idPath"] = Element\Service::getIdPath($element); $data["typePath"] = $typePath; $data["fullpath"] = $element->getRealFullPath(); $this->_helper->json($data); }
/** * @param mixed $value * @param null $object * @param null $idMapper * @return array|mixed * @throws \Exception */ public function getFromWebserviceImport($value, $object = null, $idMapper = null) { $objects = array(); if (empty($value)) { return null; } else { if (is_array($value)) { foreach ($value as $key => $item) { $item = (array) $item; $id = $item['id']; if ($idMapper) { $id = $idMapper->getMappedId("object", $id); } $dest = null; if ($id) { $dest = Object::getById($id); } if ($dest instanceof Object\AbstractObject) { $className = Tool::getModelClassMapping('\\Pimcore\\Model\\Object\\Data\\ObjectMetadata'); $metaObject = new $className($this->getName(), $this->getColumnKeys(), $dest); foreach ($this->getColumns() as $c) { $setter = "set" . ucfirst($c['key']); $metaObject->{$setter}($item[$c['key']]); } $objects[] = $metaObject; } else { if (!$idMapper || !$idMapper->ignoreMappingFailures()) { throw new \Exception("cannot get values from web service import - references unknown object with id [ " . $item['id'] . " ]"); } else { $idMapper->recordMappingFailure("object", $object->getId(), "object", $item['id']); } } } } else { throw new \Exception("cannot get values from web service import - invalid data"); } } return $objects; }
/** * @param bool $forEditMode * @return array */ public function getProperties($forEditMode = false) { $result = array(); $object = Object::getById($this->objectId); if (!$object) { throw new \Exception('Object with Id ' . $this->objectId . ' not found'); } $objectName = $object->getKey(); $internalKeys = array(); foreach ($this->arr as $pair) { $pair["inherited"] = false; $pair["source"] = $object->getId(); $pair["groupId"] = Object\KeyValue\KeyConfig::getById($pair['key'])->getGroup(); $result[] = $pair; $internalKeys[] = $pair["key"]; } $blacklist = $internalKeys; $parent = Object\Service::hasInheritableParentObject($object); while ($parent) { $kv = $parent->getKeyvaluepairs(); $parentProperties = $kv ? $kv->getInternalProperties() : []; $addedKeys = array(); foreach ($parentProperties as $parentPair) { $parentKeyId = $parentPair["key"]; $parentValue = $parentPair["value"]; if (in_array($parentKeyId, $blacklist)) { continue; } if ($this->multivalent && !$forEditMode && in_array($parentKeyId, $internalKeys)) { continue; } $add = true; for ($i = 0; $i < count($result); ++$i) { $resultPair = $result[$i]; $resultKey = $resultPair["key"]; $existingPair = null; if ($resultKey == $parentKeyId) { if ($this->multivalent && !in_array($resultKey, $blacklist)) { } else { $add = false; } // if the parent's key is already in the (internal) result list then // we don't add it => not inherited. if (!$this->multivalent) { $add = false; if (empty($resultPair["altSource"])) { $resultPair["altSource"] = $parent->getId(); $resultPair["altValue"] = $parentPair["value"]; } } $result[$i] = $resultPair; } if (!$this->multivalent) { break; } } $addedKeys[] = $parentPair["key"]; if ($add) { $parentPair["inherited"] = true; $parentPair["source"] = $parent->getId(); $parentPair["altSource"] = $parent->getId(); $parentPair["altValue"] = $parentPair["value"]; $parentPair["groupId"] = Object\KeyValue\KeyConfig::getById($parentPair['key'])->getGroup(); $result[] = $parentPair; } } foreach ($parentProperties as $parentPair) { $parentKeyId = $parentPair["key"]; $blacklist[] = $parentKeyId; } $parent = Object\Service::hasInheritableParentObject($parent); } return $result; }
/** * @param $token * @return bool * @throws \Zend_Json_Exception */ public function getObjectByToken($token) { $originalToken = $token; $token = str_replace("~", "=", $token); // base64 can contain = which isn't safe in URL's $data = \Zend_Json::decode(base64_decode($token)); if ($data) { if ($object = Object::getById($data["id"])) { if ($version = $object->getLatestVersion()) { $object = $version->getData(); } if ($object->getProperty("token") == $originalToken) { if ($object->getEmail() == $data["email"]) { return $object; } } } } return false; }
/** * @param mixed $value * @param null $object * @param null $idMapper * @return array|mixed * @throws \Exception */ public function getFromWebserviceImport($value, $object = null, $idMapper = null) { $relatedObjects = array(); if (empty($value)) { return null; } else { if (is_array($value)) { foreach ($value as $key => $item) { $item = (array) $item; $id = $item['id']; if ($idMapper) { $id = $idMapper->getMappedId("object", $id); } $relatedObject = null; if ($id) { $relatedObject = Object::getById($id); } if ($relatedObject instanceof Object\AbstractObject) { $relatedObjects[] = $relatedObject; } else { if (!$idMapper || !$idMapper->ignoreMappingFailures()) { throw new \Exception("cannot get values from web service import - references unknown object with id [ " . $item['id'] . " ]"); } else { $idMapper->recordMappingFailure("object", $object->getId(), "object", $item['id']); } } } } else { throw new \Exception("cannot get values from web service import - invalid data"); } } return $relatedObjects; }
public function preGetData($object, $params = []) { $data = null; if ($object instanceof Object\Concrete) { $data = $object->{$this->getName()}; if ($this->getLazyLoading() and !in_array($this->getName(), $object->getO__loadedLazyFields())) { //$data = $this->getDataFromResource($object->getRelationData($this->getName(), true, null)); $data = $this->load($object, ["force" => true]); $setter = "set" . ucfirst($this->getName()); if (method_exists($object, $setter)) { $object->{$setter}($data); } } } elseif ($object instanceof Object\Localizedfield) { $data = $params["data"]; } elseif ($object instanceof Object\Fieldcollection\Data\AbstractData) { $data = $object->{$this->getName()}; } elseif ($object instanceof Object\Objectbrick\Data\AbstractData) { $data = $object->{$this->getName()}; } if (Object::doHideUnpublished() and is_array($data)) { $publishedList = []; foreach ($data as $listElement) { if (Element\Service::isPublished($listElement)) { $publishedList[] = $listElement; } } return $publishedList; } return is_array($data) ? $data : []; }
public function portletModifiedObjectsAction() { $list = Object::getList(["limit" => 10, "order" => "DESC", "orderKey" => "o_modificationDate", "condition" => "o_userModification = '" . $this->getUser()->getId() . "'"]); $response = []; $response["objects"] = []; foreach ($list as $object) { $response["objects"][] = ["id" => $object->getId(), "type" => $object->getType(), "path" => $object->getRealFullPath(), "date" => $object->getModificationDate()]; } $this->_helper->json($response); }
public function indexAction() { // IE compatibility //$this->getResponse()->setHeader("X-UA-Compatible", "IE=8; IE=9", true); // clear open edit locks for this session (in the case of a reload, ...) \Pimcore\Model\Element\Editlock::clearSession(session_id()); // check maintenance $maintenance_enabled = false; $manager = Model\Schedule\Manager\Factory::getManager("maintenance.pid"); $lastExecution = $manager->getLastExecution(); if ($lastExecution) { if (time() - $lastExecution < 610) { // maintenance script should run at least every 10 minutes + a little tolerance $maintenance_enabled = true; } } $this->view->maintenance_enabled = \Zend_Json::encode($maintenance_enabled); // configuration $sysConfig = Config::getSystemConfig(); $this->view->config = $sysConfig; //mail settings $mailIncomplete = false; if ($sysConfig->email) { if (!$sysConfig->email->debug->emailaddresses) { $mailIncomplete = true; } if (!$sysConfig->email->sender->email) { $mailIncomplete = true; } if ($sysConfig->email->method == "smtp" && !$sysConfig->email->smtp->host) { $mailIncomplete = true; } } $this->view->mail_settings_complete = \Zend_Json::encode(!$mailIncomplete); // report configuration $this->view->report_config = Config::getReportConfig(); // customviews config $cvConfig = Tool::getCustomViewConfig(); $cvData = array(); if ($cvConfig) { foreach ($cvConfig as $node) { $tmpData = $node; $rootNode = Model\Object::getByPath($tmpData["rootfolder"]); if ($rootNode) { $tmpData["rootId"] = $rootNode->getId(); $tmpData["allowedClasses"] = explode(",", $tmpData["classes"]); $tmpData["showroot"] = (bool) $tmpData["showroot"]; $cvData[] = $tmpData; } } } $this->view->customview_config = $cvData; // upload limit $max_upload = filesize2bytes(ini_get("upload_max_filesize") . "B"); $max_post = filesize2bytes(ini_get("post_max_size") . "B"); $upload_mb = min($max_upload, $max_post); $this->view->upload_max_filesize = $upload_mb; // csrf token $user = $this->getUser(); $this->view->csrfToken = Tool\Session::useSession(function ($adminSession) use($user) { if (!isset($adminSession->csrfToken) && !$adminSession->csrfToken) { $adminSession->csrfToken = sha1(microtime() . $user->getName() . uniqid()); } return $adminSession->csrfToken; }); if (\Pimcore\Tool\Admin::isExtJS6()) { $this->forward("index6"); } }
/** * @param $importValue * @return mixed|null|Asset|Document|Element\ElementInterface */ public function getFromCsvImport($importValue) { $value = null; $values = explode(":", $importValue); if (count($values) == 2) { $type = $values[0]; $path = $values[1]; $value = Element\Service::getElementByPath($type, $path); } else { //fallback for old export files if ($el = Asset::getByPath($importValue)) { $value = $el; } else { if ($el = Document::getByPath($importValue)) { $value = $el; } else { if ($el = Object::getByPath($importValue)) { $value = $el; } } } } return $value; }
/** * @param integer $id * @return static */ public static function getById($id) { $id = intval($id); if ($id < 1) { return null; } $cacheKey = "object_" . $id; try { $object = \Zend_Registry::get($cacheKey); if (!$object) { throw new \Exception("Object\\AbstractObject: object in registry is null"); } } catch (\Exception $e) { try { if (!($object = Cache::load($cacheKey))) { $object = new Model\Object(); $typeInfo = $object->getResource()->getTypeById($id); if ($typeInfo["o_type"] == "object" || $typeInfo["o_type"] == "variant" || $typeInfo["o_type"] == "folder") { $mappingName = ""; if ($typeInfo["o_type"] == "folder") { $mappingName = "\\Pimcore\\Model\\Object\\Folder"; } else { $mappingName = "\\Pimcore\\Model\\Object\\" . ucfirst($typeInfo["o_className"]); } // check for a mapped class $concreteClassName = Tool::getModelClassMapping($mappingName); $object = new $concreteClassName(); \Zend_Registry::set($cacheKey, $object); $object->getResource()->getById($id); Cache::save($object, $cacheKey); } else { throw new \Exception("No entry for object id " . $id); } } else { \Zend_Registry::set($cacheKey, $object); } } catch (\Exception $e) { \Logger::warning($e->getMessage()); return null; } } // check for type $staticType = get_called_class(); if ($staticType != 'Pimcore\\Model\\Object\\Concrete' && $staticType != 'Pimcore\\Model\\Object\\AbstractObject') { if (!$object instanceof $staticType) { return null; } } if (!$object) { return null; } return $object; }
/** * @param $id * @throws \Exception */ public function getObjectConcreteById($id) { try { $object = Object::getById($id); if ($object instanceof Object\Concrete) { // load all data (eg. lazy loaded fields like multihref, object, ...) Object\Service::loadAllObjectFields($object); $apiObject = Webservice\Data\Mapper::map($object, "\\Pimcore\\Model\\Webservice\\Data\\Object\\Concrete\\Out", "out"); return $apiObject; } throw new \Exception("Object with given ID (" . $id . ") does not exist."); } catch (\Exception $e) { \Logger::error($e); throw $e; } }
/** * @param $dataArray * @param $idMapping * @return array */ private function rewriteIdsInDataEntries($dataArray, $idMapping) { $newDataArray = array(); if ($dataArray) { foreach ($dataArray as $dataArrayEntry) { if ($dataArrayEntry['data']) { $newData = array(); foreach ($dataArrayEntry['data'] as $dataEntry) { //rewrite objects if ($dataEntry['type'] == 'object' && $dataEntry['value']) { $id = $dataEntry['value']->getId(); if (array_key_exists("object", $idMapping) and array_key_exists($id, $idMapping["object"])) { $dataEntry['value'] = Object::getById($idMapping["object"][$id]); } } //rewrite assets if ($dataEntry['type'] == 'asset' && $dataEntry['value']) { $id = $dataEntry['value']->getId(); if (array_key_exists("asset", $idMapping) and array_key_exists($id, $idMapping["asset"])) { $dataEntry['value'] = Asset::getById($idMapping["asset"][$id]); } } //rewrite documents if ($dataEntry['type'] == 'document' && $dataEntry['value']) { $id = $dataEntry['value']->getId(); if (array_key_exists("document", $idMapping) and array_key_exists($id, $idMapping["document"])) { $dataEntry['value'] = Document::getById($idMapping["document"][$id]); } } $newData[] = $dataEntry; } $dataArrayEntry['data'] = $newData; } $newDataArray[] = $dataArrayEntry; } } return $newDataArray; }