public function copyAction() { $success = false; $message = ""; $sourceId = intval($this->getParam("sourceId")); $source = Object::getById($sourceId); $session = Tool\Session::get("pimcore_copy"); $targetId = intval($this->getParam("targetId")); if ($this->getParam("targetParentId")) { $sourceParent = Object::getById($this->getParam("sourceParentId")); // this is because the key can get the prefix "_copy" if the target does already exists if ($session->{$this->getParam("transactionId")}["parentId"]) { $targetParent = Object::getById($session->{$this->getParam("transactionId")}["parentId"]); } else { $targetParent = Object::getById($this->getParam("targetParentId")); } $targetPath = preg_replace("@^" . $sourceParent->getFullPath() . "@", $targetParent . "/", $source->getPath()); $target = Object::getByPath($targetPath); } else { $target = Object::getById($targetId); } if ($target->isAllowed("create")) { $source = Object::getById($sourceId); if ($source != null) { try { if ($this->getParam("type") == "child") { $newObject = $this->_objectService->copyAsChild($target, $source); $session->{$this->getParam("transactionId")}["idMapping"][(int) $source->getId()] = (int) $newObject->getId(); // this is because the key can get the prefix "_copy" if the target does already exists if ($this->getParam("saveParentId")) { $session->{$this->getParam("transactionId")}["parentId"] = $newObject->getId(); Tool\Session::writeClose(); } } else { if ($this->getParam("type") == "replace") { $this->_objectService->copyContents($target, $source); } } $success = true; } catch (\Exception $e) { \Logger::err($e); $success = false; $message = $e->getMessage() . " in object " . $source->getFullPath() . " [id: " . $source->getId() . "]"; } } else { \Logger::error("could not execute copy/paste, source object with id [ {$sourceId} ] not found"); $this->_helper->json(array("success" => false, "message" => "source object not found")); } } else { \Logger::error("could not execute copy/paste because of missing permissions on target [ " . $targetId . " ]"); $this->_helper->json(array("error" => false, "message" => "missing_permission")); } $this->_helper->json(array("success" => $success, "message" => $message)); }
public function __construct($offerClass, $offerItemClass, $parentFolderPath) { $this->offerClass = $offerClass; $this->offerItemClass = $offerItemClass; $this->parentFolderPath = strftime($parentFolderPath, time()); \Pimcore\Model\Object\Service::createFolderByPath($this->parentFolderPath); }
/** * Prepare a Cart * * @return CoreShopCart * @throws \Exception */ public static function prepare() { $cartsFolder = Service::createFolderByPath("/coreshop/carts/" . date("Y/m/d")); $cart = CoreShopCart::create(); $cart->setKey(uniqid()); $cart->setParent($cartsFolder); $cart->setPublished(true); if (Tool::getUser() instanceof CoreShopUser) { $cart->setUser(Tool::getUser()); } $cart->save(); return $cart; }
/** * Create a new Payment * * @param Payment $provider * @param $amount * @return Object\CoreShopPayment * @throws \Exception */ public function createPayment(Payment $provider, $amount) { $payment = new Object\CoreShopPayment(); $payment->setKey(uniqid()); $payment->setPublished(true); $payment->setParent(Object\Service::createFolderByPath($this->getFullPath() . "/payments/")); $payment->setAmount($amount); $payment->setTransactionIdentifier(uniqid()); $payment->setProvider($provider->getIdentifier()); $payment->save(); $this->addPayment($payment); return $payment; }
/** * @param $id * @return mixed|null|CustomLayout * @throws \Exception */ public static function getById($id) { if ($id === null) { throw new \Exception("CustomLayout id is null"); } $cacheKey = "customlayout_" . $id; try { $customLayout = \Zend_Registry::get($cacheKey); if (!$customLayout) { throw new \Exception("Custom Layout in registry is null"); } } catch (\Exception $e) { try { $customLayout = new self(); $customLayout->getDao()->getById($id); Object\Service::synchronizeCustomLayout($customLayout); \Zend_Registry::set($cacheKey, $customLayout); } catch (\Exception $e) { \Logger::error($e); return null; } } return $customLayout; }
/** * @param string $key * @return mixed */ public function getValueForFieldName($key) { if (isset($this->{$key})) { return $this->{$key}; } elseif ($this->getClass()->getFieldDefinition($key) instanceof Model\Object\ClassDefinition\Data\CalculatedValue) { $value = new Model\Object\Data\CalculatedValue($key); $value = Service::getCalculatedFieldValue($this, $value); return $value; } return false; }
/** * @return void */ public function findAction() { $user = $this->getUser(); $query = $this->getParam("query"); if ($query == "*") { $query = ""; } $query = str_replace("%", "*", $query); $types = explode(",", $this->getParam("type")); $subtypes = explode(",", $this->getParam("subtype")); $classnames = explode(",", $this->getParam("class")); if ($this->getParam("type") == "object" && is_array($classnames) && empty($classnames[0])) { $subtypes = array("object", "variant", "folder"); } $offset = intval($this->getParam("start")); $limit = intval($this->getParam("limit")); $offset = $offset ? $offset : 0; $limit = $limit ? $limit : 50; $searcherList = new Data\Listing(); $conditionParts = array(); $db = \Pimcore\Db::get(); //exclude forbidden assets if (in_array("asset", $types)) { if (!$user->isAllowed("assets")) { $forbiddenConditions[] = " `type` != 'asset' "; } else { $forbiddenAssetPaths = Element\Service::findForbiddenPaths("asset", $user); if (count($forbiddenAssetPaths) > 0) { for ($i = 0; $i < count($forbiddenAssetPaths); $i++) { $forbiddenAssetPaths[$i] = " (maintype = 'asset' AND fullpath not like " . $db->quote($forbiddenAssetPaths[$i] . "%") . ")"; } $forbiddenConditions[] = implode(" AND ", $forbiddenAssetPaths); } } } //exclude forbidden documents if (in_array("document", $types)) { if (!$user->isAllowed("documents")) { $forbiddenConditions[] = " `type` != 'document' "; } else { $forbiddenDocumentPaths = Element\Service::findForbiddenPaths("document", $user); if (count($forbiddenDocumentPaths) > 0) { for ($i = 0; $i < count($forbiddenDocumentPaths); $i++) { $forbiddenDocumentPaths[$i] = " (maintype = 'document' AND fullpath not like " . $db->quote($forbiddenDocumentPaths[$i] . "%") . ")"; } $forbiddenConditions[] = implode(" AND ", $forbiddenDocumentPaths); } } } //exclude forbidden objects if (in_array("object", $types)) { if (!$user->isAllowed("objects")) { $forbiddenConditions[] = " `type` != 'object' "; } else { $forbiddenObjectPaths = Element\Service::findForbiddenPaths("object", $user); if (count($forbiddenObjectPaths) > 0) { for ($i = 0; $i < count($forbiddenObjectPaths); $i++) { $forbiddenObjectPaths[$i] = " (maintype = 'object' AND fullpath not like " . $db->quote($forbiddenObjectPaths[$i] . "%") . ")"; } $forbiddenConditions[] = implode(" AND ", $forbiddenObjectPaths); } } } if ($forbiddenConditions) { $conditionParts[] = "(" . implode(" AND ", $forbiddenConditions) . ")"; } if (!empty($query)) { $queryCondition = "( MATCH (`data`,`properties`) AGAINST (" . $db->quote($query) . " IN BOOLEAN MODE) )"; // the following should be done with an exact-search now "ID", because the Element-ID is now in the fulltext index // if the query is numeric the user might want to search by id //if(is_numeric($query)) { //$queryCondition = "(" . $queryCondition . " OR id = " . $db->quote($query) ." )"; //} $conditionParts[] = $queryCondition; } //For objects - handling of bricks $fields = array(); $bricks = array(); if ($this->getParam("fields")) { $fields = $this->getParam("fields"); foreach ($fields as $f) { $parts = explode("~", $f); if (substr($f, 0, 1) == "~") { // $type = $parts[1]; // $field = $parts[2]; // $keyid = $parts[3]; // key value, ignore for now } else { if (count($parts) > 1) { $bricks[$parts[0]] = $parts[0]; } } } } // filtering for objects if ($this->getParam("filter") && $this->getParam("class")) { $class = Object\ClassDefinition::getByName($this->getParam("class")); $conditionFilters = Object\Service::getFilterCondition($this->getParam("filter"), $class); $join = ""; foreach ($bricks as $ob) { $join .= " LEFT JOIN object_brick_query_" . $ob . "_" . $class->getId(); $join .= " `" . $ob . "`"; $join .= " ON `" . $ob . "`.o_id = `object_" . $class->getId() . "`.o_id"; } $conditionParts[] = "( id IN (SELECT `object_" . $class->getId() . "`.o_id FROM object_" . $class->getId() . $join . " WHERE " . $conditionFilters . ") )"; } if (is_array($types) and !empty($types[0])) { foreach ($types as $type) { $conditionTypeParts[] = $db->quote($type); } if (in_array("folder", $subtypes)) { $conditionTypeParts[] = $db->quote('folder'); } $conditionParts[] = "( maintype IN (" . implode(",", $conditionTypeParts) . ") )"; } if (is_array($subtypes) and !empty($subtypes[0])) { foreach ($subtypes as $subtype) { $conditionSubtypeParts[] = $db->quote($subtype); } $conditionParts[] = "( type IN (" . implode(",", $conditionSubtypeParts) . ") )"; } if (is_array($classnames) and !empty($classnames[0])) { if (in_array("folder", $subtypes)) { $classnames[] = "folder"; } foreach ($classnames as $classname) { $conditionClassnameParts[] = $db->quote($classname); } $conditionParts[] = "( subtype IN (" . implode(",", $conditionClassnameParts) . ") )"; } if (count($conditionParts) > 0) { $condition = implode(" AND ", $conditionParts); //echo $condition; die(); $searcherList->setCondition($condition); } $searcherList->setOffset($offset); $searcherList->setLimit($limit); // do not sort per default, it is VERY SLOW //$searcherList->setOrder("desc"); //$searcherList->setOrderKey("modificationdate"); if ($this->getParam("sort")) { // we need a special mapping for classname as this is stored in subtype column $sortMapping = ["classname" => "subtype"]; $sort = $this->getParam("sort"); if (array_key_exists($this->getParam("sort"), $sortMapping)) { $sort = $sortMapping[$this->getParam("sort")]; } $searcherList->setOrderKey($sort); } if ($this->getParam("dir")) { $searcherList->setOrder($this->getParam("dir")); } $hits = $searcherList->load(); $elements = array(); foreach ($hits as $hit) { $element = Element\Service::getElementById($hit->getId()->getType(), $hit->getId()->getId()); if ($element->isAllowed("list")) { if ($element instanceof Object\AbstractObject) { $data = Object\Service::gridObjectData($element, $fields); } else { if ($element instanceof Document) { $data = Document\Service::gridDocumentData($element); } else { if ($element instanceof Asset) { $data = Asset\Service::gridAssetData($element); } } } $elements[] = $data; } else { //TODO: any message that view is blocked? //$data = Element\Service::gridElementData($element); } } // only get the real total-count when the limit parameter is given otherwise use the default limit if ($this->getParam("limit")) { $totalMatches = $searcherList->getTotalCount(); } else { $totalMatches = count($elements); } $this->_helper->json(array("data" => $elements, "success" => true, "total" => $totalMatches)); $this->removeViewRenderer(); }
/** * @return void */ public function findAction() { $user = $this->getUser(); $query = $this->getParam("query"); if ($query == "*") { $query = ""; } $query = str_replace("%", "*", $query); $query = preg_replace("@([^ ])\\-@", "\$1 ", $query); $types = explode(",", $this->getParam("type")); $subtypes = explode(",", $this->getParam("subtype")); $classnames = explode(",", $this->getParam("class")); if ($this->getParam("type") == "object" && is_array($classnames) && empty($classnames[0])) { $subtypes = ["object", "variant", "folder"]; } $offset = intval($this->getParam("start")); $limit = intval($this->getParam("limit")); $offset = $offset ? $offset : 0; $limit = $limit ? $limit : 50; $searcherList = new Data\Listing(); $conditionParts = []; $db = \Pimcore\Db::get(); //exclude forbidden assets if (in_array("asset", $types)) { if (!$user->isAllowed("assets")) { $forbiddenConditions[] = " `type` != 'asset' "; } else { $forbiddenAssetPaths = Element\Service::findForbiddenPaths("asset", $user); if (count($forbiddenAssetPaths) > 0) { for ($i = 0; $i < count($forbiddenAssetPaths); $i++) { $forbiddenAssetPaths[$i] = " (maintype = 'asset' AND fullpath not like " . $db->quote($forbiddenAssetPaths[$i] . "%") . ")"; } $forbiddenConditions[] = implode(" AND ", $forbiddenAssetPaths); } } } //exclude forbidden documents if (in_array("document", $types)) { if (!$user->isAllowed("documents")) { $forbiddenConditions[] = " `type` != 'document' "; } else { $forbiddenDocumentPaths = Element\Service::findForbiddenPaths("document", $user); if (count($forbiddenDocumentPaths) > 0) { for ($i = 0; $i < count($forbiddenDocumentPaths); $i++) { $forbiddenDocumentPaths[$i] = " (maintype = 'document' AND fullpath not like " . $db->quote($forbiddenDocumentPaths[$i] . "%") . ")"; } $forbiddenConditions[] = implode(" AND ", $forbiddenDocumentPaths); } } } //exclude forbidden objects if (in_array("object", $types)) { if (!$user->isAllowed("objects")) { $forbiddenConditions[] = " `type` != 'object' "; } else { $forbiddenObjectPaths = Element\Service::findForbiddenPaths("object", $user); if (count($forbiddenObjectPaths) > 0) { for ($i = 0; $i < count($forbiddenObjectPaths); $i++) { $forbiddenObjectPaths[$i] = " (maintype = 'object' AND fullpath not like " . $db->quote($forbiddenObjectPaths[$i] . "%") . ")"; } $forbiddenConditions[] = implode(" AND ", $forbiddenObjectPaths); } } } if ($forbiddenConditions) { $conditionParts[] = "(" . implode(" AND ", $forbiddenConditions) . ")"; } if (!empty($query)) { $queryCondition = "( MATCH (`data`,`properties`) AGAINST (" . $db->quote($query) . " IN BOOLEAN MODE) )"; // the following should be done with an exact-search now "ID", because the Element-ID is now in the fulltext index // if the query is numeric the user might want to search by id //if(is_numeric($query)) { //$queryCondition = "(" . $queryCondition . " OR id = " . $db->quote($query) ." )"; //} $conditionParts[] = $queryCondition; } //For objects - handling of bricks $fields = []; $bricks = []; if ($this->getParam("fields")) { $fields = $this->getParam("fields"); foreach ($fields as $f) { $parts = explode("~", $f); if (substr($f, 0, 1) == "~") { // $type = $parts[1]; // $field = $parts[2]; // $keyid = $parts[3]; // key value, ignore for now } elseif (count($parts) > 1) { $bricks[$parts[0]] = $parts[0]; } } } // filtering for objects if ($this->getParam("filter") && $this->getParam("class")) { $class = Object\ClassDefinition::getByName($this->getParam("class")); // add Localized Fields filtering $params = \Zend_Json::decode($this->getParam('filter')); $unlocalizedFieldsFilters = []; $localizedFieldsFilters = []; foreach ($params as $paramConditionObject) { //this loop divides filter parameters to localized and unlocalized groups $definitionExists = in_array('o_' . $paramConditionObject['property'], Object\Service::getSystemFields()) || $class->getFieldDefinition($paramConditionObject['property']); if ($definitionExists) { //TODO: for sure, we can add additional condition like getLocalizedFieldDefinition()->getFieldDefiniton(... $unlocalizedFieldsFilters[] = $paramConditionObject; } else { $localizedFieldsFilters[] = $paramConditionObject; } } //get filter condition only when filters array is not empty //string statements for divided filters $conditionFilters = count($unlocalizedFieldsFilters) ? Object\Service::getFilterCondition(\Zend_Json::encode($unlocalizedFieldsFilters), $class) : null; $localizedConditionFilters = count($localizedFieldsFilters) ? Object\Service::getFilterCondition(\Zend_Json::encode($localizedFieldsFilters), $class) : null; $join = ""; foreach ($bricks as $ob) { $join .= " LEFT JOIN object_brick_query_" . $ob . "_" . $class->getId(); $join .= " `" . $ob . "`"; $join .= " ON `" . $ob . "`.o_id = `object_" . $class->getId() . "`.o_id"; } if (null !== $conditionFilters) { //add condition query for non localised fields $conditionParts[] = "( id IN (SELECT `object_" . $class->getId() . "`.o_id FROM object_" . $class->getId() . $join . " WHERE " . $conditionFilters . ") )"; } if (null !== $localizedConditionFilters) { //add condition query for localised fields $conditionParts[] = "( id IN (SELECT `object_localized_data_" . $class->getId() . "`.ooo_id FROM object_localized_data_" . $class->getId() . $join . " WHERE " . $localizedConditionFilters . " GROUP BY ooo_id " . ") )"; } } if (is_array($types) and !empty($types[0])) { foreach ($types as $type) { $conditionTypeParts[] = $db->quote($type); } if (in_array("folder", $subtypes)) { $conditionTypeParts[] = $db->quote('folder'); } $conditionParts[] = "( maintype IN (" . implode(",", $conditionTypeParts) . ") )"; } if (is_array($subtypes) and !empty($subtypes[0])) { foreach ($subtypes as $subtype) { $conditionSubtypeParts[] = $db->quote($subtype); } $conditionParts[] = "( type IN (" . implode(",", $conditionSubtypeParts) . ") )"; } if (is_array($classnames) and !empty($classnames[0])) { if (in_array("folder", $subtypes)) { $classnames[] = "folder"; } foreach ($classnames as $classname) { $conditionClassnameParts[] = $db->quote($classname); } $conditionParts[] = "( subtype IN (" . implode(",", $conditionClassnameParts) . ") )"; } //filtering for tags $tagIds = $this->getParam("tagIds"); if ($tagIds) { foreach ($tagIds as $tagId) { foreach ($types as $type) { if ($this->getParam("considerChildTags") == "true") { $tag = Pimcore\Model\Element\Tag::getById($tagId); if ($tag) { $tagPath = $tag->getFullIdPath(); $conditionParts[] = "id IN (SELECT cId FROM tags_assignment INNER JOIN tags ON tags.id = tags_assignment.tagid WHERE ctype = " . $db->quote($type) . " AND (id = " . intval($tagId) . " OR idPath LIKE " . $db->quote($tagPath . "%") . "))"; } } else { $conditionParts[] = "id IN (SELECT cId FROM tags_assignment WHERE ctype = " . $db->quote($type) . " AND tagid = " . intval($tagId) . ")"; } } } } if (count($conditionParts) > 0) { $condition = implode(" AND ", $conditionParts); //echo $condition; die(); $searcherList->setCondition($condition); } $searcherList->setOffset($offset); $searcherList->setLimit($limit); // do not sort per default, it is VERY SLOW //$searcherList->setOrder("desc"); //$searcherList->setOrderKey("modificationdate"); $sortingSettings = \Pimcore\Admin\Helper\QueryParams::extractSortingSettings($this->getAllParams()); if ($sortingSettings['orderKey']) { // we need a special mapping for classname as this is stored in subtype column $sortMapping = ["classname" => "subtype"]; $sort = $sortingSettings['orderKey']; if (array_key_exists($sortingSettings['orderKey'], $sortMapping)) { $sort = $sortMapping[$sortingSettings['orderKey']]; } $searcherList->setOrderKey($sortingSettings['orderKey']); } if ($sortingSettings['order']) { $searcherList->setOrder($sortingSettings['order']); } $hits = $searcherList->load(); $elements = []; foreach ($hits as $hit) { $element = Element\Service::getElementById($hit->getId()->getType(), $hit->getId()->getId()); if ($element->isAllowed("list")) { if ($element instanceof Object\AbstractObject) { $data = Object\Service::gridObjectData($element, $fields); } elseif ($element instanceof Document) { $data = Document\Service::gridDocumentData($element); } elseif ($element instanceof Asset) { $data = Asset\Service::gridAssetData($element); } $elements[] = $data; } else { //TODO: any message that view is blocked? //$data = Element\Service::gridElementData($element); } } // only get the real total-count when the limit parameter is given otherwise use the default limit if ($this->getParam("limit")) { $totalMatches = $searcherList->getTotalCount(); } else { $totalMatches = count($elements); } $this->_helper->json(["data" => $elements, "success" => true, "total" => $totalMatches]); $this->removeViewRenderer(); }
/** * @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; } }
/** * @see Object\ClassDefinition\Data::getDataForEditmode * @param array $data * @param null|Model\Object\AbstractObject $object * @return array */ public function getDataForEditmode($data, $object = null) { $return = array(); $visibleFieldsArray = explode(",", $this->getVisibleFields()); $gridFields = (array) $visibleFieldsArray; // add data if (is_array($data) && count($data) > 0) { foreach ($data as $metaObject) { $object = $metaObject->getObject(); if ($object instanceof Object\Concrete) { $columnData = Object\Service::gridObjectData($object, $gridFields); foreach ($this->getColumns() as $c) { $getter = "get" . ucfirst($c['key']); $columnData[$c['key']] = $metaObject->{$getter}(); } $return[] = $columnData; } } } return $return; }
/** * @return mixed */ public function getValueFromParent($key) { $parent = Object\Service::hasInheritableParentObject($this->getObject()); if (!empty($parent)) { $containerGetter = "get" . ucfirst($this->fieldname); $brickGetter = "get" . ucfirst($this->getType()); $getter = "get" . ucfirst($key); if ($parent->{$containerGetter}()->{$brickGetter}()) { return $parent->{$containerGetter}()->{$brickGetter}()->{$getter}(); } } return null; }
public function objectbrickListAction() { $list = new Object\Objectbrick\Definition\Listing(); $list = $list->load(); if ($this->hasParam("class_id") && $this->hasParam("field_name")) { $filteredList = []; $classId = $this->getParam("class_id"); $fieldname = $this->getParam("field_name"); foreach ($list as $type) { /** @var $type Object\Objectbrick\Definition */ $clsDefs = $type->getClassDefinitions(); if (!empty($clsDefs)) { foreach ($clsDefs as $cd) { if ($cd["classname"] == $classId && $cd["fieldname"] == $fieldname) { $filteredList[] = $type; continue; } } } $layout = $type->getLayoutDefinitions(); Object\Service::enrichLayoutDefinition($layout); $type->setLayoutDefinitions($layout); } $list = $filteredList; } $returnValueContainer = new Model\Tool\Admin\EventDataContainer($list); \Pimcore::getEventManager()->trigger("admin.class.objectbrickList.preSendData", $this, ["returnValueContainer" => $returnValueContainer, "objectId" => $this->getParam('object_id')]); $this->_helper->json(["objectbricks" => $list]); }
/** * @see Object_Class_Data::getDataForEditmode * @param float $data * @return float */ public function getDataForEditmode($data, $object = null) { if ($data instanceof Model\Object\Data\CalculatedValue) { $data = Model\Object\Service::getCalculatedFieldValueForEditMode($object, $data); } return $data; }
/** * Fired before information is sent back to the admin UI about an element * @param \Zend_EventManager_Event $e * @throws \Exception */ public static function adminElementGetPreSendData($e) { $element = self::extractElementFromEvent($e); $returnValueContainer = $e->getParam('returnValueContainer'); $data = $returnValueContainer->getData(); //create a new namespace for WorkflowManagement //set some defaults $data['workflowManagement'] = ['hasWorkflowManagement' => false]; if (Workflow\Manager::elementCanAction($element)) { $data['workflowManagement']['hasWorkflowManagement'] = true; //see if we can change the layout $currentUser = Admin::getCurrentUser(); $manager = Workflow\Manager\Factory::getManager($element, $currentUser); $data['workflowManagement']['workflowName'] = $manager->getWorkflow()->getName(); //get the state and status $state = $manager->getElementState(); $data['workflowManagement']['state'] = $manager->getWorkflow()->getStateConfig($state); $status = $manager->getElementStatus(); $data['workflowManagement']['status'] = $manager->getWorkflow()->getStatusConfig($status); if ($element instanceof ConcreteObject) { $workflowLayoutId = $manager->getObjectLayout(); //check for !is_null here as we might want to specify 0 in the workflow config if (!is_null($workflowLayoutId)) { //load the new layout into the object container $validLayouts = Object\Service::getValidLayouts($element); //check that the layout id is valid before trying to load if (!empty($validLayouts)) { //todo check user permissions again if ($validLayouts && $validLayouts[$workflowLayoutId]) { $customLayout = ClassDefinition\CustomLayout::getById($workflowLayoutId); $customLayoutDefinition = $customLayout->getLayoutDefinitions(); Object\Service::enrichLayoutDefinition($customLayoutDefinition, $e->getParam('object')); $data["layout"] = $customLayoutDefinition; } } } } } $returnValueContainer->setData($data); }
/** * @param $shopConfigurations Object\OnlineShopConfiguration */ public function import($shopConfigurations) { if ($shopConfigurations && !is_array($shopConfigurations)) { $shopConfigurations = array($shopConfigurations); } $pageSize = 20; $page = 0; /** @var $shopConfiguration Object\OnlineShopConfiguration */ foreach ($shopConfigurations as $shopConfiguration) { $importDirectory = $shopConfiguration->getTrustedShopReviewsimportDirectory(); $startTime = time(); if ($this->logToConsole) { echo "Importing reviews for " . $shopConfiguration->getFullPath() . " ...\n"; } /** @var $startDate Pimcore\Date */ $startDate = $shopConfiguration->getLastSync(); while (true) { if ($this->logToConsole) { echo "Page=" . $page . "\n"; } $uri = "https://%s:%s@api.trustedshops.com/rest/restricted/v2/shops/%s/reviews.json?page=" . $page . "&size=" . $pageSize; if ($startDate) { $uri .= "&startDate=" . date('Y-m-d', $startDate->getTimestamp() - 3600 * 24 * 30); //get ratins from last 30 days - for some reasons trusted shop sometimes dont show all ratings imediately } $uri = sprintf($uri, $shopConfiguration->getTrustedShopUser(), $shopConfiguration->getTrustedShopPassword(), $shopConfiguration->getTrustedShopKey()); if ($this->logToConsole) { echo $uri . "\n"; } $this->client->setUri($uri); $result = $this->client->request(); if ($result->getStatus() != 200) { $this->logger->error("Status code " . $result->getStatus(), null, null, self::COMPONENT); throw new \Exception("Status Code: " . $result->getStatus()); } $body = $result->getBody(); $data = json_decode($body); if (!$data) { $this->logger->error("Could not decode data " . $body, null, null, self::COMPONENT); throw new \Exception("Could not decode data"); } $response = $data->response; $data = $response->data; $shop = $data->shop; if ($shop->tsId != $shopConfiguration->getTrustedShopKey()) { $this->logger->error("Tsid mismatch", null, null, self::COMPONENT); throw new \Exception("Tsid mismatch"); } $reviews = $shop->reviews; foreach ((array) $reviews as $review) { $uid = $review->UID; $comment = $review->comment; $criterias = $review->criteria; $consumerEmail = $review->consumerEmail; $mark = $review->mark; $markDescription = $review->markDescription; $orderReference = $review->orderReference; $changeDate = $review->changeDate; $creationDate = $review->creationDate; $confirmationDate = $review->confirmationDate; $changeDate = $changeDate ? strtotime($changeDate) : 0; $creationDate = $creationDate ? strtotime($creationDate) : 0; $confirmationDate = $confirmationDate ? strtotime($confirmationDate) : 0; $fc = new Object\Fieldcollection(); foreach ($criterias as $criteria) { $mark = $criteria->mark; $criteriaMarkDescription = $criteria->markDescription; $type = $criteria->type; $item = new Object\Fieldcollection\Data\TrustedShopCriteria(); $item->setMark($mark); $item->setMarkDescription($criteriaMarkDescription); $item->setCriteriaType($type); $fc->add($item); } $reviewObject = $this->getReview($shopConfiguration, $uid, $consumerEmail, $creationDate); $reviewObject->setShopConfig($shopConfiguration); $reviewObject->setUid($uid); $reviewObject->setComment($comment); $reviewObject->setConsumerEmail($consumerEmail); $reviewObject->setReviewConfirmationDate(new Pimcore\Date($confirmationDate)); $reviewObject->setReviewCreationDate(new Pimcore\Date($creationDate)); $reviewObject->setReviewChangeDate(new Pimcore\Date($changeDate)); $reviewObject->setMark($mark); $reviewObject->setMarkDescription($markDescription); $reviewObject->setCritera($fc); $reviewObject->setOrderReference($orderReference); if (!$creationDate) { $path = '/unknown'; } else { $path = '/' . date('Y/m/d', $creationDate); } $path = $importDirectory . $path; $reviewObject->setParent(Object\Service::createFolderByPath($path)); $reviewObject->save(); if ($this->logToConsole) { echo "Saved review " . $reviewObject->getId() . " " . $reviewObject->getFullPath() . "\n"; } $this->logger->info("Updated review " . $reviewObject->getId(), $reviewObject, null, self::COMPONENT); if ($page % 5 == 0) { \Pimcore::collectGarbage(); } } if (count($reviews) < $pageSize) { break; } $page++; } $shopConfiguration->setLastSync(new Pimcore\Date($startTime)); $shopConfiguration->save(); } }
public function paymentAction() { $this->checkIsAllowed(); $this->view->provider = Plugin::getPaymentProviders($this->cart); if ($this->getRequest()->isPost()) { $paymentProvider = reset($this->getParam("payment_provider", array())); foreach ($this->view->provider as $provider) { if ($provider->getIdentifier() == ${$paymentProvider}) { $paymentProvider = $provider; break; } } if (!$provider instanceof Payment) { $this->view->error = "oh shit, not found"; } else { $this->session->order['paymentProvider'] = $provider; $order = new CoreShopOrder(); $order->setKey(uniqid()); $order->setParent(Service::createFolderByPath('/coreshop/orders/' . date('Y/m/d'))); $order->setPublished(true); $order->setLang($this->view->language); $order->setCustomer($this->session->user); $order->setShippingAddress($this->session->order['address']['delivery']); $order->setBillingAddress($this->session->order['address']['billing']); $order->setPaymentProvider($provider->getIdentifier()); $order->setOrderDate(new \Zend_Date()); if ($this->session->order['shippingProvider'] instanceof Shipping) { $order->setShippingProvider($this->session->order['shippingProvider']->getIdentifier()); $order->setShipping($this->session->order['shippingProvider']->getShipping($this->cart)); } else { $order->setShipping(0); } $order->save(); $order->importCart($this->cart); $this->session->orderId = $order->getId(); $this->_helper->viewRenderer($provider->processPayment($order, $this->view->url(array("action" => "paymentreturn"), "coreshop_checkout")), null, true); } } $this->view->headTitle($this->view->translate("Payment")); }
/** * @param $keyId * @param $groupId * @param string $language * @param bool|false $ignoreFallbackLanguage * @return null */ public function getLocalizedKeyValue($groupId, $keyId, $language = "default", $ignoreFallbackLanguage = false, $ignoreDefaultLanguage = false) { $oid = $this->object->getId(); $keyConfig = Model\Object\Classificationstore\DefinitionCache::get($keyId); if ($keyConfig->getType() == "calculatedValue") { $data = new Model\Object\Data\CalculatedValue($this->getFieldname()); $childDef = Model\Object\Classificationstore\Service::getFieldDefinitionFromKeyConfig($keyConfig); $data->setContextualData("classificationstore", $this->getFieldname(), null, $language, $groupId, $keyId, $childDef); $data = Model\Object\Service::getCalculatedFieldValueForEditMode($this->getObject(), $data); return $data; } $fieldDefinition = Model\Object\Classificationstore\Service::getFieldDefinitionFromKeyConfig($keyConfig); $language = $this->getLanguage($language); $data = null; if (array_key_exists($groupId, $this->items) && array_key_exists($keyId, $this->items[$groupId]) && array_key_exists($language, $this->items[$groupId][$keyId])) { $data = $this->items[$groupId][$keyId][$language]; } // check for fallback value if ($fieldDefinition->isEmpty($data) && !$ignoreFallbackLanguage && self::doGetFallbackValues()) { $data = $this->getFallbackValue($groupId, $keyId, $language, $fieldDefinition); } if ($fieldDefinition->isEmpty($data) && !$ignoreDefaultLanguage && $language != "default") { $data = $this->items[$groupId][$keyId]["default"]; } // check for inherited value $doGetInheritedValues = AbstractObject::doGetInheritedValues(); if ($fieldDefinition->isEmpty($data) && $doGetInheritedValues) { $object = $this->getObject(); $class = $object->getClass(); $allowInherit = $class->getAllowInherit(); if ($allowInherit) { if ($object->getParent() instanceof AbstractObject) { $parent = $object->getParent(); while ($parent && $parent->getType() == "folder") { $parent = $parent->getParent(); } if ($parent && ($parent->getType() == "object" || $parent->getType() == "variant")) { if ($parent->getClassId() == $object->getClassId()) { $method = "getLocalizedfields"; if (method_exists($parent, $method)) { $getter = "get" . ucfirst($this->fieldname); $classificationStore = $parent->{$getter}(); if ($classificationStore instanceof Classificationstore) { if ($classificationStore->object->getId() != $this->object->getId()) { $data = $classificationStore->getLocalizedKeyValue($groupId, $keyId, $language, false); } } } } } } } } if ($fieldDefinition && method_exists($fieldDefinition, "preGetData")) { $data = $fieldDefinition->preGetData($this, array("data" => $data, "language" => $language, "name" => $groupId . "-" . $keyId)); } return $data; }
public function replaceAssignmentsAction() { $success = false; $message = ""; $element = Element\Service::getElementById($this->getParam("type"), $this->getParam("id")); $sourceEl = Element\Service::getElementById($this->getParam("sourceType"), $this->getParam("sourceId")); $targetEl = Element\Service::getElementById($this->getParam("targetType"), $this->getParam("targetId")); if ($element && $sourceEl && $targetEl && $this->getParam("sourceType") == $this->getParam("targetType") && $sourceEl->getType() == $targetEl->getType()) { $rewriteConfig = [$this->getParam("sourceType") => [$sourceEl->getId() => $targetEl->getId()]]; if ($element instanceof Document) { $element = Document\Service::rewriteIds($element, $rewriteConfig); } elseif ($element instanceof Object\AbstractObject) { $element = Object\Service::rewriteIds($element, $rewriteConfig); } elseif ($element instanceof Asset) { $element = Asset\Service::rewriteIds($element, $rewriteConfig); } $element->setUserModification($this->getUser()->getId()); $element->save(); $success = true; } else { $message = "source-type and target-type do not match"; } $this->_helper->json(["success" => $success, "message" => $message]); }
public function correctPath() { // set path if ($this->getId() != 1) { // not for the root node if ($this->getParentId() == $this->getId()) { throw new \Exception("ParentID and ID is identical, an element can't be the parent of itself."); } $parent = AbstractObject::getById($this->getParentId()); if ($parent) { // use the parent's path from the database here (getCurrentFullPath), to ensure the path really exists and does not rely on the path // that is currently in the parent object (in memory), because this might have changed but wasn't not saved $this->setPath(str_replace("//", "/", $parent->getCurrentFullPath() . "/")); } else { // parent document doesn't exist anymore, set the parent to to root $this->setParentId(1); $this->setPath("/"); } if (strlen($this->getKey()) < 1) { $this->setKey("---no-valid-key---" . $this->getId()); throw new \Exception("Document requires key, generated key automatically"); } } else { if ($this->getId() == 1) { // some data in root node should always be the same $this->setParentId(0); $this->setPath("/"); $this->setKey(""); $this->setType("folder"); } } if (Service::pathExists($this->getFullPath())) { $duplicate = AbstractObject::getByPath($this->getFullPath()); if ($duplicate instanceof self and $duplicate->getId() != $this->getId()) { throw new \Exception("Duplicate full path [ " . $this->getFullPath() . " ] - cannot save object"); } } if (strlen($this->getFullPath()) > 765) { throw new \Exception("Full path is limited to 765 characters, reduce the length of your parent's path"); } }
/** * returns a unique key for an element * * @param $element * @return string */ public static function getUniqueKey($element) { if ($element instanceof Object\AbstractObject) { return Object\Service::getUniqueKey($element); } elseif ($element instanceof Document) { return Document\Service::getUniqueKey($element); } elseif ($element instanceof Asset) { return Asset\Service::getUniqueKey($element); } }
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 $data * @param $getter * @param $objectFromVersion * @param int $level * @return array */ private function doGetDiffDataForEditmode($data, $getter, $objectFromVersion, $level = 0) { $parent = Object\Service::hasInheritableParentObject($data->getObject()); $item = $data->{$getter}(); if (!$item && !empty($parent)) { $data = $parent->{"get" . ucfirst($this->getName())}(); return $this->doGetDiffDataForEditmode($data, $getter, $objectFromVersion, $level + 1); } if (!$item instanceof Object\Objectbrick\Data\AbstractData) { return null; } try { $collectionDef = Object\Objectbrick\Definition::getByKey($item->getType()); } catch (\Exception $e) { return null; } $result = array(); foreach ($collectionDef->getFieldDefinitions() as $fd) { $fieldData = $this->getDiffDataForField($item, $fd->getName(), $fd, $level, $data->getObject(), $getter, $objectFromVersion); //$fd->getDataForEditmode($item->{$fd->getName()}); $diffdata = array(); foreach ($fieldData as $subdata) { $diffdata["field"] = $this->getName(); $diffdata["key"] = $this->getName() . "~" . $fd->getName(); $diffdata["value"] = $subdata["value"]; $diffdata["type"] = $subdata["type"]; $diffdata["disabled"] = $subdata["disabled"]; // this is not needed anymoe unset($subdata["type"]); unset($subdata["value"]); $diffdata["title"] = $this->getName() . " / " . $subdata["title"]; $brickdata = array("brick" => substr($getter, 3), "name" => $fd->getName(), "subdata" => $subdata); $diffdata["data"] = $brickdata; } $result[] = $diffdata; } return $result; }
/** * @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; }
/** * @static * @param ElementInterface $element * @return ElementInterface */ public static function loadAllFields(ElementInterface $element) { if ($element instanceof Document) { Document\Service::loadAllDocumentFields($element); } else { if ($element instanceof Object\Concrete) { Object\Service::loadAllObjectFields($element); } else { if ($element instanceof Asset) { Asset\Service::loadAllFields($element); } } } return $element; }
/** * @param $object \Object_Abstract * @param array $activeGroups * @return array */ public function recursiveGetActiveGroupsIds($object, $activeGroups = []) { if (!$object) { return; } $getter = "get" . ucfirst($this->getName()); /** @var $classificationStore Object\Classificationstore */ $classificationStore = $object->{$getter}(); $activeGroupIds = $classificationStore->getActiveGroups(); if ($activeGroupIds) { foreach ($activeGroupIds as $groupId => $enabled) { if ($enabled) { $activeGroups[$groupId] = $enabled; } } } $class = $object->getClass(); $inheritanceAllowed = $class->getAllowInherit(); if ($inheritanceAllowed) { $parent = Object\Service::hasInheritableParentObject($object); if ($parent) { $activeGroups = $this->recursiveGetActiveGroupsIds($parent, $activeGroups); } } return $activeGroups; }
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"); } } }
/** * @param $name * @param null $language * @return */ public function getLocalizedValue($name, $language = null, $ignoreFallbackLanguage = false) { $data = null; $language = $this->getLanguage($language); $fieldDefinition = $this->getObject()->getClass()->getFieldDefinition("localizedfields")->getFieldDefinition($name); if ($fieldDefinition instanceof Model\Object\ClassDefinition\Data\CalculatedValue) { $valueData = new Model\Object\Data\CalculatedValue($fieldDefinition->getName()); $valueData->setContextualData("localizedfield", "localizedfields", null, $language); $data = Service::getCalculatedFieldValue($this->getObject(), $valueData); return $data; } if ($this->languageExists($language)) { if (array_key_exists($name, $this->items[$language])) { $data = $this->items[$language][$name]; } } // check for inherited value $doGetInheritedValues = AbstractObject::doGetInheritedValues(); if ($fieldDefinition->isEmpty($data) && $doGetInheritedValues) { $object = $this->getObject(); $class = $object->getClass(); $allowInherit = $class->getAllowInherit(); if ($allowInherit) { if ($object->getParent() instanceof AbstractObject) { $parent = $object->getParent(); while ($parent && $parent->getType() == "folder") { $parent = $parent->getParent(); } if ($parent && ($parent->getType() == "object" || $parent->getType() == "variant")) { if ($parent->getClassId() == $object->getClassId()) { $method = "getLocalizedfields"; if (method_exists($parent, $method)) { $localizedFields = $parent->getLocalizedFields(); if ($localizedFields instanceof Localizedfield) { if ($localizedFields->object->getId() != $this->object->getId()) { $data = $localizedFields->getLocalizedValue($name, $language, true); } } } } } } } } // check for fallback value if ($fieldDefinition->isEmpty($data) && !$ignoreFallbackLanguage && self::doGetFallbackValues()) { foreach (Tool::getFallbackLanguagesFor($language) as $l) { if ($this->languageExists($l)) { if (array_key_exists($name, $this->items[$l])) { $data = $this->getLocalizedValue($name, $l); } } } } if ($fieldDefinition && method_exists($fieldDefinition, "preGetData")) { $data = $fieldDefinition->preGetData($this, array("data" => $data, "language" => $language, "name" => $name)); } return $data; }
/** * load lazy loaded fields before cloning * @return void */ public function __clone() { parent::__clone(); Service::loadAllObjectFields($this); }
public function getAction() { if (intval($this->getParam("id")) < 1) { $this->_helper->json(["success" => false]); } $user = User::getById(intval($this->getParam("id"))); if ($user->isAdmin() && !$this->getUser()->isAdmin()) { throw new \Exception("Only admin users are allowed to modify admin users"); } // workspaces $types = ["asset", "document", "object"]; foreach ($types as $type) { $workspaces = $user->{"getWorkspaces" . ucfirst($type)}(); foreach ($workspaces as $workspace) { $el = Element\Service::getElementById($type, $workspace->getCid()); if ($el) { // direct injection => not nice but in this case ok ;-) $workspace->path = $el->getRealFullPath(); } } } // object <=> user dependencies $userObjects = Object\Service::getObjectsReferencingUser($user->getId()); $userObjectData = []; foreach ($userObjects as $o) { $hasHidden = false; if ($o->isAllowed("list")) { $userObjectData[] = ["path" => $o->getRealFullPath(), "id" => $o->getId(), "subtype" => $o->getClass()->getName()]; } else { $hasHidden = true; } } // get available permissions $availableUserPermissionsList = new User\Permission\Definition\Listing(); $availableUserPermissions = $availableUserPermissionsList->load(); // get available roles $roles = []; $list = new User\Role\Listing(); $list->setCondition("`type` = ?", ["role"]); $list->load(); $roles = []; if (is_array($list->getItems())) { foreach ($list->getItems() as $role) { $roles[] = [$role->getId(), $role->getName()]; } } // unset confidential informations $userData = object2array($user); $contentLanguages = Tool\Admin::reorderWebsiteLanguages($user, Tool::getValidLanguages()); $userData["contentLanguages"] = $contentLanguages; unset($userData["password"]); $availablePerspectives = \Pimcore\Config::getAvailablePerspectives(null); $conf = \Pimcore\Config::getSystemConfig(); $this->_helper->json(["success" => true, "wsenabled" => $conf->webservice->enabled, "user" => $userData, "roles" => $roles, "permissions" => $user->generatePermissionList(), "availablePermissions" => $availableUserPermissions, "availablePerspectives" => $availablePerspectives, "objectDependencies" => ["hasHidden" => $hasHidden, "dependencies" => $userObjectData]]); }
/** * @param mixed $value * @param null $object * @param null $idMapper * @return mixed|null|Object\Localizedfield * @throws \Exception */ public function getFromWebserviceImport($value, $object = null, $idMapper = null) { if (is_array($value)) { $validLanguages = Tool::getValidLanguages(); if (!$idMapper || !$idMapper->ignoreMappingFailures()) { foreach ($value as $v) { if (!in_array($v->language, $validLanguages)) { throw new \Exception("Invalid language in localized fields"); } } } $localizedFields = $object->getLocalizedFields(); if (!$localizedFields) { $localizedFields = new Object\Localizedfield(); } if ($object instanceof Object\Concrete) { $localizedFields->setObject($object); } $user = Tool\Admin::getCurrentUser(); $languagesAllowed = null; if ($user && !$user->isAdmin()) { $languagesAllowed = Object\Service::getLanguagePermissions($object, $user, "lEdit"); if ($languagesAllowed) { $languagesAllowed = array_keys($languagesAllowed); } } foreach ($value as $field) { if ($field instanceof \stdClass) { $field = Tool\Cast::castToClass("\\Pimcore\\Model\\Webservice\\Data\\Object\\Element", $field); } if ($idMapper && $idMapper->ignoreMappingFailures()) { if (!in_array($field->language, $validLanguages)) { continue; } } if ($languagesAllowed && !in_array($field->language, $languagesAllowed)) { //TODO needs to be discussed. Maybe it is better to throw an exception instead of ignoring //the language continue; } if (!$field instanceof Model\Webservice\Data\Object\Element) { throw new \Exception("Invalid import data in field [ {$field->name} ] for language [ {$field->language} ] in localized fields [ " . $this->getName() . " ]"); } $fd = $this->getFielddefinition($field->name); if (!$fd instanceof Object\ClassDefinition\Data) { if ($idMapper && $idMapper->ignoreMappingFailures()) { continue; } throw new \Exception("Unknown field [ {$field->name} ] for language [ {$field->language} ] in localized fields [ " . $this->getName() . " ] "); } else { if ($fd->getFieldtype() != $field->type) { throw new \Exception("Type mismatch for field [ {$field->name} ] for language [ {$field->language} ] in localized fields [ " . $this->getName() . " ]. Should be [ " . $fd->getFieldtype() . " ], but is [ " . $field->type . " ] "); } } $localizedFields->setLocalizedValue($field->name, $this->getFielddefinition($field->name)->getFromWebserviceImport($field->value, $object, $idMapper), $field->language); } return $localizedFields; } else { if (!empty($value)) { throw new \Exception("Invalid data in localized fields"); } else { return null; } } }