/** * 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; }
/** * 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; }
/** * @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 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; }
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); }
/** 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 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 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"); } } }
/** * @see Model\Object\ClassDefinition\Data::getDataFromEditmode * @param array $data * @param null|Model\Object\AbstractObject $object * @return array */ public function getDataFromEditmode($data, $object = null) { //if not set, return null if ($data === null or $data === FALSE) { return null; } $multihrefMetadata = array(); if (is_array($data) && count($data) > 0) { foreach ($data as $element) { if ($element["type"] == "object") { $e = Object::getById($element["id"]); } else { if ($element["type"] == "asset") { $e = Asset::getById($element["id"]); } else { if ($element["type"] == "document") { $e = Document::getById($element["id"]); } } } if ($e instanceof Element\ElementInterface) { $className = Tool::getModelClassMapping('\\Pimcore\\Model\\Object\\Data\\ElementMetadata'); $metaData = new $className($this->getName(), $this->getColumnKeys(), $e); foreach ($this->getColumns() as $columnConfig) { $key = $columnConfig["key"]; $setter = "set" . ucfirst($key); $value = $element[$key]; $metaData->{$setter}($value); } $multihrefMetadata[] = $metaData; $elements[] = $e; } } } //must return array if data shall be set return $multihrefMetadata; }
/** 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()) { /** * @api {get} /object Get object data * @apiName Get object by id * @apiGroup Object * @apiSampleRequest off * @apiParam {int} id an object id * @apiParam {string} apikey your access token * @apiParamExample {json} Request-Example: * { * "id": 1, * "apikey": "21314njdsfn1342134" * } * @apiSuccess {json} success parameter of the returned data = true * @apiError {json} success parameter of the returned data = false * @apiErrorExample {json} Error-Response: * {"success":false, "msg":"exception 'Exception' with message '....'"} * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "success": true * "data": { * "path": "/crm/inquiries/", * "creationDate": 1368630916, * "modificationDate": 1388409137, * "userModification": null, * "childs": null, * "elements": [ * { * "type": "gender", * "value": "female", * "name": "gender", * "language": null * }, * * ... * * } */ if ($id) { $profile = $this->getParam("profiling"); if ($profile) { $startTs = microtime(true); } $object = Object::getById($id); if (!$object) { $this->encoder->encode(["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 = []; $profiling["get"] = $timeConsumedGet; $profiling["perm"] = $timeConsumedPerm; $profiling["ws"] = $timeConsumedGetWebservice; $profiling["init"] = $this->timeConsumedInit; $result = ["success" => true, "profiling" => $profiling, "data" => $object]; } else { $result = ["success" => true, "data" => $object]; } $this->encoder->encode($result); return; } } elseif ($this->isDelete()) { /** * @api {delete} /object Delete object * @apiName Delete object * @apiGroup Object * @apiSampleRequest off * @apiParam {int} id an object id * @apiParam {string} apikey your access token * @apiParamExample {json} Request-Example: * { * "id": 1, * "apikey": "21314njdsfn1342134" * } * @apiSuccess {json} success parameter of the returned data = true * @apiError {json} success parameter of the returned data = false * @apiErrorExample {json} Error-Response: * {"success":false, "msg":"exception 'Exception' with message '....'"} * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "success": true, * } * * */ $object = Object::getById($id); if ($object) { $this->checkPermission($object, "delete"); } $success = $this->service->deleteObject($id); $this->encoder->encode(["success" => $success]); return; } elseif ($this->isPost() || $this->isPut()) { $data = file_get_contents("php://input"); $data = \Zend_Json::decode($data); $type = $data["type"]; $id = null; if ($data["id"]) { /** * @api {put} /object Create a new object * @apiName Create a new object * @apiGroup Object * @apiSampleRequest off * @apiDescription * Request body: JSON-encoded object data in the same format as returned by get object by id for the data segment but with missing id field or id set to 0 * * @apiParam {json} data a new object data * @apiParam {string} apikey your access token * @apiParamExample {json} Request-Example: * { * "apikey": "21314njdsfn1342134", * "id": 66 * "data": { * "parentId": 48, * "key": "test-product-key", * "className": "product", * "type": "object", * "elements": [ * { * "type": "input", * "value": "some identyfier", * "name": "identyfier", * "language": null * }, * { * "type": "localizedfields", * "value": [ * { * "type": "input", * "value": "Test new", * "name": "name1", * "language": "en" * }, * { * "type": "input", * "value": "1", * "name": "name2", * "language": "en" * }, * { * "type": "input", * "value": null, * "name": "name1", * "language": "de" * }, * { * "type": "input", * "value": "aaa", * "name": "name2", * "language": "de" * } * ], * "name": "localizedfields", * "language": null * } * ] * } * } * @apiSuccess {json} success parameter of the returned data = true * @apiError {json} success parameter of the returned data = false * @apiErrorExample {json} Error-Response: * {"success":false, "msg":"exception 'Exception' with message '....'"} * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "success": true, * "id": 66 * } */ $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 { /** * @api {put} /object Create a new object * @apiName Create a new object * @apiGroup Object * @apiSampleRequest off * @apiDescription * Request body: JSON-encoded object data in the same format as returned by get object by id for the data segment but with missing id field or id set to 0 * * @apiParam {json} data a new object data * @apiParam {string} apikey your access token * @apiParamExample {json} Request-Example: * { * "apikey": "21314njdsfn1342134", * "data": { * "id": 61, * "parentId": 48, * "key": "test-product-key", * "className": "product", * "type": "object", * "elements": [ * { * "type": "input", * "value": "some identyfier", * "name": "identyfier", * "language": null * }, * { * "type": "localizedfields", * "value": [ * { * "type": "input", * "value": "Test", * "name": "name1", * "language": "en" * }, * { * "type": "input", * "value": "1", * "name": "name2", * "language": "en" * }, * { * "type": "input", * "value": null, * "name": "name1", * "language": "de" * }, * { * "type": "input", * "value": "aaa", * "name": "name2", * "language": "de" * } * ], * "name": "localizedfields", * "language": null * } * ] * } * } * @apiSuccess {json} success parameter of the returned data = true * @apiError {json} success parameter of the returned data = false * @apiErrorExample {json} Error-Response: * {"success":false, "msg":"exception 'Exception' with message '....'"} * @apiSuccessExample {json} Success-Response: * HTTP/1.1 200 OK * { * "success": true * } */ 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 = ["success" => $success]; if ($success && !$isUpdate) { $result["id"] = $id; } $this->encoder->encode($result); return; } } catch (\Exception $e) { Logger::error($e); $this->encoder->encode(["success" => false, "msg" => (string) $e]); } throw new \Exception("not implemented"); }
/** * @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; }
/** * @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} ]"); } } }
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); } } }
/** * @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 $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; }
/** * @see Model\Object\ClassDefinition\Data::getDataFromEditmode * @param array $data * @param null|Model\Object\AbstractObject $object * @param mixed $params * @return array */ public function getDataFromEditmode($data, $object = null, $params = []) { //if not set, return null if ($data === null or $data === false) { return null; } $multihrefMetadata = []; if (is_array($data) && count($data) > 0) { foreach ($data as $element) { if ($element["type"] == "object") { $e = Object::getById($element["id"]); } elseif ($element["type"] == "asset") { $e = Asset::getById($element["id"]); } elseif ($element["type"] == "document") { $e = Document::getById($element["id"]); } if ($e instanceof Element\ElementInterface) { $metaData = \Pimcore::getDiContainer()->make('Pimcore\\Model\\Object\\Data\\ElementMetadata', ["fieldname" => $this->getName(), "columns" => $this->getColumnKeys(), "element" => $e]); foreach ($this->getColumns() as $columnConfig) { $key = $columnConfig["key"]; $setter = "set" . ucfirst($key); $value = $element[$key]; $metaData->{$setter}($value); } $multihrefMetadata[] = $metaData; $elements[] = $e; } } } //must return array if data shall be set return $multihrefMetadata; }
/** * @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; }
/** * @see Model\Object\ClassDefinition\Data::getDataFromEditmode * @param array $data * @param null|Model\Object\AbstractObject $object * @param mixed $params * @return array */ public function getDataFromEditmode($data, $object = null, $params = []) { //if not set, return null if ($data === null or $data === false) { return null; } $elements = []; if (is_array($data) && count($data) > 0) { foreach ($data as $element) { if ($element["type"] == "object") { $e = Object::getById($element["id"]); } elseif ($element["type"] == "asset") { $e = Asset::getById($element["id"]); } elseif ($element["type"] == "document") { $e = Document::getById($element["id"]); } if ($e instanceof Element\ElementInterface) { $elements[] = $e; } } } //must return array if data shall be set return $elements; }
/** * @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; }