/** * @param string $name */ public function removeClass($name) { $class = ClassDefinition::getByName($name); if ($class) { $class->delete(); } }
public static function isInstalled() { $memberClass = ClassDefinition::getByName('Member'); if ($memberClass) { return true; } return false; }
/** * @todo refactor steps into proper methods instead of doing it all in the action * @throws Exception */ public function indexAction() { // reachable via http://your.domain/plugin/Prototyper/admin/index $this->view->previewData = null; $this->view->csvText = $this->getParam('csv'); $this->view->classname = $this->getParam('classname'); $csvData = array(); $rowNr = 0; $rows = str_getcsv($this->view->csvText, "\n"); //parse the rows foreach ($rows as $row) { $rowNr++; $rowData = str_getcsv($row, ";"); $csvData[] = $rowData; if ($rowNr == 1) { $fieldNames = array(); $fieldTitles = array(); foreach ($rowData as $cell) { $fieldTitles[] = $cell; $fieldNames[] = $this->getFieldName($cell); } $csvData[] = $fieldNames; } if ($rowNr > 10) { break; } } $this->view->previewTable = $csvData; $fieldList = array(); foreach ($fieldNames as $fieldName) { $fieldTitle = array_shift($fieldTitles); ob_start(); include __DIR__ . "/../classes/field.json.php"; $fieldList[] = ob_get_clean(); } $fields = implode(',', $fieldList); ob_start(); include __DIR__ . "/../classes/object.json.php"; $jsonText = ob_get_clean(); if ($this->getParam('generate') != '') { $class = Object\ClassDefinition::getByName($this->correctClassname($this->getParam("classname"))); if ($class == null) { $class = Object\ClassDefinition::create(array('name' => $this->correctClassname($this->getParam("classname")), 'userOwner' => $this->user->getId())); $class->save(); } $class = Object\ClassDefinition::getById($class->getId()); $success = Object\ClassDefinition\Service::importClassDefinitionFromJson($class, $jsonText); if ($success) { $this->view->successMessage = '<strong>Class generation successful.</strong>'; } } }
/** * @param null $classId * @throws \Exception */ public function __construct($classId = null) { $class = null; if (is_string($classId)) { $class = Object\ClassDefinition::getByName($classId); } elseif (is_int($classId)) { $class = Object\ClassDefinition::getById($classId); } elseif ($classId !== null) { throw new \Exception("No valid class identifier given (class name or ID)"); } if ($class instanceof Object\ClassDefinition) { $this->setClass($class); } }
public function saveAction() { $object = Object::getById($this->getParam("id")); // set the latest available version for editmode $object = $this->getLatestVersion($object); $object->setUserModification($this->getUser()->getId()); // data if ($this->getParam("data")) { $data = \Zend_Json::decode($this->getParam("data")); foreach ($data as $key => $value) { $fd = $object->getClass()->getFieldDefinition($key); if ($fd) { if ($fd instanceof Object\ClassDefinition\Data\Localizedfields) { $user = Tool\Admin::getCurrentUser(); if (!$user->getAdmin()) { $allowedLanguages = Object\Service::getLanguagePermissions($object, $user, "lEdit"); if (!is_null($allowedLanguages)) { $allowedLanguages = array_keys($allowedLanguages); $submittedLanguages = array_keys($data[$key]); foreach ($submittedLanguages as $submittedLanguage) { if (!in_array($submittedLanguage, $allowedLanguages)) { unset($value[$submittedLanguage]); } } } } } if (method_exists($fd, "isRemoteOwner") and $fd->isRemoteOwner()) { $remoteClass = Object\ClassDefinition::getByName($fd->getOwnerClassName()); $relations = $object->getRelationData($fd->getOwnerFieldName(), false, $remoteClass->getId()); $toAdd = $this->detectAddedRemoteOwnerRelations($relations, $value); $toDelete = $this->detectDeletedRemoteOwnerRelations($relations, $value); if (count($toAdd) > 0 or count($toDelete) > 0) { $this->processRemoteOwnerRelations($object, $toDelete, $toAdd, $fd->getOwnerFieldName()); } } else { $object->setValue($key, $fd->getDataFromEditmode($value, $object)); } } } } // general settings // @TODO: IS THIS STILL NECESSARY? if ($this->getParam("general")) { $general = \Zend_Json::decode($this->getParam("general")); // do not allow all values to be set, will cause problems (eg. icon) if (is_array($general) && count($general) > 0) { foreach ($general as $key => $value) { if (!in_array($key, array("o_id", "o_classId", "o_className", "o_type", "icon", "o_userOwner", "o_userModification"))) { $object->setValue($key, $value); } } } } $object = $this->assignPropertiesFromEditmode($object); // scheduled tasks if ($this->getParam("scheduler")) { $tasks = array(); $tasksData = \Zend_Json::decode($this->getParam("scheduler")); if (!empty($tasksData)) { foreach ($tasksData as $taskData) { $taskData["date"] = strtotime($taskData["date"] . " " . $taskData["time"]); $task = new Model\Schedule\Task($taskData); $tasks[] = $task; } } $object->setScheduledTasks($tasks); } if ($this->getParam("task") == "unpublish") { $object->setPublished(false); } if ($this->getParam("task") == "publish") { $object->setPublished(true); } // unpublish and save version is possible without checking mandatory fields if ($this->getParam("task") == "unpublish" || $this->getParam("task") == "version") { $object->setOmitMandatoryCheck(true); } if ($this->getParam("task") == "publish" && $object->isAllowed("publish") or $this->getParam("task") == "unpublish" && $object->isAllowed("unpublish")) { try { $object->save(); $treeData = array(); $treeData["qtipCfg"] = $object->getElementAdminStyle()->getElementQtipConfig(); $this->_helper->json(array("success" => true, "treeData" => $treeData)); } catch (\Exception $e) { \Logger::log($e); $this->_helper->json(array("success" => false, "message" => $e->getMessage())); } } elseif ($this->getParam("task") == "session") { //$object->_fulldump = true; // not working yet, donno why Tool\Session::useSession(function ($session) use($object) { $key = "object_" . $object->getId(); $session->{$key} = $object; }, "pimcore_objects"); $this->_helper->json(array("success" => true)); } else { if ($object->isAllowed("save")) { try { $object->saveVersion(); $this->_helper->json(array("success" => true)); } catch (\Exception $e) { \Logger::log($e); $this->_helper->json(array("success" => false, "message" => $e->getMessage())); } } } }
/** * @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(); }
/** * @return boolean $isInstalled */ public static function isInstalled() { $entry = Object\ClassDefinition::getByName('CoreShopProduct'); $category = Object\ClassDefinition::getByName('CoreShopProduct'); $cartItem = Object\ClassDefinition::getByName('CoreShopCart'); $cart = Object\ClassDefinition::getByName('CoreShopCartItem'); $order = Object\ClassDefinition::getByName('CoreShopOrder'); $orderItem = Object\ClassDefinition::getByName('CoreShopOrderItem'); $orderPayment = Object\ClassDefinition::getByName('CoreShopPayment'); //$cartRule = Object\ClassDefinition::getByName('CoreShopCartRule'); $orderState = Object\ClassDefinition::getByName('CoreShopOrderState'); if ($entry && $category && $cart && $cartItem && $order && $orderItem && $orderPayment && $orderState) { return true; } return false; }
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)); }
/** * @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(); }
/** * @param $objectBrick * @param $json * @return bool */ public static function importObjectBrickFromJson($objectBrick, $json, $throwException = false) { $importData = \Zend_Json::decode($json); // reverse map the class name to the class ID, see: self::generateObjectBrickJson() if (is_array($importData["classDefinitions"])) { foreach ($importData["classDefinitions"] as &$cd) { if (!is_numeric($cd["classname"])) { $class = Object\ClassDefinition::getByName($cd["classname"]); if ($class) { $cd["classname"] = $class->getId(); } } } } $layout = self::generateLayoutTreeFromArray($importData["layoutDefinitions"], $throwException); $objectBrick->setLayoutDefinitions($layout); $objectBrick->setClassDefinitions($importData["classDefinitions"]); $objectBrick->setParentClass($importData["parentClass"]); $objectBrick->save(); return true; }
protected function execute(InputInterface $input, OutputInterface $output) { $newsletter = Model\Tool\Newsletter\Config::getByName($input->getArgument("id")); if ($newsletter) { $pidFile = $newsletter->getPidFile(); if (file_exists($pidFile)) { \Logger::alert("Cannot send newsletters because there's already one active sending process"); exit; } $elementsPerLoop = 10; $objectList = "\\Pimcore\\Model\\Object\\" . ucfirst($newsletter->getClass()) . "\\Listing"; $list = new $objectList(); $conditions = array("(newsletterActive = 1 AND newsletterConfirmed = 1)"); if ($newsletter->getObjectFilterSQL()) { $conditions[] = $newsletter->getObjectFilterSQL(); } if ($newsletter->getPersonas()) { $class = Model\Object\ClassDefinition::getByName($newsletter->getClass()); if ($class && $class->getFieldDefinition("persona")) { $personas = array(); $p = explode(",", $newsletter->getPersonas()); if ($class->getFieldDefinition("persona") instanceof \Pimcore\Model\Object\ClassDefinition\Data\Persona) { foreach ($p as $value) { if (!empty($value)) { $personas[] = $list->quote($value); } } $conditions[] = "persona IN (" . implode(",", $personas) . ")"; } else { if ($class->getFieldDefinition("persona") instanceof \Pimcore\Model\Object\ClassDefinition\Data\Personamultiselect) { $personasCondition = array(); foreach ($p as $value) { $personasCondition[] = "persona LIKE " . $list->quote("%," . $value . ",%"); } $conditions[] = "(" . implode(" OR ", $personasCondition) . ")"; } } } } $list->setCondition(implode(" AND ", $conditions)); $list->setOrderKey("email"); $list->setOrder("ASC"); $elementsTotal = $list->getTotalCount(); $count = 0; $pidContents = array("start" => time(), "lastUpdate" => time(), "newsletter" => $newsletter->getName(), "total" => $elementsTotal, "current" => $count); $this->writePid($pidFile, $pidContents); for ($i = 0; $i < ceil($elementsTotal / $elementsPerLoop); $i++) { $list->setLimit($elementsPerLoop); $list->setOffset($i * $elementsPerLoop); $objects = $list->load(); foreach ($objects as $object) { try { $count++; \Logger::info("Sending newsletter " . $count . " / " . $elementsTotal . " [" . $newsletter->getName() . "]"); \Pimcore\Tool\Newsletter::sendMail($newsletter, $object, null, $input->getArgument("hostUrl")); $note = new Model\Element\Note(); $note->setElement($object); $note->setDate(time()); $note->setType("newsletter"); $note->setTitle("sent newsletter: '" . $newsletter->getName() . "'"); $note->setUser(0); $note->setData(array()); $note->save(); \Logger::info("Sent newsletter to: " . $this->obfuscateEmail($object->getEmail()) . " [" . $newsletter->getName() . "]"); } catch (\Exception $e) { \Logger::err($e); } } // check if pid exists if (!file_exists($pidFile)) { \Logger::alert("Newsletter PID not found, cancel sending process"); exit; } // update pid $pidContents["lastUpdate"] = time(); $pidContents["current"] = $count; $this->writePid($pidFile, $pidContents); \Pimcore::collectGarbage(); } // remove pid @unlink($pidFile); } else { \Logger::emerg("Newsletter '" . $input->getArgument("id") . "' doesn't exist"); } }
public function buildOptions() { $classes = $this->classes; $options = array(); if (is_array($classes)) { foreach ($classes as $class) { $class = ClassDefinition::getByName($class); if ($class instanceof ClassDefinition) { $listClassName = "Pimcore\\Model\\Object\\" . $class->getName() . "\\Listing"; $listObject = new $listClassName(); $listObject->getObjects(); foreach ($listObject as $listItem) { $options[] = array("key" => $listItem->getKey(), "value" => $listItem->getId(), "path" => $listItem->getFullPath()); } } } } $this->setOptions($options); }
/** * returns array of email addresses for batch sending * * @return SendingParamContainer[] */ public function getMailAddressesForBatchSending() { $listing = $this->getListing(); $ids = $listing->loadIdList(); $class = ClassDefinition::getByName($this->class); $tableName = "object_" . $class->getId(); $db = \Pimcore\Db::get(); $emails = $db->fetchCol("SELECT email FROM {$tableName} WHERE o_id IN (" . implode(",", $ids) . ")"); $containers = []; foreach ($emails as $email) { $containers[] = new SendingParamContainer($email, ['emailAddress' => $email]); } return $containers; }
$newsletter = Model\Tool\Newsletter\Config::getByName($argv[1]); if ($newsletter) { $pidFile = $newsletter->getPidFile(); if (file_exists($pidFile)) { \Logger::alert("Cannot send newsletters because there's already one active sending process"); exit; } $elementsPerLoop = 10; $objectList = "\\Pimcore\\Model\\Object\\" . ucfirst($newsletter->getClass()) . "\\Listing"; $list = new $objectList(); $conditions = array("(newsletterActive = 1 AND newsletterConfirmed = 1)"); if ($newsletter->getObjectFilterSQL()) { $conditions[] = $newsletter->getObjectFilterSQL(); } if ($newsletter->getPersonas()) { $class = Model\Object\ClassDefinition::getByName($newsletter->getClass()); if ($class && $class->getFieldDefinition("persona")) { $personas = array(); $p = explode(",", $newsletter->getPersonas()); if ($class->getFieldDefinition("persona") instanceof \Pimcore\Model\Object\ClassDefinition\Data\Persona) { foreach ($p as $value) { if (!empty($value)) { $personas[] = $list->quote($value); } } $conditions[] = "persona IN (" . implode(",", $personas) . ")"; } else { if ($class->getFieldDefinition("persona") instanceof \Pimcore\Model\Object\ClassDefinition\Data\Personamultiselect) { $personasCondition = array(); foreach ($p as $value) { $personasCondition[] = "persona LIKE " . $list->quote("%," . $value . ",%");
/** * * Checks if an object is an allowed relation * @param Model\Object\AbstractObject $object * @return boolean */ protected function allowObjectRelation($object) { //only relations of owner type are allowed $ownerClass = Object\ClassDefinition::getByName($this->getOwnerClassName()); if ($ownerClass->getId() > 0 and $ownerClass->getId() == $object->getClassId()) { $fd = $ownerClass->getFieldDefinition($this->getOwnerFieldName()); if ($fd instanceof Object\ClassDefinition\Data\Objects) { return $fd->allowObjectRelation($object); } } else { return false; } }
/** * @throws \Exception * @param $rootElement * @param $apiKey * @param $path * @param $apiElement * @param bool $overwrite * @param $elementCounter * @return Element\ElementInterface */ public function create($rootElement, $apiKey, $path, $apiElement, $overwrite, $elementCounter) { //correct relative path if (strpos($path, "/") !== 0) { $path = $rootElement->getFullPath() . "/" . $path; } $type = $apiElement->type; if ($apiElement instanceof Webservice\Data\Asset) { $className = "\\Pimcore\\Model\\Asset\\" . ucfirst($type); $parentClassName = "\\Pimcore\\Model\\Asset"; $maintype = "asset"; $fullPath = $path . $apiElement->filename; } else { if ($apiElement instanceof Webservice\Data\Object) { $maintype = "object"; if ($type == "object") { $className = "\\Pimcore\\Model\\Object\\" . ucfirst($apiElement->className); if (!Tool::classExists($className)) { throw new \Exception("Unknown class [ " . $className . " ]"); } } else { $className = "\\Pimcore\\Model\\Object\\" . ucfirst($type); } $parentClassName = "\\Pimcore\\Model\\Object"; $fullPath = $path . $apiElement->key; } else { if ($apiElement instanceof Webservice\Data\Document) { $maintype = "document"; $className = "\\Pimcore\\Model\\Document\\" . ucfirst($type); $parentClassName = "\\Pimcore\\Model\\Document"; $fullPath = $path . $apiElement->key; } else { throw new \Exception("Unknown import element"); } } } $existingElement = $className::getByPath($fullPath); if ($overwrite && $existingElement) { $apiElement->parentId = $existingElement->getParentId(); return $existingElement; } $element = new $className(); $element->setId(null); $element->setCreationDate(time()); if ($element instanceof Asset) { $element->setFilename($apiElement->filename); $element->setData(base64_decode($apiElement->data)); } else { if ($element instanceof Object\Concrete) { $element->setKey($apiElement->key); $element->setClassName($apiElement->className); $class = Object\ClassDefinition::getByName($apiElement->className); if (!$class instanceof Object\ClassDefinition) { throw new \Exception("Unknown object class [ " . $apiElement->className . " ] "); } $element->setClassId($class->getId()); } else { $element->setKey($apiElement->key); } } $this->setModificationParams($element, true); $key = $element->getKey(); if (empty($key) and $apiElement->id == 1) { if ($element instanceof Asset) { $element->setFilename("home_" . uniqid()); } else { $element->setKey("home_" . uniqid()); } } else { if (empty($key)) { throw new \Exception("Cannot create element without key "); } } $parent = $parentClassName::getByPath($path); if (Element\Service::getType($rootElement) == $maintype and $parent) { $element->setParentId($parent->getId()); $apiElement->parentId = $parent->getId(); $existingElement = $parentClassName::getByPath($parent->getFullPath() . "/" . $element->getKey()); if ($existingElement) { //set dummy key to avoid duplicate paths if ($element instanceof Asset) { $element->setFilename(str_replace("/", "_", $apiElement->path) . uniqid() . "_" . $elementCounter . "_" . $element->getFilename()); } else { $element->setKey(str_replace("/", "_", $apiElement->path) . uniqid() . "_" . $elementCounter . "_" . $element->getKey()); } } } else { if (Element\Service::getType($rootElement) != $maintype) { //this is a related element - try to import it to it's original path or set the parent to home folder $potentialParent = $parentClassName::getByPath($path); //set dummy key to avoid duplicate paths if ($element instanceof Asset) { $element->setFilename(str_replace("/", "_", $apiElement->path) . uniqid() . "_" . $elementCounter . "_" . $element->getFilename()); } else { $element->setKey(str_replace("/", "_", $apiElement->path) . uniqid() . "_" . $elementCounter . "_" . $element->getKey()); } if ($potentialParent) { $element->setParentId($potentialParent->getId()); //set actual id and path for second run $apiElements[$apiKey]["path"] = $potentialParent->getFullPath(); $apiElement->parentId = $potentialParent->getId(); } else { $element->setParentId(1); //set actual id and path for second run $apiElements[$apiKey]["path"] = "/"; $apiElement->parentId = 1; } } else { $element->setParentId($rootElement->getId()); //set actual id and path for second run $apiElements[$apiKey]["path"] = $rootElement->getFullPath(); $apiElement->parentId = $rootElement->getId(); //set dummy key to avoid duplicate paths if ($element instanceof Asset) { $element->setFilename(str_replace("/", "_", $apiElement->path) . uniqid() . "_" . $elementCounter . "_" . $element->getFilename()); } else { $element->setKey(str_replace("/", "_", $apiElement->path) . uniqid() . "_" . $elementCounter . "_" . $element->getKey()); } } } //if element exists, make temp key permanent by setting it in apiElement if ($parentClassName::getByPath($fullPath)) { if ($element instanceof Asset) { $apiElement->filename = $element->getFilename(); } else { $apiElement->key = $element->getKey(); } } $element->save(); //todo save type and id for later rollback $this->importInfo[Element\Service::getType($element) . "_" . $element->getId()] = array("id" => $element->getId(), "type" => Element\Service::getType($element), "fullpath" => $element->getFullPath()); return $element; }
/** * Try to load definition by name * * @param $name * @return AbstractModel|null */ protected function loadDefinition($name) { return ClassDefinition::getByName($name); }
/** * @param $classname * @param $filepath * @throws \Exception */ private static function createClass($classname, $filepath) { $class = \Pimcore\Model\Object\ClassDefinition::getByName($classname); if (!$class) { $class = new \Pimcore\Model\Object\ClassDefinition(); $class->setName($classname); } $json = file_get_contents($filepath); $success = \Pimcore\Model\Object\ClassDefinition\Service::importClassDefinitionFromJson($class, $json); if (!$success) { throw new \Exception("Could not import {$classname} Class."); } }
/** * See http://www.pimcore.org/issues/browse/PIMCORE-2358 * Add option to export/import all class definitions/brick definitions etc. at once */ public function bulkCommitAction() { $filename = $this->getParam("filename"); $data = json_decode($this->getParam("data"), true); $json = @file_get_contents($filename); $json = json_decode($json, true); $type = $data["type"]; $name = $data["name"]; $list = $json[$type]; foreach ($list as $item) { unset($item["creationDate"]); unset($item["modificationDate"]); unset($item["userOwner"]); unset($item["userModification"]); unset($item["id"]); if ($type == "class" && $item["name"] == $name) { $class = Object\ClassDefinition::getByName($name); if (!$class) { $class = new Object\ClassDefinition(); $class->setName($name); } $success = Object\ClassDefinition\Service::importClassDefinitionFromJson($class, json_encode($item), true); $this->_helper->json(["success" => $success !== false]); } elseif ($type == "objectbrick" && $item["key"] == $name) { try { $brick = Object\Objectbrick\Definition::getByKey($name); } catch (\Exception $e) { $brick = new Object\Objectbrick\Definition(); $brick->setKey($name); } $success = Object\ClassDefinition\Service::importObjectBrickFromJson($brick, json_encode($item), true); $this->_helper->json(["success" => $success !== false]); } elseif ($type == "fieldcollection" && $item["key"] == $name) { try { $fieldCollection = Object\Fieldcollection\Definition::getByKey($name); } catch (\Exception $e) { $fieldCollection = new Object\Fieldcollection\Definition(); $fieldCollection->setKey($name); } $success = Object\ClassDefinition\Service::importFieldCollectionFromJson($fieldCollection, json_encode($item), true); $this->_helper->json(["success" => $success !== false]); } elseif ($type == "customlayout") { $layoutData = unserialize($data["name"]); $className = $layoutData["className"]; $layoutName = $layoutData["name"]; if ($item["name"] == $layoutName && $item["className"] == $className) { $class = Object\ClassDefinition::getByName($className); if (!$class) { throw new \Exception("Class does not exist"); } $classId = $class->getId(); $layoutList = new Object\ClassDefinition\CustomLayout\Listing(); $db = \Pimcore\Db::get(); $layoutList->setCondition("name = " . $db->quote($layoutName) . " AND classId = " . $classId); $layoutList = $layoutList->load(); $layoutDefinition = null; if ($layoutList) { $layoutDefinition = $layoutList[0]; } if (!$layoutDefinition) { $layoutDefinition = new Object\ClassDefinition\CustomLayout(); $layoutDefinition->setName($layoutName); $layoutDefinition->setClassId($classId); } try { $layoutDefinition->setDescription($item["description"]); $layoutDef = Object\ClassDefinition\Service::generateLayoutTreeFromArray($item["layoutDefinitions"], true); $layoutDefinition->setLayoutDefinitions($layoutDef); $layoutDefinition->save(); } catch (\Exception $e) { Logger::error($e->getMessage()); $this->_helper->json(["success" => false, "message" => $e->getMessage()]); } } } } $this->_helper->json(["success" => true]); }