vendor/pimcore/pimcore/models/DataObject/AbstractObject.php line 367

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Commercial License (PCL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PCL
  13.  */
  14. namespace Pimcore\Model\DataObject;
  15. use Doctrine\DBAL\Exception\RetryableException;
  16. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  17. use Pimcore\Cache;
  18. use Pimcore\Cache\RuntimeCache;
  19. use Pimcore\Db;
  20. use Pimcore\Event\DataObjectEvents;
  21. use Pimcore\Event\Model\DataObjectEvent;
  22. use Pimcore\Logger;
  23. use Pimcore\Model;
  24. use Pimcore\Model\DataObject;
  25. use Pimcore\Model\Element;
  26. use Pimcore\Model\Element\DuplicateFullPathException;
  27. /**
  28.  * @method AbstractObject\Dao getDao()
  29.  * @method array|null getPermissions(?string $type, Model\User $user, bool $quote = true)
  30.  * @method bool __isBasedOnLatestData()
  31.  * @method string getCurrentFullPath()
  32.  * @method int getChildAmount($objectTypes = [DataObject::OBJECT_TYPE_OBJECT, DataObject::OBJECT_TYPE_FOLDER], Model\User $user = null)
  33.  * @method array getChildPermissions(?string $type, Model\User $user, bool $quote = true)
  34.  */
  35. abstract class AbstractObject extends Model\Element\AbstractElement
  36. {
  37.     const OBJECT_TYPE_FOLDER 'folder';
  38.     const OBJECT_TYPE_OBJECT 'object';
  39.     const OBJECT_TYPE_VARIANT 'variant';
  40.     const OBJECT_CHILDREN_SORT_BY_DEFAULT 'key';
  41.     const OBJECT_CHILDREN_SORT_BY_INDEX 'index';
  42.     const OBJECT_CHILDREN_SORT_ORDER_DEFAULT 'ASC';
  43.     /**
  44.      * possible types of a document
  45.      *
  46.      * @var array
  47.      */
  48.     public static $types = [self::OBJECT_TYPE_FOLDERself::OBJECT_TYPE_OBJECTself::OBJECT_TYPE_VARIANT];
  49.     /**
  50.      * @var bool
  51.      */
  52.     private static $hideUnpublished false;
  53.     /**
  54.      * @var bool
  55.      */
  56.     private static $getInheritedValues false;
  57.     /**
  58.      * @internal
  59.      *
  60.      * @var bool
  61.      */
  62.     protected static $disableDirtyDetection false;
  63.     /**
  64.      * @internal
  65.      *
  66.      * @var string[]
  67.      */
  68.     protected static $objectColumns = ['o_id''o_parentid''o_type''o_key''o_classid''o_classname''o_path'];
  69.     /**
  70.      * @internal
  71.      *
  72.      * @deprecated
  73.      *
  74.      * @var int|null
  75.      */
  76.     protected $o_id;
  77.     /**
  78.      * @internal
  79.      *
  80.      * @deprecated
  81.      *
  82.      * @var int|null
  83.      */
  84.     protected $o_parentId;
  85.     /**
  86.      * @internal
  87.      *
  88.      * @deprecated
  89.      */
  90.     protected $o_parent;
  91.     /**
  92.      * @internal
  93.      *
  94.      * @var string
  95.      */
  96.     protected $o_type 'object';
  97.     /**
  98.      * @internal
  99.      *
  100.      * @var string|null
  101.      */
  102.     protected $o_key;
  103.     /**
  104.      * @internal
  105.      *
  106.      * @deprecated
  107.      *
  108.      * @var string|null
  109.      */
  110.     protected $o_path;
  111.     /**
  112.      * @internal
  113.      *
  114.      * @var int
  115.      */
  116.     protected $o_index 0;
  117.     /**
  118.      * @internal
  119.      *
  120.      * @deprecated
  121.      *
  122.      * @var int|null
  123.      */
  124.     protected $o_creationDate;
  125.     /**
  126.      * @internal
  127.      *
  128.      * @deprecated
  129.      *
  130.      * @var int|null
  131.      */
  132.     protected $o_modificationDate;
  133.     /**
  134.      * @internal
  135.      *
  136.      * @deprecated
  137.      *
  138.      * @var int|null
  139.      */
  140.     protected ?int $o_userOwner null;
  141.     /**
  142.      * @internal
  143.      *
  144.      * @deprecated
  145.      *
  146.      * @var int|null
  147.      */
  148.     protected ?int $o_userModification null;
  149.     /**
  150.      * @internal
  151.      *
  152.      * @var bool[]
  153.      */
  154.     protected $o_hasChildren = [];
  155.     /**
  156.      * Contains a list of sibling documents
  157.      *
  158.      * @internal
  159.      *
  160.      * @var array
  161.      */
  162.     protected $o_siblings = [];
  163.     /**
  164.      * Indicator if object has siblings or not
  165.      *
  166.      * @internal
  167.      *
  168.      * @var bool[]
  169.      */
  170.     protected $o_hasSiblings = [];
  171.     /**
  172.      * @internal
  173.      *
  174.      * @var array
  175.      */
  176.     protected $o_children = [];
  177.     /**
  178.      * @internal
  179.      *
  180.      * @deprecated
  181.      *
  182.      * @var string
  183.      */
  184.     protected $o_locked;
  185.     /**
  186.      * @internal
  187.      *
  188.      * @var string|null
  189.      */
  190.     protected $o_childrenSortBy;
  191.     /**
  192.      * @internal
  193.      *
  194.      * @var string|null
  195.      */
  196.     protected $o_childrenSortOrder;
  197.     /**
  198.      * @internal
  199.      *
  200.      * @deprecated
  201.      *
  202.      * @var int
  203.      */
  204.     protected $o_versionCount 0;
  205.     /**
  206.      * @internal
  207.      *
  208.      * @deprecated
  209.      *
  210.      * @var array|null
  211.      */
  212.     protected $o_properties null;
  213.     public function __construct()
  214.     {
  215.         $this->o_id = & $this->id;
  216.         $this->o_path = & $this->path;
  217.         $this->o_creationDate = & $this->creationDate;
  218.         $this->o_userOwner = & $this->userOwner;
  219.         $this->o_versionCount = & $this->versionCount;
  220.         $this->o_modificationDate = & $this->modificationDate;
  221.         $this->o_locked = & $this->locked;
  222.         $this->o_parent = & $this->parent;
  223.         $this->o_properties = & $this->properties;
  224.         $this->o_userModification = & $this->userModification;
  225.         $this->o_parentId = & $this->parentId;
  226.     }
  227.     /**
  228.      * {@inheritdoc}
  229.      */
  230.     protected function getBlockedVars(): array
  231.     {
  232.         $blockedVars = ['o_hasChildren''o_versions''o_class''scheduledTasks''o_parent''parent''omitMandatoryCheck'];
  233.         if ($this->isInDumpState()) {
  234.             // this is if we want to make a full dump of the object (eg. for a new version), including children for recyclebin
  235.             $blockedVars array_merge($blockedVars, ['o_dirtyFields']);
  236.         } else {
  237.             // this is if we want to cache the object
  238.             $blockedVars array_merge($blockedVars, ['o_children''properties''o_properties']);
  239.         }
  240.         return $blockedVars;
  241.     }
  242.     /**
  243.      * @static
  244.      *
  245.      * @return bool
  246.      */
  247.     public static function getHideUnpublished()
  248.     {
  249.         return self::$hideUnpublished;
  250.     }
  251.     /**
  252.      * @static
  253.      *
  254.      * @param bool $hideUnpublished
  255.      */
  256.     public static function setHideUnpublished($hideUnpublished)
  257.     {
  258.         self::$hideUnpublished $hideUnpublished;
  259.     }
  260.     /**
  261.      * @static
  262.      *
  263.      * @return bool
  264.      */
  265.     public static function doHideUnpublished()
  266.     {
  267.         return self::$hideUnpublished;
  268.     }
  269.     /**
  270.      * @static
  271.      *
  272.      * @param bool $getInheritedValues
  273.      */
  274.     public static function setGetInheritedValues($getInheritedValues)
  275.     {
  276.         self::$getInheritedValues $getInheritedValues;
  277.     }
  278.     /**
  279.      * @static
  280.      *
  281.      * @return bool
  282.      */
  283.     public static function getGetInheritedValues()
  284.     {
  285.         return self::$getInheritedValues;
  286.     }
  287.     /**
  288.      * @static
  289.      *
  290.      * @param Concrete|null $object
  291.      *
  292.      * @return bool
  293.      */
  294.     public static function doGetInheritedValues(Concrete $object null)
  295.     {
  296.         if (self::$getInheritedValues && $object !== null) {
  297.             $class $object->getClass();
  298.             return $class->getAllowInherit();
  299.         }
  300.         return self::$getInheritedValues;
  301.     }
  302.     /**
  303.      * get possible types
  304.      *
  305.      * @return array
  306.      */
  307.     public static function getTypes()
  308.     {
  309.         return self::$types;
  310.     }
  311.     /**
  312.      * Static helper to get an object by the passed ID
  313.      *
  314.      * @param int $id
  315.      * @param array|bool $force
  316.      *
  317.      * @return static|null
  318.      */
  319.     public static function getById($id$force false)
  320.     {
  321.         if (!is_numeric($id) || $id 1) {
  322.             return null;
  323.         }
  324.         $id = (int)$id;
  325.         $cacheKey self::getCacheKey($id);
  326.         $params Model\Element\Service::prepareGetByIdParams($force__METHOD__func_num_args() > 1);
  327.         if (!$params['force'] && RuntimeCache::isRegistered($cacheKey)) {
  328.             $object RuntimeCache::get($cacheKey);
  329.             if ($object && static::typeMatch($object)) {
  330.                 return $object;
  331.             }
  332.         }
  333.         if ($params['force'] || !($object Cache::load($cacheKey))) {
  334.             $object = new Model\DataObject();
  335.             try {
  336.                 $typeInfo $object->getDao()->getTypeById($id);
  337.                 if (!empty($typeInfo['o_type']) && in_array($typeInfo['o_type'], DataObject::$types)) {
  338.                     if ($typeInfo['o_type'] == DataObject::OBJECT_TYPE_FOLDER) {
  339.                         $className Folder::class;
  340.                     } else {
  341.                         $className 'Pimcore\\Model\\DataObject\\' ucfirst($typeInfo['o_className']);
  342.                     }
  343.                     /** @var AbstractObject $object */
  344.                     $object self::getModelFactory()->build($className);
  345.                     RuntimeCache::set($cacheKey$object);
  346.                     $object->getDao()->getById($id);
  347.                     $object->__setDataVersionTimestamp($object->getModificationDate());
  348.                     Service::recursiveResetDirtyMap($object);
  349.                     // force loading of relation data
  350.                     if ($object instanceof Concrete) {
  351.                         $object->__getRawRelationData();
  352.                     }
  353.                     Cache::save($object$cacheKey);
  354.                 } else {
  355.                     throw new Model\Exception\NotFoundException('No entry for object id ' $id);
  356.                 }
  357.             } catch (Model\Exception\NotFoundException $e) {
  358.                 return null;
  359.             }
  360.         } else {
  361.             RuntimeCache::set($cacheKey$object);
  362.         }
  363.         if (!$object || !static::typeMatch($object)) {
  364.             return null;
  365.         }
  366.         \Pimcore::getEventDispatcher()->dispatch(
  367.             new DataObjectEvent($object, ['params' => $params]),
  368.             DataObjectEvents::POST_LOAD
  369.         );
  370.         return $object;
  371.     }
  372.     /**
  373.      * @param string $path
  374.      * @param array|bool $force
  375.      *
  376.      * @return static|null
  377.      */
  378.     public static function getByPath($path$force false)
  379.     {
  380.         if (!$path) {
  381.             return null;
  382.         }
  383.         $path Model\Element\Service::correctPath($path);
  384.         try {
  385.             $object = new static();
  386.             $object->getDao()->getByPath($path);
  387.             return static::getById($object->getId(), Model\Element\Service::prepareGetByIdParams($force__METHOD__func_num_args() > 1));
  388.         } catch (Model\Exception\NotFoundException $e) {
  389.             return null;
  390.         }
  391.     }
  392.     /**
  393.      * @param array $config
  394.      *
  395.      * @return DataObject\Listing
  396.      *
  397.      * @throws \Exception
  398.      */
  399.     public static function getList($config = [])
  400.     {
  401.         $className DataObject::class;
  402.         // get classname
  403.         if (!in_array(static::class, [__CLASS__Concrete::class, Folder::class], true)) {
  404.             /** @var Concrete $tmpObject */
  405.             $tmpObject = new static();
  406.             if ($tmpObject instanceof Concrete) {
  407.                 $className 'Pimcore\\Model\\DataObject\\' ucfirst($tmpObject->getClassName());
  408.             }
  409.         }
  410.         if (is_array($config)) {
  411.             if (!empty($config['class'])) {
  412.                 $className ltrim($config['class'], '\\');
  413.             }
  414.             if ($className) {
  415.                 $listClass $className '\\Listing';
  416.                 /** @var DataObject\Listing $list */
  417.                 $list self::getModelFactory()->build($listClass);
  418.                 $list->setValues($config);
  419.                 return $list;
  420.             }
  421.         }
  422.         throw new \Exception('Unable to initiate list class - class not found or invalid configuration');
  423.     }
  424.     /**
  425.      * @deprecated will be removed in Pimcore 11
  426.      *
  427.      * @param array $config
  428.      *
  429.      * @return int total count
  430.      */
  431.     public static function getTotalCount($config = [])
  432.     {
  433.         $list = static::getList($config);
  434.         $count $list->getTotalCount();
  435.         return $count;
  436.     }
  437.     /**
  438.      * @internal
  439.      *
  440.      * @param AbstractObject $object
  441.      *
  442.      * @return bool
  443.      */
  444.     protected static function typeMatch(AbstractObject $object)
  445.     {
  446.         return in_array(static::class, [Concrete::class, __CLASS__], true) || $object instanceof static;
  447.     }
  448.     /**
  449.      * @param array $objectTypes
  450.      * @param bool $includingUnpublished
  451.      *
  452.      * @return DataObject[]
  453.      */
  454.     public function getChildren(array $objectTypes = [self::OBJECT_TYPE_OBJECTself::OBJECT_TYPE_FOLDER], $includingUnpublished false)
  455.     {
  456.         $cacheKey $this->getListingCacheKey(func_get_args());
  457.         if (!isset($this->o_children[$cacheKey])) {
  458.             if ($this->getId()) {
  459.                 $list = new Listing();
  460.                 $list->setUnpublished($includingUnpublished);
  461.                 $list->setCondition('o_parentId = ?'$this->getId());
  462.                 $list->setOrderKey(sprintf('o_%s'$this->getChildrenSortBy()));
  463.                 $list->setOrder($this->getChildrenSortOrder());
  464.                 $list->setObjectTypes($objectTypes);
  465.                 $this->o_children[$cacheKey] = $list->load();
  466.                 $this->o_hasChildren[$cacheKey] = (bool) count($this->o_children[$cacheKey]);
  467.             } else {
  468.                 $this->o_children[$cacheKey] = [];
  469.                 $this->o_hasChildren[$cacheKey] = false;
  470.             }
  471.         }
  472.         return $this->o_children[$cacheKey];
  473.     }
  474.     /**
  475.      * Quick test if there are children
  476.      *
  477.      * @param array $objectTypes
  478.      * @param bool|null $includingUnpublished
  479.      *
  480.      * @return bool
  481.      */
  482.     public function hasChildren($objectTypes = [self::OBJECT_TYPE_OBJECTself::OBJECT_TYPE_FOLDER], $includingUnpublished null)
  483.     {
  484.         $cacheKey $this->getListingCacheKey(func_get_args());
  485.         if (isset($this->o_hasChildren[$cacheKey])) {
  486.             return $this->o_hasChildren[$cacheKey];
  487.         }
  488.         return $this->o_hasChildren[$cacheKey] = $this->getDao()->hasChildren($objectTypes$includingUnpublished);
  489.     }
  490.     /**
  491.      * Get a list of the sibling documents
  492.      *
  493.      * @param array $objectTypes
  494.      * @param bool $includingUnpublished
  495.      *
  496.      * @return array
  497.      */
  498.     public function getSiblings(array $objectTypes = [self::OBJECT_TYPE_OBJECTself::OBJECT_TYPE_FOLDER], $includingUnpublished false)
  499.     {
  500.         $cacheKey $this->getListingCacheKey(func_get_args());
  501.         if (!isset($this->o_siblings[$cacheKey])) {
  502.             if ($this->getParentId()) {
  503.                 $list = new Listing();
  504.                 $list->setUnpublished($includingUnpublished);
  505.                 $list->addConditionParam('o_parentId = ?'$this->getParentId());
  506.                 if ($this->getId()) {
  507.                     $list->addConditionParam('o_id != ?'$this->getId());
  508.                 }
  509.                 $list->setOrderKey('o_key');
  510.                 $list->setObjectTypes($objectTypes);
  511.                 $list->setOrder('asc');
  512.                 $this->o_siblings[$cacheKey] = $list->load();
  513.                 $this->o_hasSiblings[$cacheKey] = (bool) count($this->o_siblings[$cacheKey]);
  514.             } else {
  515.                 $this->o_siblings[$cacheKey] = [];
  516.                 $this->o_hasSiblings[$cacheKey] = false;
  517.             }
  518.         }
  519.         return $this->o_siblings[$cacheKey];
  520.     }
  521.     /**
  522.      * Returns true if the object has at least one sibling
  523.      *
  524.      * @param array $objectTypes
  525.      * @param bool|null $includingUnpublished
  526.      *
  527.      * @return bool
  528.      */
  529.     public function hasSiblings($objectTypes = [self::OBJECT_TYPE_OBJECTself::OBJECT_TYPE_FOLDER], $includingUnpublished null)
  530.     {
  531.         $cacheKey $this->getListingCacheKey(func_get_args());
  532.         if (isset($this->o_hasSiblings[$cacheKey])) {
  533.             return $this->o_hasSiblings[$cacheKey];
  534.         }
  535.         return $this->o_hasSiblings[$cacheKey] = $this->getDao()->hasSiblings($objectTypes$includingUnpublished);
  536.     }
  537.     /**
  538.      * @internal
  539.      *
  540.      * @throws \Exception
  541.      */
  542.     protected function doDelete()
  543.     {
  544.         // delete children
  545.         $children $this->getChildren(self::$typestrue);
  546.         if (count($children) > 0) {
  547.             foreach ($children as $child) {
  548.                 $child->delete();
  549.             }
  550.         }
  551.         // remove dependencies
  552.         $d = new Model\Dependency;
  553.         $d->cleanAllForElement($this);
  554.         // remove all properties
  555.         $this->getDao()->deleteAllProperties();
  556.     }
  557.     /**
  558.      * @throws \Exception
  559.      */
  560.     public function delete()
  561.     {
  562.         $this->dispatchEvent(new DataObjectEvent($this), DataObjectEvents::PRE_DELETE);
  563.         $this->beginTransaction();
  564.         try {
  565.             $this->doDelete();
  566.             $this->getDao()->delete();
  567.             $this->commit();
  568.             //clear parent data from registry
  569.             $parentCacheKey self::getCacheKey($this->getParentId());
  570.             if (RuntimeCache::isRegistered($parentCacheKey)) {
  571.                 /** @var AbstractObject $parent * */
  572.                 $parent RuntimeCache::get($parentCacheKey);
  573.                 if ($parent instanceof self) {
  574.                     $parent->setChildren(null);
  575.                 }
  576.             }
  577.         } catch (\Exception $e) {
  578.             try {
  579.                 $this->rollBack();
  580.             } catch (\Exception $er) {
  581.                 // PDO adapter throws exceptions if rollback fails
  582.                 Logger::info((string) $er);
  583.             }
  584.             $failureEvent = new DataObjectEvent($this);
  585.             $failureEvent->setArgument('exception'$e);
  586.             $this->dispatchEvent($failureEventDataObjectEvents::POST_DELETE_FAILURE);
  587.             Logger::crit((string) $e);
  588.             throw $e;
  589.         }
  590.         // empty object cache
  591.         $this->clearDependentCache();
  592.         //clear object from registry
  593.         RuntimeCache::set(self::getCacheKey($this->getId()), null);
  594.         $this->dispatchEvent(new DataObjectEvent($this), DataObjectEvents::POST_DELETE);
  595.     }
  596.     /**
  597.      * @return $this
  598.      *
  599.      * @throws \Exception
  600.      */
  601.     public function save()
  602.     {
  603.         // additional parameters (e.g. "versionNote" for the version note)
  604.         $params = [];
  605.         if (func_num_args() && is_array(func_get_arg(0))) {
  606.             $params func_get_arg(0);
  607.         }
  608.         $isUpdate false;
  609.         $differentOldPath null;
  610.         try {
  611.             $isDirtyDetectionDisabled self::isDirtyDetectionDisabled();
  612.             $preEvent = new DataObjectEvent($this$params);
  613.             if ($this->getId()) {
  614.                 $isUpdate true;
  615.                 $this->dispatchEvent($preEventDataObjectEvents::PRE_UPDATE);
  616.             } else {
  617.                 self::disableDirtyDetection();
  618.                 $this->dispatchEvent($preEventDataObjectEvents::PRE_ADD);
  619.             }
  620.             $params $preEvent->getArguments();
  621.             $this->correctPath();
  622.             // we wrap the save actions in a loop here, so that we can restart the database transactions in the case it fails
  623.             // if a transaction fails it gets restarted $maxRetries times, then the exception is thrown out
  624.             // this is especially useful to avoid problems with deadlocks in multi-threaded environments (forked workers, ...)
  625.             $maxRetries 5;
  626.             for ($retries 0$retries $maxRetries$retries++) {
  627.                 // be sure that unpublished objects in relations are saved also in frontend mode, eg. in importers, ...
  628.                 $hideUnpublishedBackup self::getHideUnpublished();
  629.                 self::setHideUnpublished(false);
  630.                 $this->beginTransaction();
  631.                 try {
  632.                     if (!in_array($this->getType(), self::$types)) {
  633.                         throw new \Exception('invalid object type given: [' $this->getType() . ']');
  634.                     }
  635.                     if (!$isUpdate) {
  636.                         $this->getDao()->create();
  637.                     }
  638.                     // get the old path from the database before the update is done
  639.                     $oldPath null;
  640.                     if ($isUpdate) {
  641.                         $oldPath $this->getDao()->getCurrentFullPath();
  642.                     }
  643.                     // if the old path is different from the new path, update all children
  644.                     // we need to do the update of the children's path before $this->update() because the
  645.                     // inheritance helper needs the correct paths of the children in InheritanceHelper::buildTree()
  646.                     $updatedChildren = [];
  647.                     if ($oldPath && $oldPath != $this->getRealFullPath()) {
  648.                         $differentOldPath $oldPath;
  649.                         $this->getDao()->updateWorkspaces();
  650.                         $updatedChildren $this->getDao()->updateChildPaths($oldPath);
  651.                     }
  652.                     $this->update($isUpdate$params);
  653.                     self::setHideUnpublished($hideUnpublishedBackup);
  654.                     $this->commit();
  655.                     break; // transaction was successfully completed, so we cancel the loop here -> no restart required
  656.                 } catch (\Exception $e) {
  657.                     try {
  658.                         $this->rollBack();
  659.                     } catch (\Exception $er) {
  660.                         // PDO adapter throws exceptions if rollback fails
  661.                         Logger::info((string) $er);
  662.                     }
  663.                     // set "HideUnpublished" back to the value it was originally
  664.                     self::setHideUnpublished($hideUnpublishedBackup);
  665.                     if ($e instanceof UniqueConstraintViolationException) {
  666.                         throw new Element\ValidationException('unique constraint violation'0$e);
  667.                     }
  668.                     if ($e instanceof RetryableException) {
  669.                         // we try to start the transaction $maxRetries times again (deadlocks, ...)
  670.                         if ($retries < ($maxRetries 1)) {
  671.                             $run $retries 1;
  672.                             $waitTime random_int(15) * 100000// microseconds
  673.                             Logger::warn('Unable to finish transaction (' $run ". run) because of the following reason '" $e->getMessage() . "'. --> Retrying in " $waitTime ' microseconds ... (' . ($run 1) . ' of ' $maxRetries ')');
  674.                             usleep($waitTime); // wait specified time until we restart the transaction
  675.                         } else {
  676.                             // if the transaction still fail after $maxRetries retries, we throw out the exception
  677.                             Logger::error('Finally giving up restarting the same transaction again and again, last message: ' $e->getMessage());
  678.                             throw $e;
  679.                         }
  680.                     } else {
  681.                         throw $e;
  682.                     }
  683.                 }
  684.             }
  685.             $additionalTags = [];
  686.             if (isset($updatedChildren) && is_array($updatedChildren)) {
  687.                 foreach ($updatedChildren as $objectId) {
  688.                     $tag 'object_' $objectId;
  689.                     $additionalTags[] = $tag;
  690.                     // remove the child also from registry (internal cache) to avoid path inconsistencies during long running scripts, such as CLI
  691.                     RuntimeCache::set($tagnull);
  692.                 }
  693.             }
  694.             $this->clearDependentCache($additionalTags);
  695.             $postEvent = new DataObjectEvent($this$params);
  696.             if ($isUpdate) {
  697.                 if ($differentOldPath) {
  698.                     $postEvent->setArgument('oldPath'$differentOldPath);
  699.                 }
  700.                 $this->dispatchEvent($postEventDataObjectEvents::POST_UPDATE);
  701.             } else {
  702.                 self::setDisableDirtyDetection($isDirtyDetectionDisabled);
  703.                 $this->dispatchEvent($postEventDataObjectEvents::POST_ADD);
  704.             }
  705.             return $this;
  706.         } catch (\Exception $e) {
  707.             $failureEvent = new DataObjectEvent($this$params);
  708.             $failureEvent->setArgument('exception'$e);
  709.             if ($isUpdate) {
  710.                 $this->dispatchEvent($failureEventDataObjectEvents::POST_UPDATE_FAILURE);
  711.             } else {
  712.                 $this->dispatchEvent($failureEventDataObjectEvents::POST_ADD_FAILURE);
  713.             }
  714.             throw $e;
  715.         }
  716.     }
  717.     /**
  718.      * @internal
  719.      *
  720.      * @throws \Exception|DuplicateFullPathException
  721.      */
  722.     protected function correctPath()
  723.     {
  724.         // set path
  725.         if ($this->getId() != 1) { // not for the root node
  726.             if (!Element\Service::isValidKey($this->getKey(), 'object')) {
  727.                 throw new \Exception('invalid key for object with id [ '.$this->getId().' ] key is: [' $this->getKey() . ']');
  728.             }
  729.             if ($this->getParentId() == $this->getId()) {
  730.                 throw new \Exception("ParentID and ID is identical, an element can't be the parent of itself.");
  731.             }
  732.             $parent DataObject::getById($this->getParentId());
  733.             if ($parent) {
  734.                 // use the parent's path from the database here (getCurrentFullPath), to ensure the path really exists and does not rely on the path
  735.                 // that is currently in the parent object (in memory), because this might have changed but wasn't not saved
  736.                 $this->setPath(str_replace('//''/'$parent->getCurrentFullPath().'/'));
  737.             } else {
  738.                 trigger_deprecation(
  739.                     'pimcore/pimcore',
  740.                     '10.5',
  741.                     'Fallback for parentId will be removed in Pimcore 11.',
  742.                 );
  743.                 // parent document doesn't exist anymore, set the parent to to root
  744.                 $this->setParentId(1);
  745.                 $this->setPath('/');
  746.             }
  747.             if (strlen($this->getKey()) < 1) {
  748.                 throw new \Exception('DataObject requires key');
  749.             }
  750.         } elseif ($this->getId() == 1) {
  751.             // some data in root node should always be the same
  752.             $this->setParentId(0);
  753.             $this->setPath('/');
  754.             $this->setKey('');
  755.             $this->setType(DataObject::OBJECT_TYPE_FOLDER);
  756.         }
  757.         if (Service::pathExists($this->getRealFullPath())) {
  758.             $duplicate DataObject::getByPath($this->getRealFullPath());
  759.             if ($duplicate instanceof self && $duplicate->getId() != $this->getId()) {
  760.                 $duplicateFullPathException = new DuplicateFullPathException('Duplicate full path [ '.$this->getRealFullPath().' ] - cannot save object');
  761.                 $duplicateFullPathException->setDuplicateElement($duplicate);
  762.                 throw $duplicateFullPathException;
  763.             }
  764.         }
  765.         $this->validatePathLength();
  766.     }
  767.     /**
  768.      * @internal
  769.      *
  770.      * @param bool|null $isUpdate
  771.      * @param array $params
  772.      *
  773.      * @throws \Exception
  774.      */
  775.     protected function update($isUpdate null$params = [])
  776.     {
  777.         $this->updateModificationInfos();
  778.         // save properties
  779.         $this->getProperties();
  780.         $this->getDao()->deleteAllProperties();
  781.         if (is_array($this->getProperties()) && count($this->getProperties()) > 0) {
  782.             foreach ($this->getProperties() as $property) {
  783.                 if (!$property->getInherited()) {
  784.                     $property->setDao(null);
  785.                     $property->setCid($this->getId());
  786.                     $property->setCtype('object');
  787.                     $property->setCpath($this->getRealFullPath());
  788.                     $property->save();
  789.                 }
  790.             }
  791.         }
  792.         // save dependencies
  793.         $d = new Model\Dependency();
  794.         $d->setSourceType('object');
  795.         $d->setSourceId($this->getId());
  796.         foreach ($this->resolveDependencies() as $requirement) {
  797.             if ($requirement['id'] == $this->getId() && $requirement['type'] === 'object') {
  798.                 // dont't add a reference to yourself
  799.                 continue;
  800.             }
  801.             $d->addRequirement($requirement['id'], $requirement['type']);
  802.         }
  803.         $d->save();
  804.         //set object to registry
  805.         RuntimeCache::set(self::getCacheKey($this->getId()), $this);
  806.     }
  807.     /**
  808.      * {@inheritdoc}
  809.      */
  810.     public function clearDependentCache($additionalTags = [])
  811.     {
  812.         self::clearDependentCacheByObjectId($this->getId(), $additionalTags);
  813.     }
  814.     /**
  815.      * @internal
  816.      *
  817.      * @param int $objectId
  818.      * @param array $additionalTags
  819.      */
  820.     public static function clearDependentCacheByObjectId($objectId$additionalTags = [])
  821.     {
  822.         if (!$objectId) {
  823.             throw new \Exception('object ID missing');
  824.         }
  825.         try {
  826.             $tags = ['object_' $objectId'object_properties''output'];
  827.             $tags array_merge($tags$additionalTags);
  828.             Cache::clearTags($tags);
  829.         } catch (\Exception $e) {
  830.             Logger::crit((string) $e);
  831.         }
  832.     }
  833.     /**
  834.      * @internal
  835.      *
  836.      * @param int $index
  837.      */
  838.     public function saveIndex($index)
  839.     {
  840.         $this->getDao()->saveIndex($index);
  841.         $this->clearDependentCache();
  842.     }
  843.     /**
  844.      * @return string
  845.      */
  846.     public function getFullPath()
  847.     {
  848.         $path $this->getPath() . $this->getKey();
  849.         return $path;
  850.     }
  851.     /**
  852.      * @return string
  853.      */
  854.     public function getRealPath()
  855.     {
  856.         return $this->getPath();
  857.     }
  858.     /**
  859.      * @return string
  860.      */
  861.     public function getRealFullPath()
  862.     {
  863.         return $this->getFullPath();
  864.     }
  865.     /**
  866.      * @return int|null
  867.      */
  868.     public function getParentId()
  869.     {
  870.         $parentId parent::getParentId();
  871.         // fall back to parent if no ID is set but we have a parent object
  872.         if (!$parentId && $this->parent) {
  873.             return $this->parent->getId();
  874.         }
  875.         return $parentId;
  876.     }
  877.     /**
  878.      * @return string
  879.      */
  880.     public function getType()
  881.     {
  882.         return $this->o_type;
  883.     }
  884.     /**
  885.      * @return string|null
  886.      */
  887.     public function getKey()
  888.     {
  889.         return $this->o_key;
  890.     }
  891.     /**
  892.      * @return int
  893.      */
  894.     public function getIndex()
  895.     {
  896.         return $this->o_index;
  897.     }
  898.     /**
  899.      * @param int $parentId
  900.      *
  901.      * @return $this
  902.      */
  903.     public function setParentId($parentId)
  904.     {
  905.         $parentId = (int) $parentId;
  906.         if ($parentId != $this->parentId) {
  907.             $this->markFieldDirty('parentId');
  908.         }
  909.         parent::setParentId($parentId);
  910.         $this->o_siblings = [];
  911.         $this->o_hasSiblings = [];
  912.         return $this;
  913.     }
  914.     /**
  915.      * @param string $o_type
  916.      *
  917.      * @return $this
  918.      */
  919.     public function setType($o_type)
  920.     {
  921.         $this->o_type $o_type;
  922.         return $this;
  923.     }
  924.     /**
  925.      * @param string $o_key
  926.      *
  927.      * @return $this
  928.      */
  929.     public function setKey($o_key)
  930.     {
  931.         $this->o_key = (string)$o_key;
  932.         return $this;
  933.     }
  934.     /**
  935.      * @param int $o_index
  936.      *
  937.      * @return $this
  938.      */
  939.     public function setIndex($o_index)
  940.     {
  941.         $this->o_index = (int) $o_index;
  942.         return $this;
  943.     }
  944.     /**
  945.      * @param string|null $childrenSortBy
  946.      */
  947.     public function setChildrenSortBy($childrenSortBy)
  948.     {
  949.         if ($this->o_childrenSortBy !== $childrenSortBy) {
  950.             $this->o_children = [];
  951.             $this->o_hasChildren = [];
  952.         }
  953.         $this->o_childrenSortBy $childrenSortBy;
  954.     }
  955.     /**
  956.      * @param DataObject[]|null $children
  957.      * @param array $objectTypes
  958.      * @param bool $includingUnpublished
  959.      *
  960.      * @return $this
  961.      */
  962.     public function setChildren($children, array $objectTypes = [self::OBJECT_TYPE_OBJECTself::OBJECT_TYPE_FOLDER], $includingUnpublished false)
  963.     {
  964.         if ($children === null) {
  965.             // unset all cached children
  966.             $this->o_children = [];
  967.             $this->o_hasChildren = [];
  968.         } elseif (is_array($children)) {
  969.             //default cache key
  970.             $cacheKey $this->getListingCacheKey([$objectTypes$includingUnpublished]);
  971.             $this->o_children[$cacheKey] = $children;
  972.             $this->o_hasChildren[$cacheKey] = (bool) count($children);
  973.         }
  974.         return $this;
  975.     }
  976.     /**
  977.      * @return self|null
  978.      */
  979.     public function getParent() /** : ?self **/
  980.     {
  981.         $parent parent::getParent();
  982.         return $parent instanceof AbstractObject $parent null;
  983.     }
  984.     /**
  985.      * @param self|null $parent
  986.      *
  987.      * @return $this
  988.      */
  989.     public function setParent($parent)
  990.     {
  991.         $newParentId $parent instanceof self $parent->getId() : 0;
  992.         $this->setParentId($newParentId);
  993.         $this->parent $parent;
  994.         return $this;
  995.     }
  996.     /**
  997.      * @return string
  998.      */
  999.     public function getChildrenSortBy()
  1000.     {
  1001.         return $this->o_childrenSortBy ?? self::OBJECT_CHILDREN_SORT_BY_DEFAULT;
  1002.     }
  1003.     /**
  1004.      * @param string $method
  1005.      * @param array $args
  1006.      *
  1007.      * @return mixed
  1008.      *
  1009.      * @throws \Exception
  1010.      */
  1011.     public function __call($method$args)
  1012.     {
  1013.         // compatibility mode (they do not have any set_oXyz() methods anymore)
  1014.         if (preg_match('/^(get|set)o_/i'$method)) {
  1015.             $newMethod preg_replace('/^(get|set)o_/i''$1'$method);
  1016.             if (method_exists($this$newMethod)) {
  1017.                 $r call_user_func_array([$this$newMethod], $args);
  1018.                 return $r;
  1019.             }
  1020.         }
  1021.         return parent::__call($method$args);
  1022.     }
  1023.     /**
  1024.      * @return bool
  1025.      */
  1026.     public static function doNotRestoreKeyAndPath()
  1027.     {
  1028.         return self::$doNotRestoreKeyAndPath;
  1029.     }
  1030.     /**
  1031.      * @param bool $doNotRestoreKeyAndPath
  1032.      */
  1033.     public static function setDoNotRestoreKeyAndPath($doNotRestoreKeyAndPath)
  1034.     {
  1035.         self::$doNotRestoreKeyAndPath $doNotRestoreKeyAndPath;
  1036.     }
  1037.     /**
  1038.      * @param string $fieldName
  1039.      * @param string|null $language
  1040.      *
  1041.      * @throws \Exception
  1042.      *
  1043.      * @return mixed
  1044.      */
  1045.     public function get($fieldName$language null)
  1046.     {
  1047.         if (!$fieldName) {
  1048.             throw new \Exception('Field name must not be empty.');
  1049.         }
  1050.         return $this->{'get'.ucfirst($fieldName)}($language);
  1051.     }
  1052.     /**
  1053.      * @param string $fieldName
  1054.      * @param mixed $value
  1055.      * @param string|null $language
  1056.      *
  1057.      * @throws \Exception
  1058.      *
  1059.      * @return mixed
  1060.      */
  1061.     public function set($fieldName$value$language null)
  1062.     {
  1063.         if (!$fieldName) {
  1064.             throw new \Exception('Field name must not be empty.');
  1065.         }
  1066.         return $this->{'set'.ucfirst($fieldName)}($value$language);
  1067.     }
  1068.     /**
  1069.      * @internal
  1070.      *
  1071.      * @return bool
  1072.      */
  1073.     public static function isDirtyDetectionDisabled()
  1074.     {
  1075.         return self::$disableDirtyDetection;
  1076.     }
  1077.     /**
  1078.      * @internal
  1079.      *
  1080.      * @param bool $disableDirtyDetection
  1081.      */
  1082.     public static function setDisableDirtyDetection(bool $disableDirtyDetection)
  1083.     {
  1084.         self::$disableDirtyDetection $disableDirtyDetection;
  1085.     }
  1086.     /**
  1087.      * @internal
  1088.      */
  1089.     public static function disableDirtyDetection()
  1090.     {
  1091.         self::setDisableDirtyDetection(true);
  1092.     }
  1093.     /**
  1094.      * @internal
  1095.      */
  1096.     public static function enableDirtyDetection()
  1097.     {
  1098.         self::setDisableDirtyDetection(false);
  1099.     }
  1100.     /**
  1101.      * @internal
  1102.      *
  1103.      * @param array $args
  1104.      *
  1105.      * @return string
  1106.      */
  1107.     protected function getListingCacheKey(array $args = [])
  1108.     {
  1109.         $objectTypes $args[0] ?? [self::OBJECT_TYPE_OBJECTself::OBJECT_TYPE_FOLDER];
  1110.         $includingUnpublished = (bool)($args[1] ?? false);
  1111.         if (is_array($objectTypes)) {
  1112.             $objectTypes implode('_'$objectTypes);
  1113.         }
  1114.         $cacheKey $objectTypes . (!empty($includingUnpublished) ? '_' '') . (string)$includingUnpublished;
  1115.         return $cacheKey;
  1116.     }
  1117.     /**
  1118.      * @param string | null $o_reverseSort
  1119.      *
  1120.      * @return AbstractObject
  1121.      */
  1122.     public function setChildrenSortOrder(?string $o_reverseSort): Element\ElementInterface
  1123.     {
  1124.         $this->o_childrenSortOrder $o_reverseSort;
  1125.         return $this;
  1126.     }
  1127.     /**
  1128.      * @return string
  1129.      */
  1130.     public function getChildrenSortOrder(): string
  1131.     {
  1132.         return $this->o_childrenSortOrder ?? self::OBJECT_CHILDREN_SORT_ORDER_DEFAULT;
  1133.     }
  1134.     /**
  1135.      * load lazy loaded fields before cloning
  1136.      */
  1137.     public function __clone()
  1138.     {
  1139.         parent::__clone();
  1140.         // renew references when cloning
  1141.         foreach (['id''path''creationDate''userOwner''versionCount''modificationDate''locked''parent''properties''userModification''parentId'] as $referenceField) {
  1142.             $oldValue $this->$referenceField;
  1143.             unset($this->$referenceField);
  1144.             $this->$referenceField $oldValue;
  1145.             $this->{'o_'.$referenceField} = &$this->$referenceField;
  1146.         }
  1147.         $this->o_parent null;
  1148.         // note that o_children is currently needed for the recycle bin
  1149.         $this->o_hasSiblings = [];
  1150.         $this->o_siblings = [];
  1151.     }
  1152.     /**
  1153.      * @param string $method
  1154.      * @param array $arguments
  1155.      *
  1156.      * @return mixed|Listing|null
  1157.      *
  1158.      * @throws \Exception
  1159.      */
  1160.     public static function __callStatic($method$arguments)
  1161.     {
  1162.         $propertyName lcfirst(preg_replace('/^getBy/i'''$method));
  1163.         $realPropertyName 'o_'.$propertyName;
  1164.         $db \Pimcore\Db::get();
  1165.         if (in_array(strtolower($realPropertyName), self::$objectColumns)) {
  1166.             $arguments array_pad($arguments40);
  1167.             [$value$limit$offset$objectTypes] = $arguments;
  1168.             $defaultCondition $realPropertyName.' = '.Db::get()->quote($value).' ';
  1169.             $listConfig = [
  1170.                 'condition' => $defaultCondition,
  1171.             ];
  1172.             if (!is_array($limit)) {
  1173.                 if ($limit) {
  1174.                     $listConfig['limit'] = $limit;
  1175.                 }
  1176.                 if ($offset) {
  1177.                     $listConfig['offset'] = $offset;
  1178.                 }
  1179.             } else {
  1180.                 $listConfig array_merge($listConfig$limit);
  1181.                 $limitCondition $limit['condition'] ?? '';
  1182.                 $listConfig['condition'] = $defaultCondition.$limitCondition;
  1183.             }
  1184.             $list = static::makeList($listConfig$objectTypes);
  1185.             if (isset($listConfig['limit']) && $listConfig['limit'] == 1) {
  1186.                 $elements $list->getObjects();
  1187.                 return isset($elements[0]) ? $elements[0] : null;
  1188.             }
  1189.             return $list;
  1190.         }
  1191.         // there is no property for the called method, so throw an exception
  1192.         Logger::error('Class: DataObject\\AbstractObject => call to undefined static method ' $method);
  1193.         throw new \Exception('Call to undefined static method ' $method ' in class DataObject\\AbstractObject');
  1194.     }
  1195.     /**
  1196.      * @param  array  $listConfig
  1197.      * @param  mixed $objectTypes
  1198.      *
  1199.      * @return Listing
  1200.      *
  1201.      * @throws \Exception
  1202.      */
  1203.     protected static function makeList(array $listConfigmixed $objectTypes): Listing
  1204.     {
  1205.         $list = static::getList($listConfig);
  1206.         // Check if variants, in addition to objects, to be fetched
  1207.         if (!empty($objectTypes)) {
  1208.             if (\array_diff($objectTypes, [static::OBJECT_TYPE_VARIANT, static::OBJECT_TYPE_OBJECT])) {
  1209.                 Logger::error('Class: DataObject\\AbstractObject => Unsupported object type in array ' implode(','$objectTypes));
  1210.                 throw new \Exception('Unsupported object type in array [' implode(','$objectTypes) . '] in class DataObject\\AbstractObject');
  1211.             }
  1212.             $list->setObjectTypes($objectTypes);
  1213.         }
  1214.         return $list;
  1215.     }
  1216.     public function __wakeup()
  1217.     {
  1218.         $propertyMappings = [
  1219.             'o_id' => 'id',
  1220.             'o_path' => 'path',
  1221.             'o_creationDate' => 'creationDate',
  1222.             'o_userOwner' => 'userOwner',
  1223.             'o_versionCount' => 'versionCount',
  1224.             'o_locked' => 'locked',
  1225.             'o_parent' => 'parent',
  1226.             'o_properties' => 'properties',
  1227.             'o_userModification' => 'userModification',
  1228.             'o_modificationDate' => 'modificationDate',
  1229.             'o_parentId' => 'parentId',
  1230.         ];
  1231.         foreach ($propertyMappings as $oldProperty => $newProperty) {
  1232.             if ($this->$newProperty === null) {
  1233.                 $this->$newProperty $this->$oldProperty;
  1234.                 $this->$oldProperty = & $this->$newProperty;
  1235.             }
  1236.         }
  1237.         parent::__wakeup();
  1238.     }
  1239. }