Linkuje plik
@param string $srcObject obiekt źródłowy
@param int $srcId id źródła
@param string $destObject obiekt docelowy
@param int $destId docelowy id
@return int ilość zlinkowanych
547765
public static function link($srcObject, $srcId, $destObject, $destId)
    {
        $i = 0;
        //kopiowanie plików
        foreach (CmsFileQuery::byObject($srcObject, $srcId)->find() as $file) {
            $newFile = clone $file;
            $newFile->object = $destObject;
            $newFile->objectId = $destId;
            $newFile->id = null;
            $newFile->save();
            $i++;
        }
        return $i;
    }
757616
public function describeAction()
    {
        //sprawdzamy, czy jest id pliku i form
        if (!$this->getPost()->cmsFileId || !is_array($this->getPost()->form)) {
            return $this->_jsonError(186);
        }
        //szukamy rekordu pliku
        if (null === $record = (new CmsFileQuery)->findPk($this->getPost()->cmsFileId)) {
            return $this->_jsonError(186);
        }
        //pobranie danych
        $form = array_merge(['active' => 0, 'sticky' => null], $this->getPost()->form);
        foreach ($form as $field) {
            $form[$field['name']] = $field['value'];
            if ($field['name'] == 'active' || $field['name'] == 'sticky') {
                continue;
            }
            if ($field['name'] == 'original') {
                //dodajemy rozszerzenie
                //pozycja ostatniej kropki w nazwie - rozszerzenie pliku
                $pointPosition = strrpos($record->name, '.');
                if ($pointPosition !== false) {
                    $form['original'] .= substr($record->name, $pointPosition);
                }
                $record->data->original = $form['original'];
                continue;
            }
            $record->data->{$field['name']} = $field['value'];
        }
        //próba zapisu postera
        if (isset($form['poster']) && $form['poster']) {
            $form['posterFileName'] = $this->_savePoster($form['poster'], $record);
        }
        unset($form['poster']);
        if ($record->data instanceof \Mmi\DataObject) {
            //czyszczenie nieprzesłanych checkboxów
            foreach (array_keys($record->data->toArray()) as $name) {
                //nie czyścimy postera jeśli był wgrany
                if ($name == 'posterFileName') {
                    continue;
                }
                if (!isset($form[$name])) {
                    $record->data->{$name} = null;
                }
            }
        }
        $record->active = isset($form['active']) ? $form['active'] : $record->active;
        $record->sticky = isset($form['sticky']) ? $form['sticky'] : $record->sticky;
        $record->original = isset($form['original']) ? $form['original'] : $record->original;
        if ($record->sticky) {
            $result = $record->setSticky();
        } else {
            $result = $record->save();
        }
        if ($result) {
            //jeśli wykonać operację po edycji
            if ($this->getPost()->afterEdit) {
                $this->_operationAfter($this->getPost()->afterEdit, $record);
            }
            return json_encode(['result' => 'OK']);
        }
        return $this->_jsonError(186);
    }
525011
public function cartBlock($pid) {
    $site_commerce = $this->entityTypeManager->getStorage('site_commerce')->load($pid);

    // Проверяем добавлена ли текущая позиция в корзину.
    $position_in_cart = FALSE;
    $databaseSendOrder = \Drupal::service('site_orders.database');
    if ($databaseSendOrder->hasPositionInCart($site_commerce->getEntityTypeId(), $site_commerce->id())) {
      $position_in_cart = TRUE;
    }

    // Тип отображения.
    $type = 'default';
    if ($position_in_cart) {
      // Доступные варианты: default, load_open_cart_form, load_order_form, load_message_form.
      $type = $site_commerce->get('field_cart')->event;
    }

    return [
      '#theme' => 'site_commerce_cart_block',
      '#site_commerce' => $site_commerce,
      '#type' => $type,
    ];
  }
969076
public function resolveEntity(DOMDocumentType $domDocumentType = null)
    {
        if (null === $domDocumentType) {
            $errMsg = 'Отсутствует DOMDocumentType';
            throw new InvalidDtdSchemaException($errMsg);
        }

        $systemId = $domDocumentType->systemId;

        $uri = static::uriFactory($systemId);

        if (!($this->isOpenSymphonyUrl($uri) && $this->isDtdReference($uri))) {
            $errMsg = sprintf('Некорректный uri doctype: %s', $systemId);
            throw new InvalidDtdSchemaException($errMsg);
        }


        $path = $uri->getPath();

        $dtd = $this->localDtd($path);

        return $dtd;
    }
532978
public function setSticky()
    {
        //brak pliku
        if ($this->id === null) {
            return false;
        }
        //wyłącza sticky na innych plikach dla tego object+objectId
        foreach (\Cms\Orm\CmsFileQuery::stickyByObject($this->object, $this->objectId)->find() as $related) {
            $related->sticky = 0;
            $related->save();
        }
        $this->sticky = 1;
        return $this->save();
    }
483931
public static function copy($srcObject, $srcId, $destObject, $destId)
    {
        $i = 0;
        //kopiowanie plików
        foreach (CmsFileQuery::byObject($srcObject, $srcId)->find() as $file) {
            try {
                //tworzenie kopii
                $copy = new \Mmi\Http\RequestFile([
                    'name' => $file->original,
                    'tmp_name' => $file->getRealPath(),
                    'size' => $file->size
                ]);
            } catch (\Mmi\App\KernelException $e) {
                \Mmi\App\FrontController::getInstance()->getLogger()->warning('Unable to copy file, file not found: ' . $file->getRealPath());
                continue;
            }
            $newFile = clone $file;
            $newFile->id = null;
            //dołączanie pliku
            self::_copyFile($copy, $destObject, $destId, $newFile);
            $i++;
        }
        return $i;
    }
670754
public function getNextRecordCode($code = null)
    {
        if (is_null($code)) {
            $code = $this->getMyKey();
        }
        $crID = null;
        if (is_string($code)) {
            $sro = $this->performRequest($this->evidence.'/(kod=\''.$code.'\').json');
            if (count($sro[$this->evidence])) {
                $crID = current(current($sro[$this->evidence]));
            }
        } else {
            $crID = $code;
        }

        $cr                = $this->performRequest($this->evidence.'/'.$crID.'.json');
        $radaPokladniPohyb = current($cr[$this->evidence]);
        $crInfo            = end($radaPokladniPohyb['polozkyRady']);

        $cislo = $crInfo['cisAkt'] + 1;
        if ($crInfo['zobrazNuly'] == 'true') {
            return $crInfo['prefix'].sprintf('%\'.0'.$crInfo['cisDelka'].'d',
                    $cislo).'/'.date('y');
        } else {
            return $crInfo['prefix'].$cislo.'/'.date('y');
        }
    }
661720
public function getDocById($str_id)
    {
        $obj_request = new ListDocumentsRequest();
        $obj_params = $this->prepareRequestParams($obj_request);
        $obj_params->setStartDocId($str_id)->setLimit(1);
        $this->execute('ListDocuments', $obj_request, new ListDocumentsResponse());
        $obj_response = $this->processListResponse();

        // Verify that the document is the one we want and if not, empty the response
        // This works around the lack of a "get-by-id" method on the Google Protocol Buffer
        if($obj_response->count > 0) {
            if($str_id !== $obj_response->docs[0]->getId()) {
                $obj_response->count = 0;
                $obj_response->docs = [];
            }
        }
        return $obj_response;
    }
704196
public function addMapping(string $src, string $dest): void
	{
		$this->mapper[$src] = $dest;
	}
995238
protected function getPageEditLink($pageId, $documentSetId)
    {
        return Controller::join_links(
            CMSPageEditController::singleton()->getEditForm($pageId)->FormAction(),
            'field/DocumentSets/item',
            (int) $documentSetId
        );
    }
1174497
public function appendLinkObject($key, LinkObject $linkObject) {
		Validator::checkMemberName($key);
		
		if (isset($this->links[$key]) === false) {
			$this->addLinksArray($key, new LinksArray());
		}
		elseif ($this->links[$key] instanceof LinksArray === false) {
			throw new DuplicateException('can not add to key "'.$key.'", it is not an array of links');
		}
		
		$this->links[$key]->addLinkObject($linkObject);
	}
1026223
public static function byObject($object = null, $objectId = null)
    {
        //zapytanie o pliki po obiektach i id
        return (new self)
                ->whereObject()->equals($object)
                ->andFieldObjectId()->equals($objectId)
                //posortowane po kolejności
                ->orderAscOrder()
                //sortowanie po ID, jeśli ordery są NULL
                ->orderAscId();
    }
867316
public function addLinkObject($key, LinkObject $linkObject) {
		$this->ensureLinksObject();
		$this->links->addLinkObject($key, $linkObject);
	}
1012280
public static function byObjectJoinedOriginal($object = null, $objectId = null)
    {
        //zapytanie o pliki po obiektach i id
        return (new self)
                ->joinLeft('cms_file', 'cms_file', 'original_file')
                ->on('cms_file_original_id', 'id')
                ->whereObject()->equals($object)
                ->andFieldObjectId()->equals($objectId)
                //posortowane po kolejności
                ->orderAscOrder()
                //sortowanie po ID, jeśli ordery są NULL
                ->orderAscId();
    }
774772
function execute(Ob $o) {
		$provider = $o[Plugin::PROVIDER]; /** @var Provider $provider */
		/** @var ISearchResult|ApiSearchResult|UiSearchResult|OrderGC|InvoiceGC|CreditmemoGC $result */
		$result = $o[Plugin::RESULT];
		// 2017-08-02 For now, we do not handle «sales_order_invoice_grid_data_source»
		// and «sales_order_creditmemo_grid_data_source».
		if ('sales_order_grid_data_source' === $provider->getName()) {
			/**
			 * 2016-07-28
			 * https://github.com/magento/magento2/blob/2.1.0/lib/internal/Magento/Framework/View/Element/UiComponent/DataProvider/SearchResult.php#L37-L40
			 * @see \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult::$document
			 * The document's structure is described here: https://mage2.pro/t/1908
			 */
			$cacheKey = __METHOD__; /** @var string $cacheKey */
			$prop = 'payment_method';  /** @var string $prop */
			df_map($result, function(Document $item) use($cacheKey, $prop) {
				/** @var string|null $methodCode */
				if (($methodCode = $item[$prop]) && df_starts_with($methodCode, 'dfe_')) {
					/**
					 * 2017-05-09
					 * Как оказалось, наличие приставки «dfe_» ешё не гарантирует,
					 * что @uses dfpm() (вызываемый ниже опосредованно через dfpm_title())
					 * действительно вернёт наследника @see \Df\Payment\Method
					 * Возможна ситуация, когда админтратор установил какой-либо из моих патёжных модулей,
					 * сделал платёж посредством него, а затем либо удалил модуль,
					 * либо из-за каких-то некорректных действий модуль стал отключенным,
					 * и вот тогда M2 вернёт не наследника @see \Df\Payment\Method,
					 * а экземпляр класса @see \Magento\Payment\Model\Method\Substitution:
					 * «How is @see \Magento\Payment\Model\Method\Substitution implemented and used?»
					 * https://mage2.pro/t/3924
					 * 1) @see \Magento\Sales\Model\Order\Payment\Info::getMethodInstance()
					 *	try {
					 *		$instance = $this->paymentData->getMethodInstance($this->getMethod());
					 *	} catch (\UnexpectedValueException $e) {
					 *		$instance = $this->paymentData->getMethodInstance(Substitution::CODE);
					 *	}
					 * https://github.com/magento/magento2/blob/2.1.6/app/code/Magento/Sales/Model/Order/Payment/Info.php#L113-L117
					 * 2) @see \Magento\Payment\Model\Info::getMethodInstance()
					 *	try {
					 *		$instance = $this->_paymentData->getMethodInstance($this->getMethod());
					 *	} catch (\UnexpectedValueException $e) {
					 *		$instance = $this->_paymentData->getMethodInstance(Method\Substitution::CODE);
					 *	}
					 * https://github.com/magento/magento2/blob/2.1.6/app/code/Magento/Payment/Model/Info.php#L106-L110
					 */
					$id = $item['entity_id']; /** @var int $id */
					// 2016-07-29
					// Эта операция очень ресурсоёмка:
					// для каждой строки таблицы заказов она делает кучу запросов к базе данных.
					// Поэтому кэшируем результаты в постоянном кэше.
					$item[$prop] = df_cache_get_simple([$cacheKey, $id], function() use($id) {
						$m = dfpm($o = df_order($id)); /** @var O $o */ /** @var M|Substitution $m */
						return !dfp_my($m) ? $m->getTitle() : df_cc_br(dfpm_title($m), dfp_choice($o)->title());
					});
				}
			});
		}
	}
1014100
static function appendRelatingNodeIDs( $object, &$nodeIDList )
    {
        $viewCacheIni = eZINI::instance( 'viewcache.ini' );
        if ( $viewCacheIni->hasVariable( 'ViewCacheSettings', 'ClearRelationTypes' ) )
        {
            $relTypes = $viewCacheIni->variable( 'ViewCacheSettings', 'ClearRelationTypes' );

            if ( !count( $relTypes ) )
                return;

            $relatedObjects = array();

            $relationsMask = 0;
            if ( in_array( 'object', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON | eZContentObject::RELATION_EMBED;

            if ( in_array( 'common', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON;

            if ( in_array( 'embedded', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_EMBED;

            if ( in_array( 'linked', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_LINK;

            if ( in_array( 'attribute', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_ATTRIBUTE;

            if ( $relationsMask )
            {
                $objects = $object->relatedContentObjectList( false, false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                $previousVersionObjects = array();
                $previousVersion = $object->previousVersion();
                if ( $previousVersion )
                {
                    $previousVersionObjects = $object->relatedContentObjectList( $previousVersion, false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                }
                $relatedObjects = array_merge( $relatedObjects, $objects, $previousVersionObjects );
            }

            $relationsMask = 0;
            if ( in_array( 'reverse_object', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON | eZContentObject::RELATION_EMBED;

            if ( in_array( 'reverse_common', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON;

            if ( in_array( 'reverse_embedded', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_EMBED;

            if ( in_array( 'reverse_linked', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_LINK;

            if ( in_array( 'reverse_attribute', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_ATTRIBUTE;

            if ( $relationsMask )
            {
                $objects = $object->reverseRelatedObjectList( false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                $previousVersionObjects = array();
                $previousVersion = $object->previousVersion();
                if ( $previousVersion )
                {
                    $previousVersionObjects = $object->relatedContentObjectList( $previousVersion, false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                }
                $relatedObjects = array_merge( $relatedObjects, $objects, $previousVersionObjects );
            }
        }
        else
        {
            $normalRelated = $object->relatedContentObjectArray();
            $reversedRelated = $object->contentObjectListRelatingThis();

            $relatedObjects = array_merge( $normalRelated, $reversedRelated );
        }

        foreach ( $relatedObjects as $relatedObject )
        {
            $assignedNodes = $relatedObject->assignedNodes( false );
            foreach ( $assignedNodes as $assignedNode )
            {
                $nodeIDList[] = $assignedNode['node_id'];
            }
        }
        $nodeIDList = array_unique( $nodeIDList );
    }
308379
public static function deleteByObject($object = null, $objectId = null)
    {
        //wybieramy kolekcję i usuwamy całą
        return CmsFileQuery::byObject($object, $objectId)
                ->find()
                ->delete();
    }