Ejemplo n.º 1
0
 /**
  * Looks up ezcontentobjectattribute entries matching an image filepath and
  * a contentobjectattribute ID
  *
  * @param string $filePath file path to look up as URL in the XML string
  * @param int $contentObjectAttributeID
  *
  * @return array An array with a series of ezcontentobject_attribute's id, version and language_code
  */
 static function fetchImageAttributesByFilepath($filepath, $contentObjectAttributeID)
 {
     $db = eZDB::instance();
     $contentObjectAttributeID = (int) $contentObjectAttributeID;
     $cond = array('id' => $contentObjectAttributeID);
     $fields = array('contentobject_id', 'contentclassattribute_id');
     $limit = array('offset' => 0, 'length' => 1);
     $rows = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), $fields, $cond, null, $limit, false);
     if (count($rows) != 1) {
         return array();
     }
     $contentObjectID = (int) $rows[0]['contentobject_id'];
     $contentClassAttributeID = (int) $rows[0]['contentclassattribute_id'];
     // Transform ", &, < and > to entities since they are being transformed in entities by DOM
     // See eZImageAliasHandler::initialize()
     // Ref https://jira.ez.no/browse/EZP-20090
     $filepath = $db->escapeString(htmlspecialchars($filepath, version_compare(PHP_VERSION, '5.4.0', '>=') ? ENT_COMPAT | ENT_HTML401 : ENT_COMPAT, 'UTF-8'));
     // Escape _ in like to avoid it to act as a wildcard !
     $filepath = addcslashes($filepath, "_");
     $query = "SELECT id, version, language_code\n                  FROM   ezcontentobject_attribute\n                  WHERE  contentobject_id = {$contentObjectID} AND\n                         contentclassattribute_id = {$contentClassAttributeID} AND\n                         data_text LIKE '%url=\"{$filepath}\"%'";
     if ($db->databaseName() == 'oracle') {
         $query .= " ESCAPE '\\'";
     }
     $rows = $db->arrayQuery($query);
     return $rows;
 }
 /**
  * Makes the 'contentclass_attribute' attribute a 'field' instead
  * of a function attribute, for testing purposes.
  *
  * @return the overridden definition array
  */
 public static function definition()
 {
     $definitionOverride = array('fields' => array('contentclass_attribute' => array('name' => "ContentClassAttribute", 'datatype' => 'mixed')));
     $definition = array_merge_recursive(parent::definition(), $definitionOverride);
     $definition['class_name'] = __CLASS__;
     unset($definition['function_attributes']['contentclass_attribute']);
     return $definition;
 }
 /**
  * Fetch media objects by content object id
  * @param int $contentObjectID contentobject id
  * @param string $languageCode language code
  * @param boolean $asObject if return object
  * @return array
  */
 static function fetchByContentObjectID($contentObjectID, $languageCode = null, $asObject = true)
 {
     $condition = array();
     $condition['contentobject_id'] = $contentObjectID;
     $condition['data_type_string'] = 'ezmedia';
     if ($languageCode != null) {
         $condition['language_code'] = $languageCode;
     }
     $custom = array(array('operation' => 'DISTINCT id', 'name' => 'id'));
     $ids = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), array(), $condition, null, null, false, false, $custom);
     $mediaFiles = array();
     foreach ($ids as $id) {
         $mediaFileObjectAttribute = eZMedia::fetch($id['id'], null, $asObject);
         $mediaFiles = array_merge($mediaFiles, $mediaFileObjectAttribute);
     }
     return $mediaFiles;
 }
Ejemplo n.º 4
0
 /**
  * Looks up ezcontentobjectattribute entries matching an image filepath and
  * a contentobjectattribute ID
  *
  * @param string $filePath file path to look up as URL in the XML string
  * @param int $contentObjectAttributeID
  *
  * @return array An array of content object attribute ids and versions of
  *               image files where the url is referenced
  *
  * @todo Rewrite ! A where data_text LIKE '%xxx%' is a resource hog !
  */
 static function fetchImageAttributesByFilepath($filepath, $contentObjectAttributeID)
 {
     $db = eZDB::instance();
     $contentObjectAttributeID = (int) $contentObjectAttributeID;
     $cond = array('id' => $contentObjectAttributeID);
     $fields = array('contentobject_id', 'contentclassattribute_id');
     $limit = array('offset' => 0, 'length' => 1);
     $rows = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), $fields, $cond, null, $limit, false);
     if (count($rows) != 1) {
         return array();
     }
     $contentObjectID = (int) $rows[0]['contentobject_id'];
     $contentClassAttributeID = (int) $rows[0]['contentclassattribute_id'];
     $filepath = $db->escapeString($filepath);
     // Escape _ in like to avoid it to act as a wildcard !
     $filepath = addcslashes($filepath, "_");
     $query = "SELECT id, version\n                  FROM   ezcontentobject_attribute\n                  WHERE  contentobject_id = {$contentObjectID} and\n                         contentclassattribute_id = {$contentClassAttributeID} and\n                         data_text like '%url=\"{$filepath}\"%'";
     $rows = $db->arrayQuery($query);
     return $rows;
 }
 function updateContentFromClassAttribute($classAttributeID)
 {
     $asObject = true;
     $i = 0;
     $offset = 0;
     $countList = 0;
     $limit = 100;
     $conditions = array("contentclassattribute_id" => $classAttributeID);
     $limitArray = array('offset' => $offset, 'limit' => $limit);
     $sortArray = array('id' => 'asc');
     // Only fetch some objects each time to avoid memory problems.
     while (true) {
         $contentObjectAttributeList = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $conditions, $sortArray, $limitArray, $asObject);
         if (count($contentObjectAttributeList) == 0) {
             break;
         }
         foreach ($contentObjectAttributeList as $contentObjectAttribute) {
             $this->updateContentObjectAttribute($contentObjectAttribute);
         }
         $this->Cli->output(".", false);
         $i++;
         if ($i % 70 == 0) {
             $this->Cli->output(' ' . $this->Cli->stylize('strong', $i * $limit));
         }
         $countList = count($contentObjectAttributeList);
         unset($contentObjectList);
         $offset += $limit;
         $limitArray = array('offset' => $offset, 'limit' => $limit);
     }
     $repeatLength = 70 - $i % 70;
     $count = ($i - 1) * $limit + $countList;
     $this->Cli->output(str_repeat(' ', $repeatLength) . ' ' . $this->Cli->stylize('strong', $count), false);
 }
Ejemplo n.º 6
0
                }
            }
        }
        // while END
        if ($isTextModified) {
            $xmlAttribute->setAttribute('data_text', $xmlText);
            $xmlAttribute->store();
        }
    }
    // foreach END
}
// 6. fixing datatype ezobjectrelationlist
$conditions = array('contentobject_id' => '', 'data_type_string' => 'ezobjectrelationlist');
foreach ($syncObjectIDListNew as $contentObjectID) {
    $conditions['contentobject_id'] = $contentObjectID;
    $attributeList = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $conditions);
    if (count($attributeList) == 0) {
        continue;
    }
    foreach ($attributeList as $relationListAttribute) {
        $relationsXmlText = $relationListAttribute->attribute('data_text');
        $relationsDom = eZObjectRelationListType::parseXML($relationsXmlText);
        $relationItems = $relationsDom->getElementsByTagName('relation-item');
        $isRelationModified = false;
        foreach ($relationItems as $relationItem) {
            $originalObjectID = $relationItem->getAttribute('contentobject-id');
            $key = array_search($originalObjectID, $syncObjectIDListSrc);
            if ($key !== false) {
                $newObjectID = $syncObjectIDListNew[$key];
                $relationItem->setAttribute('contentobject-id', $newObjectID);
                $isRelationModified = true;
Ejemplo n.º 7
0
    /**
     * Looks up ezcontentobjectattribute entries matching an image filepath and
     * a contentobjectattribute ID
     *
     * @param string $filePath file path to look up as URL in the XML string
     * @param int $contentObjectAttributeID
     *
     * @return array An array of content object attribute ids and versions of
     *               image files where the url is referenced
     *
     * @todo Rewrite ! A where data_text LIKE '%xxx%' is a resource hog !
     */
    static function fetchImageAttributesByFilepath( $filepath, $contentObjectAttributeID )
    {
        $db = eZDB::instance();
        $contentObjectAttributeID = (int) $contentObjectAttributeID;

        $cond = array( 'id' => $contentObjectAttributeID );
        $fields = array( 'contentobject_id', 'contentclassattribute_id' );
        $limit = array( 'offset' => 0, 'length' => 1 );
        $rows = eZPersistentObject::fetchObjectList( eZContentObjectAttribute::definition(),
                                                     $fields,
                                                     $cond,
                                                     null,
                                                     $limit,
                                                     false );
        if ( count( $rows ) != 1 )
            return array();

        $contentObjectID = (int)( $rows[0]['contentobject_id'] );
        $contentClassAttributeID = (int)( $rows[0]['contentclassattribute_id'] );
        $filepath = $db->escapeString( $filepath );
        $query = "SELECT id, version
                  FROM   ezcontentobject_attribute
                  WHERE  contentobject_id = $contentObjectID and
                         contentclassattribute_id = $contentClassAttributeID and
                         data_text like '%url=\"$filepath\"%'";
        $rows = $db->arrayQuery( $query );
        return $rows;
    }
 /**
  * Fetches all attributes from any versions of the content object
  *
  * @param int $contentObjectID
  * @param bool $asObject
  * @param array|null $limit the limit array passed to {@see eZPersistentObject::fetchObjectList}
  * @return eZContentObjectAttribute[]|array|null
  */
 function allContentObjectAttributes( $contentObjectID, $asObject = true, $limit = null )
 {
     return eZPersistentObject::fetchObjectList( eZContentObjectAttribute::definition(),
                                                 null,
                                                 array("contentobject_id" => $contentObjectID ),
                                                 null,
                                                 $limit,
                                                 $asObject );
 }
Ejemplo n.º 9
0
 /**
  * Get actual values for PaEx data for the given contentobject id.
  * If not defined for the given coID, use defaults.
  *
  * @param int $ezcoid Contentobject id (user id) to get PaEx for
  * @param bool $checkIfUserHasDatatype See if user has paex datatype, default false
  * @return eZPaEx|null Actual PaEx applicable data, null if $checkIfUserHasDatatype = true
  *                     and object does not have ezpaex datatype
  */
 static function getPaEx($ezcoid, $checkIfUserHasDatatype = false)
 {
     $currentPaex = eZPaEx::fetch($ezcoid);
     // If we don't have paex object for the current object id, create a default one
     if (!$currentPaex instanceof eZPaEx) {
         // unless user does not have paex datatype
         if ($checkIfUserHasDatatype) {
             //eZContentObject::fetch( $ezcoid );
             $paexDataTypeCount = eZPersistentObject::count(eZContentObjectAttribute::definition(), array('contentobject_id' => $ezcoid, 'data_type_string' => ezpaextype::DATA_TYPE_STRING), 'id');
             if (!$paexDataTypeCount) {
                 eZDebug::writeDebug("User id {$ezcoid} does not have paex datatype", __METHOD__);
                 return null;
             }
         }
         return eZPaEx::create($ezcoid);
     }
     // Get default paex values from ini to use in case there is anyone missing in the object
     $ini = eZINI::instance('mbpaex.ini');
     $iniPasswordValidationRegexp = $ini->variable('mbpaexSettings', 'PasswordValidationRegexp');
     $iniDefaultPasswordLifeTime = $ini->variable('mbpaexSettings', 'DefaultPasswordLifeTime');
     $iniExpirationNotification = $ini->variable('mbpaexSettings', 'ExpirationNotification');
     // If still any empty values in the paex object, set defaults from ini
     if (!$currentPaex->hasRegexp()) {
         $currentPaex->setAttribute('passwordvalidationregexp', $iniPasswordValidationRegexp);
         eZDebug::writeDebug('Regexp empty, used default: "' . $iniPasswordValidationRegexp . '"', 'eZPaEx::getPaEx');
     }
     if (!$currentPaex->hasLifeTime()) {
         $currentPaex->setAttribute('passwordlifetime', $iniDefaultPasswordLifeTime);
         eZDebug::writeDebug('PasswordLifeTime empty, used default: "' . $iniDefaultPasswordLifeTime . '"', 'eZPaEx::getPaEx');
     }
     if (!$currentPaex->hasNotification()) {
         $currentPaex->setAttribute('expirationnotification', $iniExpirationNotification);
         eZDebug::writeDebug('ExpirationNotification empty, used default: "' . $iniPasswordValidationRegexp . '"', 'eZPaEx::getPaEx');
     }
     eZDebug::writeDebug('PasswordLastUpdated value: "' . $currentPaex->attribute('password_last_updated') . '"', 'eZPaEx::getPaEx');
     return $currentPaex;
 }
            continue;
        }
    } else {
        $cli->output("  Moving file to {$newPath}");
    }
    if (!$optDryRun && $moveFile) {
        $clusterHandler->fileMove($filePath, $newPath);
        $db->query("UPDATE ezimagefile SET filepath = '{$newPath}' WHERE contentobject_attribute_id = {$imageAttributeId}");
    }
    if (!isset($renamedFiles[$imageAttributeId])) {
        $renamedFiles[$imageAttributeId] = array();
    }
    $renamedFiles[$imageAttributeId][$filePath] = $newPath;
}
foreach ($renamedFiles as $attributeId => $files) {
    $attributeObjects = eZContentObjectAttribute::fetchObjectList(eZContentObjectAttribute::definition(), null, array('id' => $attributeId));
    /** @var eZContentObjectAttribute $attributeObject */
    foreach ($attributeObjects as $attributeObject) {
        $dom = new DOMDocument('1.0', 'utf-8');
        if (!$dom->loadXML($attributeObject->attribute('data_text'))) {
            continue;
        }
        foreach ($dom->getElementsByTagName('ezimage') as $ezimageNode) {
            // Update main image
            $oldPath = $ezimageNode->getAttribute('url');
            if (isset($files[$oldPath])) {
                $ezimageNode->setAttribute('url', $files[$oldPath]);
                $ezimageNode->setAttribute('dirpath', dirname($files[$oldPath]));
            }
            // Update aliases
            foreach ($ezimageNode->getElementsByTagName('alias') as $ezimageAlias) {
Ejemplo n.º 11
0
<?php

$db = eZDB::instance();
$offset = 0;
$length = 100;
$cond = array('data_type_string' => xrowMetaDataType::DATA_TYPE_STRING);
$count = eZPersistentObject::count(eZContentObjectAttribute::definition(), $cond);
echo "There are {$count} priorities to reset.\n";
$output = new ezcConsoleOutput();
$bar = new ezcConsoleProgressbar($output, $count / $length);
$limit = array('offset' => $offset, 'length' => $length);
$list = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $cond, null, $limit);
while (!empty($list)) {
    $db->begin();
    /* var eZContentObjectAttribute */
    foreach ($list as $attribute) {
        /* var xrowMetaData */
        $data = $attribute->content();
        $data->priority = null;
        $attribute->setContent($data);
        $attribute->store();
    }
    $db->commit();
    $bar->advance();
    $offset = $offset + $length;
    $limit = array('offset' => $offset, 'length' => $length);
    $list = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $cond, null, $limit);
}
$script = eZScript::instance(array('description' => "Migrates sckenhancedselection datatype to version which stores content object data to database table.", 'use-session' => true, 'use-modules' => false, 'use-extensions' => true));
$script->startup();
$script->getOptions();
$script->initialize();
$cli->warning("This script will NOT republish objects, but rather update ALL versions");
$cli->warning("of content objects. If you do not wish to do that, you have");
$cli->warning("15 seconds to cancel the script! (press Ctrl-C)\n");
sleep(15);
$db = eZDB::instance();
$offset = 0;
$limit = 50;
$attributeCount = (int) eZPersistentObject::count(eZContentObjectAttribute::definition(), array('data_type_string' => 'sckenhancedselection'));
while ($offset < $attributeCount) {
    eZContentObject::clearCache();
    /** @var eZContentObjectAttribute[] $attributes */
    $attributes = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, array('data_type_string' => 'sckenhancedselection'), null, array('offset' => $offset, 'length' => $limit));
    foreach ($attributes as $attribute) {
        SckEnhancedSelection::removeByAttribute($attribute->attribute('id'), $attribute->attribute('version'));
        $identifiers = unserialize((string) $attribute->attribute('data_text'));
        if (is_array($identifiers) && !empty($identifiers)) {
            foreach ($identifiers as $identifier) {
                $sckEnhancedSelection = new SckEnhancedSelection(array('contentobject_attribute_id' => $attribute->attribute('id'), 'contentobject_attribute_version' => $attribute->attribute('version'), 'identifier' => $identifier));
                $sckEnhancedSelection->store();
            }
        }
        $attribute->setAttribute('data_text', null);
        $attribute->store();
        $cli->output("Converted attribute #{$attribute->attribute('id')} in version {$attribute->attribute('version')}");
    }
    unset($attributes);
    $offset += $limit;
Ejemplo n.º 13
0
 static function removeRelationObject($contentObjectAttribute, $deletionItem)
 {
     if (self::isItemPublished($deletionItem)) {
         return;
     }
     $hostObject = $contentObjectAttribute->attribute('object');
     $hostObjectID = $hostObject->attribute('id');
     // Do not try removing the object if present in trash
     // Only objects being really orphaned (not even being in trash) should be removed by this method.
     // See issue #019457
     if ((int) eZPersistentObject::count(eZContentObjectTrashNode::definition(), array("contentobject_id" => $hostObjectID)) > 0) {
         return;
     }
     $hostObjectVersions = $hostObject->versions();
     $isDeletionAllowed = true;
     // check if the relation item to be deleted is unique in the domain of all host-object versions
     foreach ($hostObjectVersions as $version) {
         if ($isDeletionAllowed and $version->attribute('version') != $contentObjectAttribute->attribute('version')) {
             $relationAttribute = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, array('version' => $version->attribute('version'), 'contentobject_id' => $hostObjectID, 'contentclassattribute_id' => $contentObjectAttribute->attribute('contentclassattribute_id')));
             if (count($relationAttribute) > 0) {
                 $relationContent = $relationAttribute[0]->content();
                 if (is_array($relationContent) and is_array($relationContent['relation_list'])) {
                     foreach ($relationContent['relation_list'] as $relationItem) {
                         if ($deletionItem['contentobject_id'] == $relationItem['contentobject_id'] && $deletionItem['contentobject_version'] == $relationItem['contentobject_version']) {
                             $isDeletionAllowed = false;
                             break 2;
                         }
                     }
                 }
             }
         }
     }
     if ($isDeletionAllowed) {
         $subObjectVersion = eZContentObjectVersion::fetchVersion($deletionItem['contentobject_version'], $deletionItem['contentobject_id']);
         if ($subObjectVersion instanceof eZContentObjectVersion) {
             $subObjectVersion->removeThis();
         } else {
             eZDebug::writeError('Cleanup of subobject-version failed. Could not fetch object from relation list.\\n' . 'Requested subobject id: ' . $deletionItem['contentobject_id'] . '\\n' . 'Requested Subobject version: ' . $deletionItem['contentobject_version'], __METHOD__);
         }
     }
 }
/**
 * File containing the ${NAME} class.
 *
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
 * @license For full copyright and license information view LICENSE file distributed with this source code.
 * @version 2014.11.1
 */
require_once 'autoload.php';
$cli = eZCLI::instance();
$script = eZScript::instance(array('description' => "Re-creates missing references to image files in ezimagefile. See issue EZP-21324\n", 'use-session' => true, 'use-modules' => false, 'use-extensions' => true));
$script->startup();
$options = $script->getOptions("[dry-run]", "", array('n' => 'Dry run'));
$optDryRun = (bool) $options['dry-run'];
$script->initialize();
$imageAttributes = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), array('id', 'contentobject_id', 'version', 'data_text'), array('data_type_string' => 'ezimage'), null, null, false);
$cli->output("Re-creating missing ezcontentobject_attribute / ezimagefile references");
if ($optDryRun) {
    $cli->warning("dry-run mode");
}
foreach ($imageAttributes as $imageAttribute) {
    if (($doc = simplexml_load_string($imageAttribute["data_text"])) === false) {
        continue;
    }
    // Creates ezimagefile entries
    foreach ($doc->xpath("//*/@url") as $url) {
        $url = (string) $url;
        echo "Processing {$imageAttribute['contentobject_id']}#{$imageAttribute['version']} ({$url})\n";
        if ($url === "") {
            continue;
        }
 /**
  * Return the contentObject.
  * 
  * @return void
  */
 public function contentObject()
 {
     $singleAttributeList = ezPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, array('id' => $this->attribute('contentobjectattribute_id')), null, 1, true);
     $singleAttribute = $singleAttributeList[0];
     return $singleAttribute->attribute('object');
 }
 /**
  * @param $tpl eZTemplate
  * @param $operatorName array
  * @param $operatorParameters array
  * @param $rootNamespace string
  * @param $currentNamespace string
  * @param $operatorValue mixed
  * @param $namedParameters array
  *
  * @return mixed
  */
 function modify(&$tpl, &$operatorName, &$operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters)
 {
     $ini = eZINI::instance('ocoperatorscollection.ini');
     $appini = eZINI::instance('app.ini');
     switch ($operatorName) {
         case 'related_attribute_objects':
             $object = $operatorValue;
             $identifier = $namedParameters['identifier'];
             $dataMap = $object instanceof eZContentObject || $object instanceof eZContentObjectTreeNode ? $object->attribute('data_map') : array();
             $data = array();
             if (isset($dataMap[$identifier])) {
                 $ids = $dataMap[$identifier] instanceof eZContentObjectAttribute ? explode('-', $dataMap[$identifier]->toString()) : array();
                 if (!empty($ids)) {
                     $data = eZContentObject::fetchList(true, array("id" => array($ids)));
                 }
             }
             $operatorValue = $data;
             break;
         case 'smart_override':
             $identifier = $namedParameters['identifier'];
             $view = $namedParameters['view'];
             $node = $operatorValue;
             $operatorValue = $this->findSmartTemplate($identifier, $view, $node);
             break;
         case 'parse_link_href':
             $href = $operatorValue;
             $hrefParts = explode(':', $href);
             $hrefFirst = array_shift($hrefParts);
             if (!in_array($hrefFirst, array('http', 'https', 'file', 'mailto', 'ftp'))) {
                 if (!empty($hrefFirst)) {
                     $nodeID = eZURLAliasML::fetchNodeIDByPath('/' . $hrefFirst);
                     if ($nodeID) {
                         $contentNode = eZContentObjectTreeNode::fetch($nodeID);
                         if ($contentNode instanceof eZContentObjectTreeNode) {
                             $keyArray = array(array('node', $contentNode->attribute('node_id')), array('object', $contentNode->attribute('contentobject_id')), array('class_identifier', $contentNode->attribute('class_identifier')), array('class_group', $contentNode->attribute('object')->attribute('content_class')->attribute('match_ingroup_id_list')));
                             $tpl = new eZTemplate();
                             $ini = eZINI::instance();
                             $autoLoadPathList = $ini->variable('TemplateSettings', 'AutoloadPathList');
                             $extensionAutoloadPath = $ini->variable('TemplateSettings', 'ExtensionAutoloadPath');
                             $extensionPathList = eZExtension::expandedPathList($extensionAutoloadPath, 'autoloads/');
                             $autoLoadPathList = array_unique(array_merge($autoLoadPathList, $extensionPathList));
                             $tpl->setAutoloadPathList($autoLoadPathList);
                             $tpl->autoload();
                             $tpl->setVariable('node', $contentNode);
                             $tpl->setVariable('object', $contentNode->attribute('object'));
                             $tpl->setVariable('original_href', $href);
                             $res = new eZTemplateDesignResource();
                             $res->setKeys($keyArray);
                             $tpl->registerResource($res);
                             $result = trim($tpl->fetch('design:link/href.tpl'));
                             if (!empty($result)) {
                                 $href = $result;
                             }
                         }
                     }
                 }
             }
             return $operatorValue = $href;
             break;
         case 'gmap_static_image':
             try {
                 $cacheFileNames = array();
                 //@todo
                 $operatorValue = OCOperatorsCollectionsTools::gmapStaticImage($namedParameters['parameters'], $namedParameters['attribute'], $cacheFileNames);
             } catch (Exception $e) {
                 eZDebug::writeError($e->getMessage(), 'gmap_static_image');
             }
             break;
         case 'fa_class_icon':
             $faIconIni = eZINI::instance('fa_icons.ini');
             $node = $operatorValue;
             $data = $namedParameters['fallback'] != '' ? $namedParameters['fallback'] : $faIconIni->variable('ClassIcons', '_fallback');
             if ($node instanceof eZContentObjectTreeNode) {
                 if ($faIconIni->hasVariable('ClassIcons', $node->attribute('class_identifier'))) {
                     $data = $faIconIni->variable('ClassIcons', $node->attribute('class_identifier'));
                 }
             }
             $operatorValue = $data;
             break;
         case 'fa_object_icon':
             $faIconIni = eZINI::instance('fa_icons.ini');
             $object = $operatorValue;
             $data = $namedParameters['fallback'] != '' ? $namedParameters['fallback'] : '';
             if ($object instanceof eZContentObject) {
                 if ($faIconIni->hasVariable('ObjectIcons', $object->attribute('id'))) {
                     $data = $faIconIni->variable('ObjectIcons', $object->attribute('id'));
                 }
             } else {
                 if ($faIconIni->hasVariable('ObjectIcons', $node)) {
                     $data = $faIconIni->variable('ObjectIcons', $node);
                 }
             }
             $operatorValue = $data;
             break;
         case 'fa_node_icon':
             $faIconIni = eZINI::instance('fa_icons.ini');
             $node = $operatorValue;
             $data = $namedParameters['fallback'] != '' ? $namedParameters['fallback'] : '';
             if ($node instanceof eZContentObjectTreeNode) {
                 if ($faIconIni->hasVariable('NodeIcons', $node->attribute('node_id'))) {
                     $data = $faIconIni->variable('NodeIcons', $node->attribute('node_id'));
                 }
             } else {
                 if ($faIconIni->hasVariable('NodeIcons', $node)) {
                     $data = $faIconIni->variable('NodeIcons', $node);
                 }
             }
             $operatorValue = $data;
             break;
         case 'children_class_identifiers':
             $node = $operatorValue;
             $data = array();
             if ($node instanceof eZContentObjectTreeNode) {
                 $search = eZFunctionHandler::execute('ezfind', 'search', array('subtree_array' => array($node->attribute('node_id')), 'limit' => 1, 'as_objects' => false, 'filter' => array('-meta_id_si:' . $node->attribute('contentobject_id')), 'facet' => array(array('field' => 'meta_class_identifier_ms', 'name' => 'class_identifier', 'limit' => 200))));
                 if (isset($search['SearchExtras'])) {
                     $facets = $search['SearchExtras']->attribute('facet_fields');
                     $data = array_diff(array_values($facets[0]['nameList']), $namedParameters['exclude']);
                 }
             }
             //eZDebug::writeNotice( $data, 'children_class_identifiers'  );
             $operatorValue = $data;
             break;
         case 'json_encode':
             $operatorValue = json_encode($operatorValue);
             break;
         case 'browse_template':
             $identifiers = array('image', 'image2', 'galleria', 'gallery', 'immagini');
             if ($ini->hasVariable('ObjectRelationsMultiupload', 'ClassAttributeIdentifiers')) {
                 $identifiers = $ini->variable('ObjectRelationsMultiupload', 'ClassAttributeIdentifiers');
             }
             if ($operatorValue instanceof eZContentBrowse && $operatorValue->hasAttribute('type') && $operatorValue->attribute('type') == 'AddRelatedObjectListToDataType' && $operatorValue->hasAttribute('action_name')) {
                 $currentAttributeId = str_replace('AddRelatedObject_', '', $operatorValue->attribute('action_name'));
                 $currentAttribute = eZPersistentObject::fetchObject(eZContentObjectAttribute::definition(), null, array("id" => $currentAttributeId), false);
                 if (isset($currentAttribute['contentclassattribute_id'])) {
                     $contentClassAttribute = eZContentClassAttribute::fetch($currentAttribute['contentclassattribute_id']);
                     if ($contentClassAttribute instanceof eZContentClassAttribute && ($contentClassAttribute->attribute('data_type_string') == 'mugoobjectrelationlist' || $contentClassAttribute->attribute('data_type_string') == 'ezobjectrelationlist') && in_array($contentClassAttribute->attribute('identifier'), $identifiers)) {
                         return $operatorValue = 'multiupload.tpl';
                     }
                 }
             } elseif ($operatorValue instanceof eZContentBrowse && $operatorValue->hasAttribute('action_name') && $operatorValue->attribute('action_name') == 'MultiUploadBrowse') {
                 return $operatorValue = 'multiupload.tpl';
             }
             $operatorValue = 'default.tpl';
             break;
         case 'multiupload_file_types_string':
             $availableFileTypes = array();
             $availableFileTypesString = '';
             if (eZINI::instance('ezmultiupload.ini')->hasGroup('FileTypeSettings_' . $operatorValue)) {
                 $availableFileTypes = eZINI::instance('ezmultiupload.ini')->variable('FileTypeSettings_' . $operatorValue, 'FileType');
             }
             if (!empty($availableFileTypes)) {
                 $availableFileTypesString = implode(';', $availableFileTypes);
             }
             $operatorValue = $availableFileTypesString;
             break;
         case 'multiupload_file_types_string_from_attribute':
             $availableFileTypesString = '';
             $attribute = $operatorValue;
             if ($attribute instanceof eZContentObjectAttribute) {
                 $identifiers = array();
                 if ($ini->hasVariable('ObjectRelationsMultiupload', 'ClassAttributeIdentifiers')) {
                     $identifier = $attribute->attribute('contentclass_attribute_identifier');
                     $identifiers = $ini->variable('ObjectRelationsMultiupload', 'ClassAttributeIdentifiers');
                     if (in_array($identifier, $identifiers)) {
                         $availableFileTypes = array();
                         $groups = $ini->group('ObjectRelationsMultiuploadFileTypesGroups');
                         foreach ($groups as $groupName => $fileType) {
                             $groupIdentifiers = $ini->variable('ObjectRelationsMultiuploadFileTypes_' . $groupName, 'Identifiers');
                             if (in_array($identifier, $groupIdentifiers)) {
                                 $availableFileTypesString = $fileType;
                             }
                         }
                     }
                 }
             }
             $operatorValue = $availableFileTypesString;
             break;
         case 'session_id':
             $operatorValue = session_id();
             break;
         case 'session_name':
             $operatorValue = session_name();
             break;
         case 'user_session_hash':
             $operatorValue = '';
             break;
         case 'developer_warning':
             $res = false;
             $user = eZUser::currentUser();
             if ($user->attribute('login') == 'admin') {
                 $templates = $tpl->templateFetchList();
                 $data = array_pop($templates);
                 $res = '<div class="developer-warning alert alert-danger"><strong>Avviso per lo sviluppatore</strong>:<br /><code>' . $data . '</code><br />' . $namedParameters['text'] . '</div>';
             }
             $operatorValue = $res;
             break;
         case 'editor_warning':
             $res = false;
             $user = eZUser::currentUser();
             if ($user->hasAccessTo('content', 'dashboard')) {
                 $res = '<div class="editor-warning alert alert-warning"><strong>Avviso per l\'editor</strong>: ' . $namedParameters['text'] . '</div>';
             }
             $operatorValue = $res;
             break;
         case 'appini':
             if ($appini->hasVariable($namedParameters['block'], $namedParameters['setting'])) {
                 $rs = $appini->variable($namedParameters['block'], $namedParameters['setting']);
             } else {
                 $rs = $namedParameters['default'];
             }
             $operatorValue = $rs;
             break;
         case 'has_attribute':
         case 'attribute':
             if ($operatorName == 'attribute' && $namedParameters['show_values'] == 'show') {
                 $legacy = new eZTemplateAttributeOperator();
                 $parameters = $legacy->namedParameterList();
                 if (isset($parameters['attribute'])) {
                     $parameters = $parameters['attribute'];
                 }
                 $legacyParameters = array();
                 foreach (array_keys($parameters) as $key) {
                     switch ($key) {
                         case "as_html":
                             $legacyParameters[$key] = true;
                             break;
                         default:
                             $legacyParameters[$key] = isset($namedParameters[$key]) ? $namedParameters[$key] : false;
                     }
                 }
                 $legacy->modify($tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, $operatorValue, $legacyParameters, null);
                 return $operatorValue;
             }
             return $operatorValue = $this->hasContentObjectAttribute($operatorValue, $namedParameters['show_values']);
             break;
         case 'set_defaults':
             if (is_array($namedParameters['variables'])) {
                 foreach ($namedParameters['variables'] as $key => $value) {
                     if (!$tpl->hasVariable($key, $currentNamespace)) {
                         $tpl->setLocalVariable($key, $value, $currentNamespace);
                     }
                 }
             }
             break;
         case 'unset_defaults':
             foreach ($namedParameters['variables'] as $key) {
                 $tpl->unsetLocalVariable($key, $currentNamespace);
                 //                    if ( isset( $tpl->Variables[$rootNamespace] ) &&
                 //                         array_key_exists( $key, $tpl->Variables[$rootNamespace] ) )
                 //                    {
                 //                        $tpl->unsetVariable( $key, $rootNamespace );
                 //                    }
             }
             break;
             //@todo add cache!
         //@todo add cache!
         case 'include_cache':
             $tpl = eZTemplate::factory();
             foreach ($namedParameters['variables'] as $key => $value) {
                 $tpl->setVariable($key, $value);
             }
             $operatorValue = $tpl->fetch('design:' . $namedParameters['template']);
             break;
         case 'find_global_layout':
             $result = false;
             $node = $operatorValue;
             if (is_numeric($node)) {
                 $node = eZContentObjectTreeNode::fetch($node);
             }
             if (!$node) {
                 return $operatorValue = $result;
             }
             $pathArray = $node->attribute('path_array');
             $nodesParams = array();
             foreach ($pathArray as $pathNodeID) {
                 if ($pathNodeID < eZINI::instance('content.ini')->variable('NodeSettings', 'RootNode') || $pathNodeID == $node->attribute('node_id')) {
                     continue;
                 } else {
                     $nodesParams[] = array('ParentNodeID' => $pathNodeID, 'ResultID' => 'ezcontentobject_tree.node_id', 'ClassFilterType' => 'include', 'ClassFilterArray' => $ini->variable('GlobalLayout', 'Classes'), 'Depth' => 1, 'DepthOperator' => 'eq', 'AsObject' => false);
                 }
             }
             //eZDebug::writeWarning( var_export($nodesParams,1), __METHOD__);
             $findNodes = eZContentObjectTreeNode::subTreeMultiPaths($nodesParams, array('SortBy' => array('node_id', false)));
             $sortByParentNodeID = array();
             if (!empty($findNodes)) {
                 foreach ($findNodes as $findNode) {
                     $sortByParentNodeID[$findNode['parent_node_id']] = $findNode;
                 }
                 krsort($sortByParentNodeID);
                 $result = array_shift($sortByParentNodeID);
                 $result = eZContentObjectTreeNode::makeObjectsArray(array($result));
                 if (!empty($result)) {
                     $result = $result[0];
                 }
             }
             return $operatorValue = $result;
         case 'redirect':
             $url = $namedParameters['url'];
             header('Location: ' . $url);
             break;
         case 'sort_nodes':
             $sortNodes = array();
             if (!empty($operatorValue) && is_array($operatorValue)) {
                 $nodes = $operatorValue;
                 foreach ($nodes as $node) {
                     if (!$node instanceof eZContentObjectTreeNode) {
                         continue;
                     }
                     $object = $node->object();
                     switch ($namedParameters['by']) {
                         case 'published':
                         default:
                             $sortby = $object->attribute('published');
                             break;
                     }
                     $sortNodes[$sortby] = $node;
                 }
                 ksort($sortNodes);
                 if ($namedParameters['order'] == 'desc') {
                     $sortNodes = array_reverse($sortNodes);
                 }
             }
             return $operatorValue = $sortNodes;
             break;
         case 'to_query_string':
             if (!empty($namedParameters['param'])) {
                 $value = $namedParameters['param'];
             } else {
                 $value = $operatorValue;
             }
             $string = http_build_query($value);
             return $operatorValue = $string;
             break;
         case 'has_abstract':
         case 'abstract':
             $node = $operatorValue;
             if (!$node instanceof eZContentObjectTreeNode && isset($namedParameters['node'])) {
                 $node = $namedParameters['node'];
                 if (is_numeric($node)) {
                     $node = eZContentObjectTreeNode::fetch($node);
                 }
             }
             return $operatorValue = $this->getAbstract($node, $operatorName == 'has_abstract');
             break;
         case 'subsite':
             $path = $this->getPath($tpl);
             $result = false;
             $identifiers = $ini->hasVariable('Subsite', 'Classes') ? $ini->variable('Subsite', 'Classes') : array();
             $root = eZContentObjectTreeNode::fetch(eZINI::instance('content.ini')->variable('NodeSettings', 'RootNode'));
             if (in_array($root->attribute('class_identifier'), $identifiers)) {
                 $result = $root;
             }
             foreach ($path as $item) {
                 if (isset($item['node_id'])) {
                     $node = eZContentObjectTreeNode::fetch($item['node_id']);
                     if (in_array($node->attribute('class_identifier'), $identifiers)) {
                         $result = $node;
                     }
                 }
             }
             return $operatorValue = $result;
             break;
         case 'in_subsite':
             $result = false;
             $identifiers = $ini->hasVariable('Subsite', 'Classes') ? $ini->variable('Subsite', 'Classes') : array();
             $root = eZContentObjectTreeNode::fetch(eZINI::instance('content.ini')->variable('NodeSettings', 'RootNode'));
             if (in_array($root->attribute('class_identifier'), $identifiers)) {
                 $result = $root;
             }
             $node = $operatorValue;
             if (is_numeric($node)) {
                 $node = eZContentObjectTreeNode::fetch($node);
             }
             if (!$node) {
                 return $operatorValue = $result;
             }
             foreach ($node->attribute('path') as $item) {
                 if (in_array($item->attribute('class_identifier'), $identifiers)) {
                     $result = $item;
                     break;
                 }
             }
             return $operatorValue = $result;
             break;
         case 'is_subsite':
             $identifiers = $ini->hasVariable('Subsite', 'Classes') ? $ini->variable('Subsite', 'Classes') : array();
             $inSubsite = false;
             $node = $operatorValue;
             if (is_numeric($node)) {
                 $node = eZContentObjectTreeNode::fetch($node);
             }
             if (!$node instanceof eZContentObjectTreeNode) {
                 $inSubsite = false;
             } elseif (in_array($node->attribute('class_identifier'), $identifiers)) {
                 $inSubsite = true;
             }
             return $operatorValue = $inSubsite;
             break;
         case 'is_in_subsite':
             if ($operatorValue instanceof eZContentObject) {
                 $nodes = $operatorValue->attribute('assigned_nodes');
                 foreach ($nodes as $node) {
                     if ($this->isNodeInCurrentSiteaccess($node)) {
                         return $operatorValue;
                     }
                 }
             } elseif ($operatorValue instanceof eZContentObjectTreeNode) {
                 if ($this->isNodeInCurrentSiteaccess($operatorValue)) {
                     return $operatorValue;
                 }
             }
             return $operatorValue = false;
         case 'section_color':
             $path = $this->getPath($tpl);
             $color = false;
             $attributesIdentifiers = $ini->hasVariable('Color', 'Attributes') ? $ini->variable('Color', 'Attributes') : array();
             foreach ($path as $item) {
                 if (isset($item['node_id'])) {
                     $node = eZContentObjectTreeNode::fetch($item['node_id']);
                     /** @var eZContentObjectAttribute[] $attributes */
                     $attributes = $node->attribute('object')->fetchAttributesByIdentifier($attributesIdentifiers);
                     if (is_array($attributes)) {
                         foreach ($attributes as $attribute) {
                             if ($attribute->hasContent()) {
                                 $color = $attribute->content();
                             }
                         }
                     }
                 }
             }
             return $operatorValue = $color;
             break;
         case 'oc_shorten':
             $search = array('@<script[^>]*?>.*?</script>@si', '@<style[^>]*?>.*?</style>@siU');
             $operatorValue = preg_replace($search, '', $operatorValue);
             $operatorValue = strip_tags($operatorValue, $namedParameters['allowable_tags']);
             $operatorValue = preg_replace('!\\s+!', ' ', $operatorValue);
             $operatorValue = str_replace('&nbsp;', ' ', $operatorValue);
             $strlenFunc = function_exists('mb_strlen') ? 'mb_strlen' : 'strlen';
             $operatorLength = $strlenFunc($operatorValue);
             if ($operatorLength > $namedParameters['chars_to_keep']) {
                 if ($namedParameters['trim_type'] === 'middle') {
                     $appendedStrLen = $strlenFunc($namedParameters['str_to_append']);
                     if ($namedParameters['chars_to_keep'] > $appendedStrLen) {
                         $chop = $namedParameters['chars_to_keep'] - $appendedStrLen;
                         $middlePos = (int) ($chop / 2);
                         $leftPartLength = $middlePos;
                         $rightPartLength = $chop - $middlePos;
                         $operatorValue = trim($this->custom_substr($operatorValue, 0, $leftPartLength) . $namedParameters['str_to_append'] . $this->custom_substr($operatorValue, $operatorLength - $rightPartLength, $rightPartLength));
                     } else {
                         $operatorValue = $namedParameters['str_to_append'];
                     }
                 } else {
                     $chop = $namedParameters['chars_to_keep'] - $strlenFunc($namedParameters['str_to_append']);
                     $operatorValue = $this->custom_substr($operatorValue, 0, $chop);
                     $operatorValue = trim($operatorValue);
                     if ($operatorLength > $chop) {
                         $operatorValue = $operatorValue . $namedParameters['str_to_append'];
                     }
                 }
             }
             if ($namedParameters['allowable_tags'] !== '') {
                 $operatorValue = $this->force_balance_tags($operatorValue);
             }
             break;
         case 'cookieset':
             $key = isset($namedParameters['cookie_name']) ? $namedParameters['cookie_name'] : false;
             $prefix = $ini->variable('CookiesSettings', 'CookieKeyPrefix');
             $key = "{$prefix}{$key}";
             // Get our parameters:
             $value = $namedParameters['cookie_val'];
             $expire = $namedParameters['expiry_time'];
             // Check and calculate the expiry time:
             if ($expire > 0) {
                 // It is a number of days:
                 $expire = time() + 60 * 60 * 24 * $expire;
             }
             setcookie($key, $value, $expire, '/');
             eZDebug::writeDebug('setcookie(' . $key . ', ' . $value . ', ' . $expire . ', "/")', __METHOD__);
             return $operatorValue = false;
             break;
         case 'cookieget':
             $key = isset($namedParameters['cookie_name']) ? $namedParameters['cookie_name'] : false;
             $prefix = $ini->variable('CookiesSettings', 'CookieKeyPrefix');
             $key = "{$prefix}{$key}";
             $operatorValue = false;
             if (isset($_COOKIE[$key])) {
                 $operatorValue = $_COOKIE[$key];
             }
             return $operatorValue;
             break;
         case 'check_and_set_cookies':
             $prefix = $ini->variable('CookiesSettings', 'CookieKeyPrefix');
             $http = eZHTTPTool::instance();
             $return = array();
             if ($ini->hasVariable('Cookies', 'Cookies')) {
                 $cookies = $ini->variable('Cookies', 'Cookies');
                 foreach ($cookies as $key) {
                     $_key = "{$prefix}{$key}";
                     $default = isset($_COOKIE[$_key]) ? $_COOKIE[$_key] : $ini->variable($key, 'Default');
                     $value = $http->variable($key, $default);
                     setcookie($_key, $value, time() + 60 * 60 * 24 * 365, '/');
                     $return[$key] = $value;
                 }
             }
             $operatorValue = $return;
             break;
         case 'checkbrowser':
             @(require 'extension/ocoperatorscollection/lib/browser_detection.php');
             if (function_exists('browser_detection')) {
                 $full = browser_detection('full_assoc', 2);
                 $operatorValue = $full;
             } else {
                 eZDebug::writeError("function browser_detection not found", __METHOD__);
             }
             break;
         case 'is_deprecated_browser':
             $browser = $namedParameters['browser_array'];
             if ($browser['browser_working'] == 'ie' && $browser['browser_number'] > '7.0') {
                 $operatorValue = true;
             }
             $operatorValue = false;
             break;
         case 'slugize':
             $operatorValue = $this->sanitize_title_with_dashes($operatorValue);
             break;
     }
     return false;
 }
function updateClass($classId, $scheduledScript)
{
    $cli = eZCLI::instance();
    /*
    // If the class is not stored yet, store it now
    $class = eZContentClass::fetch( $classId, true, eZContentClass::VERSION_STATUS_TEMPORARY );
    if ( $class )
    {
        $cli->output( "Storing class" );
        $class->storeDefined( $class->fetchAttributes() );
    }
    */
    // Fetch the stored class
    $class = eZContentClass::fetch($classId, true, eZContentClass::VERSION_STATUS_MODIFIED);
    if (!$class) {
        $cli->error('No class in a modified version status with ID: ' . $classId);
        return;
    }
    // Fetch attributes and definitions
    $attributes = $class->fetchAttributes($classId, true, eZContentClass::VERSION_STATUS_MODIFIED);
    $oldClassAttributes = $class->fetchAttributes($classId, true, eZContentClass::VERSION_STATUS_DEFINED);
    // Delete object attributes which have been removed.
    foreach ($oldClassAttributes as $oldClassAttribute) {
        $attributeExist = false;
        $oldClassAttributeID = $oldClassAttribute->attribute('id');
        foreach ($attributes as $newClassAttribute) {
            if ($oldClassAttributeID == $newClassAttribute->attribute('id')) {
                $attributeExist = true;
            }
        }
        if (!$attributeExist) {
            $ezscriptmonitorINI = eZINI::instance('ezscriptmonitor.ini');
            $objectLimit = $ezscriptmonitorINI->variable('GeneralSettings', 'ObjectLimit');
            $limit = array('offset' => 0, 'length' => $objectLimit);
            do {
                $objectAttributes = eZContentObjectAttribute::fetchSameClassAttributeIDList($oldClassAttributeID, false, false, false, $limit);
                $objectAttributeCount = count($objectAttributes);
                $conditions = array("contentclassattribute_id" => $oldClassAttributeID);
                $totalObjectAttributeCount = eZContentObjectAttribute::count(eZContentObjectAttribute::definition(), array("contentclassattribute_id" => $oldClassAttributeID));
                if (is_array($objectAttributes) && $objectAttributeCount > 0) {
                    $db = eZDB::instance();
                    $db->begin();
                    foreach ($objectAttributes as $objectAttribute) {
                        $objectAttribute = new eZContentObjectAttribute($objectAttribute);
                        $objectAttribute->removeThis($objectAttribute->attribute('id'));
                    }
                    $db->commit();
                    $limit['offset'] += $objectAttributeCount;
                    $percentage = round(100 * $limit['offset'] / $totalObjectAttributeCount, 2);
                    // for ezscriptmonitor 100 means the script is all the way done
                    if ($percentage < 100 && $scheduledScript !== false) {
                        $scheduledScript->updateProgress($percentage);
                    }
                    $cli->output("Removing attributes - Progress: " . $percentage . " %");
                }
            } while ($objectAttributeCount == $objectLimit);
        }
    }
    $class->storeVersioned($attributes, eZContentClass::VERSION_STATUS_DEFINED);
    // Add object attributes which have been added.
    foreach ($attributes as $newClassAttribute) {
        $attributeExist = false;
        foreach ($oldClassAttributes as $oldClassAttribute) {
            if ($oldClassAttribute->attribute('id') == $newClassAttribute->attribute('id')) {
                $attributeExist = true;
                break;
            }
        }
        if (!$attributeExist) {
            $objects = null;
            $cli->output("Adding attribute : " . $newClassAttribute->attribute('name'));
            $newClassAttribute->initializeObjectAttributes($objects);
        }
    }
    if ($scheduledScript !== false) {
        $scheduledScript->updateProgress(100);
    }
}
Ejemplo n.º 18
0
$arguments = false;
$useStandardOptions = true;

$options = $script->getOptions( $config, $argumentConfig, $optionHelp, $arguments, $useStandardOptions );
$script->initialize();

$script->setIterationData( '.', '~' );

$db = eZDB::instance();

$db->begin();

require_once( 'kernel/common/image.php' );
$imageManager = imageInit();

$contentObjectAttributes = eZPersistentObject::fetchObjectList( eZContentObjectAttribute::definition(),
                                                                null,
                                                                array( 'data_type_string' => 'ezimage' ) );
$script->resetIteration( count( $contentObjectAttributes ) );

foreach ( $contentObjectAttributes as $contentObjectAttribute )
{
    $success = false;
    $xmlString = $contentObjectAttribute->attribute( 'data_text' );
    if ( $xmlString != '' )
    {
        $dom = new DOMDocument( '1.0', 'UTF-8' );
        $success = $dom->loadXML( $xmlString );
        unset( $dom );
    }
    $path = $options['from_path'];
} else {
    $cli->error("Specifica il percorso da sostituire");
    $script->shutdown();
    eZExecution::cleanExit();
}
$path = rtrim($path, '/') . '/';
$varDir = rtrim($varDir, '/') . '/';
$output = new ezcConsoleOutput();
$question = ezcConsoleQuestionDialog::YesNoQuestion($output, "Correggo i percorsi per VarDir: da \"{$path}\" a \"{$varDir}\" ?", "y");
if (ezcConsoleDialogViewer::displayDialog($question) == "n") {
    $script->shutdown();
    eZExecution::cleanExit();
} else {
    $cli->output("Process ezimagefile table");
    $list = eZImageFile::fetchObjectList(eZImageFile::definition());
    foreach ($list as $item) {
        $newPath = str_replace($path, $varDir, $item->attribute('filepath'));
        if ($newPath != $item->attribute('filepath')) {
            $cli->output("Fix attribute " . $item->attribute('contentobject_attribute_id') . " " . $item->attribute('filepath'));
            eZImageFile::moveFilepath($item->attribute('contentobject_attribute_id'), $item->attribute('filepath'), $newPath);
        }
        $attributes = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, array('id' => $item->attribute('contentobject_attribute_id')));
        foreach ($attributes as $attribute) {
            $newDataText = str_replace($path, $varDir, $attribute->attribute('data_text'));
            $attribute->setAttribute('data_text', $newDataText);
            $attribute->store();
        }
    }
    $script->shutdown();
}
Ejemplo n.º 20
0
 /**
  * Clones the attribute to a new version
  *
  * @param int $newVersionNumber Target version number
  * @param int $currentVersionNumnber Source version number
  * @param int $contentObjectID
  * @param string $newLanguageCode
  *
  * @note The cloned attribute isn't stored automatically
  *
  * @return eZContentObjectAttribute The cloned attribute
  *
  * @todo Deprecate this in favor of a real __clone
  */
 function cloneContentObjectAttribute($newVersionNumber, $currentVersionNumber, $contentObjectID = false, $newLanguageCode = false)
 {
     $tmp = clone $this;
     $tmp->setAttribute("version", $newVersionNumber);
     if ($contentObjectID != false) {
         // if copying the whole object
         if ($contentObjectID != $tmp->attribute('contentobject_id')) {
             $exAttr = eZPersistentObject::fetchObject(eZContentObjectAttribute::definition(), null, array('contentobject_id' => $contentObjectID, 'contentclassattribute_id' => $tmp->attribute('contentclassattribute_id'), 'language_code' => $tmp->attribute('language_code')), true);
             // if the new object already contains the same attribute with another version
             if (is_object($exAttr)) {
                 // we take attribute id from it
                 $id = $exAttr->attribute('id');
             } else {
                 // otherwise new attribute id will be generated
                 $id = null;
             }
             $tmp->setAttribute('id', $id);
         }
         $tmp->setAttribute('contentobject_id', $contentObjectID);
     } else {
         // if not copying, we will remove the information on which language has to be always shown
         $tmp->setAttribute('language_id', $tmp->attribute('language_id') & ~1);
     }
     if ($newLanguageCode != false && $tmp->attribute('language_code') != $newLanguageCode) {
         $exAttr = eZPersistentObject::fetchObject(eZContentObjectAttribute::definition(), null, array('contentobject_id' => $contentObjectID ? $contentObjectID : $tmp->attribute('contentobject_id'), 'contentclassattribute_id' => $tmp->attribute('contentclassattribute_id'), 'language_code' => $newLanguageCode), true);
         // if the new object already contains the same attribute with another version
         if (is_object($exAttr)) {
             $id = $exAttr->attribute('id');
         } else {
             $id = null;
         }
         $tmp->setAttribute('id', $id);
         $tmp->setAttribute('language_code', $newLanguageCode);
         $tmp->setAttribute('language_id', eZContentLanguage::idByLocale($newLanguageCode));
     }
     $db = eZDB::instance();
     $db->begin();
     $tmp->sync();
     $tmp->initialize($currentVersionNumber, $this);
     $tmp->sync();
     $tmp->postInitialize($currentVersionNumber, $this);
     $db->commit();
     return $tmp;
 }
Ejemplo n.º 21
0
$scriptSettings['use-modules'] = false;
$scriptSettings['use-extensions'] = true;
$script = eZScript::instance($scriptSettings);
$script->startup();
$config = '';
$argumentConfig = '';
$optionHelp = false;
$arguments = false;
$useStandardOptions = true;
$options = $script->getOptions($config, $argumentConfig, $optionHelp, $arguments, $useStandardOptions);
$script->initialize();
$script->setIterationData('.', '~');
$db = eZDB::instance();
$db->begin();
$imageManager = eZImageManager::factory();
$contentObjectAttributes = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, array('data_type_string' => 'ezimage'));
$script->resetIteration(count($contentObjectAttributes));
foreach ($contentObjectAttributes as $contentObjectAttribute) {
    $success = false;
    $xmlString = $contentObjectAttribute->attribute('data_text');
    if ($xmlString != '') {
        $dom = new DOMDocument('1.0', 'UTF-8');
        $success = $dom->loadXML($xmlString);
        unset($dom);
    }
    if (!$success) {
        // upgrade from old image system to the one introduced in eZ Publish 3.3
        $imageAliasHandler = new eZImageAliasHandler($contentObjectAttribute);
        $attributeID = $contentObjectAttribute->attribute('id');
        $attributeVersion = $contentObjectAttribute->attribute('version');
        $objectID = $contentObjectAttribute->attribute('contentobject_id');
Ejemplo n.º 22
0
function copySubtree($srcNodeID, $dstNodeID, &$notifications, $allVersions, $keepCreator, $keepTime)
{
    // 1. Copy subtree and form the arrays of accordance of the old and new nodes and content objects.
    $sourceSubTreeMainNode = $srcNodeID ? eZContentObjectTreeNode::fetch($srcNodeID) : false;
    $destinationNode = $dstNodeID ? eZContentObjectTreeNode::fetch($dstNodeID) : false;
    if (!$sourceSubTreeMainNode) {
        eZDebug::writeError("Cannot get subtree main node (nodeID = {$srcNodeID}).", "Subtree copy Error!");
        $notifications['Errors'][] = ezpI18n::tr('kernel/content/copysubtree', "Fatal error: cannot get subtree main node (ID = %1).", null, array($srcNodeID));
        $notifications['Result'] = false;
        return $notifications;
    }
    if (!$destinationNode) {
        eZDebug::writeError("Cannot get destination node (nodeID = {$dstNodeID}).", "Subtree copy Error!");
        $notifications['Errors'][] = ezpI18n::tr('kernel/content/copysubtree', "Fatal error: cannot get destination node (ID = %1).", null, array($dstNodeID));
        $notifications['Result'] = false;
        return $notifications;
    }
    $sourceNodeList = array();
    $syncNodeIDListSrc = array();
    // arrays for synchronizing between source and new IDs of nodes
    $syncNodeIDListNew = array();
    $syncObjectIDListSrc = array();
    // arrays for synchronizing between source and new IDs of contentobjects
    $syncObjectIDListNew = array();
    $sourceSubTreeMainNodeID = $sourceSubTreeMainNode->attribute('node_id');
    $sourceNodeList[] = $sourceSubTreeMainNode;
    $syncNodeIDListSrc[] = $sourceSubTreeMainNode->attribute('parent_node_id');
    $syncNodeIDListNew[] = (int) $dstNodeID;
    $nodeIDBlackList = array();
    // array of nodes which are unable to copy
    $objectIDBlackList = array();
    // array of contentobjects which are unable to copy in any location inside new subtree
    $sourceNodeList = array_merge($sourceNodeList, eZContentObjectTreeNode::subTreeByNodeID(array('Limitation' => array()), $sourceSubTreeMainNodeID));
    $countNodeList = count($sourceNodeList);
    $notifications['Notifications'][] = ezpI18n::tr('kernel/content/copysubtree', "Number of nodes of source subtree - %1", null, array($countNodeList));
    // Prepare list of source node IDs. We will need it in the future
    // for checking node is inside or outside of the subtree being copied.
    $sourceNodeIDList = array();
    foreach ($sourceNodeList as $sourceNode) {
        $sourceNodeIDList[] = $sourceNode->attribute('node_id');
    }
    eZDebug::writeDebug("Source NodeID = {$srcNodeID}, destination NodeID = {$dstNodeID}", "Subtree copy: START!");
    // 1. copying and publishing source subtree
    $k = 0;
    while (count($sourceNodeList) > 0) {
        if ($k > $countNodeList) {
            eZDebug::writeError("Too many loops while copying nodes.", "Subtree Copy Error!");
            break;
        }
        for ($i = 0; $i < count($sourceNodeList); $i) {
            $sourceNodeID = $sourceNodeList[$i]->attribute('node_id');
            // if node was alreaty copied
            if (in_array($sourceNodeID, $syncNodeIDListSrc)) {
                array_splice($sourceNodeList, $i, 1);
                continue;
            }
            //////////// check permissions START
            // if node is already in black list, then skip current node:
            if (in_array($sourceNodeID, $nodeIDBlackList)) {
                array_splice($sourceNodeList, $i, 1);
                continue;
            }
            $sourceObject = $sourceNodeList[$i]->object();
            $srcSubtreeNodeIDlist = $sourceNodeID == $sourceSubTreeMainNodeID ? $syncNodeIDListSrc : $sourceNodeIDList;
            $copyResult = copyPublishContentObject($sourceObject, $srcSubtreeNodeIDlist, $syncNodeIDListSrc, $syncNodeIDListNew, $syncObjectIDListSrc, $syncObjectIDListNew, $objectIDBlackList, $nodeIDBlackList, $notifications, $allVersions, $keepCreator, $keepTime);
            if ($copyResult === 0) {
                // if copying successful then remove $sourceNode from $sourceNodeList
                array_splice($sourceNodeList, $i, 1);
            } else {
                $i++;
            }
        }
        $k++;
    }
    array_shift($syncNodeIDListSrc);
    array_shift($syncNodeIDListNew);
    $countNewNodes = count($syncNodeIDListNew);
    $countNewObjects = count($syncObjectIDListNew);
    $notifications['Notifications'][] = ezpI18n::tr('kernel/content/copysubtree', "Number of copied nodes - %1", null, array($countNewNodes));
    $notifications['Notifications'][] = ezpI18n::tr('kernel/content/copysubtree', "Number of copied contentobjects - %1", null, array($countNewObjects));
    eZDebug::writeDebug(count($syncNodeIDListNew), "Number of copied nodes: ");
    eZDebug::writeDebug(count($syncObjectIDListNew), "Number of copied contentobjects: ");
    eZDebug::writeDebug($objectIDBlackList, "Copy subtree: Not copied object IDs list:");
    eZDebug::writeDebug($nodeIDBlackList, "Copy subtree: Not copied node IDs list:");
    $key = array_search($sourceSubTreeMainNodeID, $syncNodeIDListSrc);
    if ($key === false) {
        eZDebug::writeDebug("Root node of given subtree was not copied.", "Subtree copy:");
        $notifications['Result'] = false;
        return $notifications;
    }
    // 2. fetch all new subtree
    $newSubTreeMainNodeID = $syncNodeIDListSrc[$key];
    $newSubTreeMainNode = eZContentObjectTreeNode::fetch($newSubTreeMainNodeID);
    $newNodeList[] = $newSubTreeMainNode;
    $newNodeList = $sourceNodeList = array_merge($newNodeList, eZContentObjectTreeNode::subTreeByNodeID(false, $newSubTreeMainNodeID));
    // 3. fix local links (in ezcontentobject_link)
    eZDebug::writeDebug("Fixing global and local links...", "Subtree copy:");
    $db = eZDB::instance();
    if (!$db) {
        eZDebug::writeError("Cannot create instance of eZDB for fixing local links (related objects).", "Subtree Copy Error!");
        $notifications['Errors'][] = ezpI18n::tr('kernel/content/copysubtree', "Cannot create instance of eZDB to fix local links (related objects).");
        return $notifications;
    }
    $idListINString = $db->generateSQLINStatement($syncObjectIDListNew, 'from_contentobject_id', false, false, 'int');
    $relatedRecordsList = $db->arrayQuery("SELECT * FROM ezcontentobject_link WHERE {$idListINString}");
    foreach ($relatedRecordsList as $relatedEntry) {
        $kindex = array_search($relatedEntry['to_contentobject_id'], $syncObjectIDListSrc);
        if ($kindex !== false) {
            $newToContentObjectID = (int) $syncObjectIDListNew[$kindex];
            $linkID = (int) $relatedEntry['id'];
            $db->query("UPDATE ezcontentobject_link SET  to_contentobject_id={$newToContentObjectID} WHERE id={$linkID}");
        }
    }
    // 4. duplicating of global links for new contentobjects (in ezurl_object_link) are automatic during copy of contentobject.
    //    it was fixed as bug patch.
    // 5. fixing node_ids and object_ids in ezxmltext attributes of copied objects
    $conditions = array('contentobject_id' => '', 'data_type_string' => 'ezxmltext');
    foreach ($syncObjectIDListNew as $contentObjectID) {
        $conditions['contentobject_id'] = $contentObjectID;
        $attributeList = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $conditions);
        if (count($attributeList) == 0) {
            continue;
        }
        foreach ($attributeList as $xmlAttribute) {
            $xmlText = $xmlAttribute->attribute('data_text');
            $xmlTextLen = strlen($xmlText);
            $isTextModified = false;
            $curPos = 0;
            while ($curPos < $xmlTextLen) {
                $literalTagBeginPos = strpos($xmlText, "<literal", $curPos);
                if ($literalTagBeginPos) {
                    $literalTagEndPos = strpos($xmlText, "</literal>", $literalTagBeginPos);
                    if ($literalTagEndPos === false) {
                        break;
                    }
                    $curPos = $literalTagEndPos + 9;
                }
                if (($tagBeginPos = strpos($xmlText, "<link", $curPos)) !== false or ($tagBeginPos = strpos($xmlText, "<a", $curPos)) !== false or ($tagBeginPos = strpos($xmlText, "<embed", $curPos)) !== false) {
                    $tagEndPos = strpos($xmlText, ">", $tagBeginPos + 1);
                    if ($tagEndPos === false) {
                        break;
                    }
                    $tagText = substr($xmlText, $tagBeginPos, $tagEndPos - $tagBeginPos);
                    if (($nodeIDAttributePos = strpos($tagText, " node_id=\"")) !== false) {
                        $idNumberPos = $nodeIDAttributePos + 10;
                        $quoteEndPos = strpos($tagText, "\"", $idNumberPos);
                        if ($quoteEndPos !== false) {
                            $idNumber = substr($tagText, $idNumberPos, $quoteEndPos - $idNumberPos);
                            $key = array_search((int) $idNumber, $syncNodeIDListSrc);
                            if ($key !== false) {
                                $tagText = substr_replace($tagText, (string) $syncNodeIDListNew[$key], $idNumberPos, $quoteEndPos - $idNumberPos);
                                $xmlText = substr_replace($xmlText, $tagText, $tagBeginPos, $tagEndPos - $tagBeginPos);
                                $isTextModified = true;
                            }
                        }
                    } else {
                        if (($objectIDAttributePos = strpos($tagText, " object_id=\"")) !== false) {
                            $idNumberPos = $objectIDAttributePos + 12;
                            $quoteEndPos = strpos($tagText, "\"", $idNumberPos);
                            if ($quoteEndPos !== false) {
                                $idNumber = substr($tagText, $idNumberPos, $quoteEndPos - $idNumberPos);
                                $key = array_search((int) $idNumber, $syncObjectIDListSrc);
                                if ($key !== false) {
                                    $tagText = substr_replace($tagText, (string) $syncObjectIDListNew[$key], $idNumberPos, $quoteEndPos - $idNumberPos);
                                    $xmlText = substr_replace($xmlText, $tagText, $tagBeginPos, $tagEndPos - $tagBeginPos);
                                    $isTextModified = true;
                                }
                            }
                        }
                    }
                    $curPos = $tagEndPos;
                } else {
                    if (($tagBeginPos = strpos($xmlText, "<object", $curPos)) !== false) {
                        $tagEndPos = strpos($xmlText, ">", $tagBeginPos + 1);
                        if (!$tagEndPos) {
                            break;
                        }
                        $tagText = substr($xmlText, $tagBeginPos, $tagEndPos - $tagBeginPos);
                        if (($idAttributePos = strpos($tagText, " id=\"")) !== false) {
                            $idNumberPos = $idAttributePos + 5;
                            $quoteEndPos = strpos($tagText, "\"", $idNumberPos);
                            if ($quoteEndPos !== false) {
                                $idNumber = substr($tagText, $idNumberPos, $quoteEndPos - $idNumberPos);
                                $key = array_search((int) $idNumber, $syncObjectIDListSrc);
                                if ($key !== false) {
                                    $tagText = substr_replace($tagText, (string) $syncObjectIDListNew[$key], $idNumberPos, $quoteEndPos - $idNumberPos);
                                    $xmlText = substr_replace($xmlText, $tagText, $tagBeginPos, $tagEndPos - $tagBeginPos);
                                    $isTextModified = true;
                                }
                            }
                        }
                        $curPos = $tagEndPos;
                    } else {
                        break;
                    }
                }
            }
            // while END
            if ($isTextModified) {
                $xmlAttribute->setAttribute('data_text', $xmlText);
                $xmlAttribute->store();
            }
        }
        // foreach END
    }
    // 6. fixing datatype ezobjectrelationlist
    $conditions = array('contentobject_id' => '', 'data_type_string' => 'ezobjectrelationlist');
    foreach ($syncObjectIDListNew as $contentObjectID) {
        $conditions['contentobject_id'] = $contentObjectID;
        $attributeList = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, $conditions);
        if (count($attributeList) == 0) {
            continue;
        }
        foreach ($attributeList as $relationListAttribute) {
            $relationsXmlText = $relationListAttribute->attribute('data_text');
            $relationsDom = eZObjectRelationListType::parseXML($relationsXmlText);
            $relationItems = $relationsDom->getElementsByTagName('relation-item');
            $isRelationModified = false;
            foreach ($relationItems as $relationItem) {
                $originalObjectID = $relationItem->getAttribute('contentobject-id');
                $key = array_search($originalObjectID, $syncObjectIDListSrc);
                if ($key !== false) {
                    $newObjectID = $syncObjectIDListNew[$key];
                    $relationItem->setAttribute('contentobject-id', $newObjectID);
                    $isRelationModified = true;
                }
                $originalNodeID = $relationItem->getAttribute('node-id');
                if ($originalNodeID) {
                    $key = array_search($originalNodeID, $syncNodeIDListSrc);
                    if ($key !== false) {
                        $newNodeID = $syncNodeIDListNew[$key];
                        $relationItem->setAttribute('node-id', $newNodeID);
                        $newNode = eZContentObjectTreeNode::fetch($newNodeID);
                        $newParentNodeID = $newNode->attribute('parent_node_id');
                        $relationItem->setAttribute('parent-node-id', $newParentNodeID);
                        $isRelationModified = true;
                    }
                }
            }
            if ($isRelationModified) {
                $attributeID = $relationListAttribute->attribute('id');
                $attributeVersion = $relationListAttribute->attribute('version');
                $changedDomString = $db->escapeString(eZObjectRelationListType::domString($relationsDom));
                $db->query("UPDATE ezcontentobject_attribute SET data_text='{$changedDomString}'\n                             WHERE id={$attributeID} AND version={$attributeVersion}");
            }
        }
    }
    eZDebug::writeDebug("Successfuly DONE.", "Copy subtree:");
    $notifications['Result'] = true;
    return $notifications;
}
 function removeRelationObject($contentObjectAttribute, $deletionItem)
 {
     if (eZObjectRelationBrowseType::isItemPublished($deletionItem)) {
         return;
     }
     $hostObject = $contentObjectAttribute->attribute('object');
     $hostObjectVersions = $hostObject->versions();
     $isDeletionAllowed = true;
     // check if the relation item to be deleted is unique in the domain of all host-object versions
     foreach ($hostObjectVersions as $version) {
         if ($isDeletionAllowed and $version->attribute('version') != $contentObjectAttribute->attribute('version')) {
             $relationAttribute = eZPersistentObject::fetchObjectList(eZContentObjectAttribute::definition(), null, array('version' => $version->attribute('version'), 'contentobject_id' => $hostObject->attribute('id'), 'contentclassattribute_id' => $contentObjectAttribute->attribute('contentclassattribute_id')));
             if (count($relationAttribute) > 0) {
                 $relationContent = $relationAttribute[0]->content();
                 if (is_array($relationContent) and is_array($relationContent['relation_browse'])) {
                     foreach ($relationContent['relation_browse'] as $relationItem) {
                         if ($deletionItem['contentobject_id'] == $relationItem['contentobject_id'] && $deletionItem['contentobject_version'] == $relationItem['contentobject_version']) {
                             $isDeletionAllowed = false;
                             break 2;
                         }
                     }
                 }
             }
         }
     }
     if ($isDeletionAllowed) {
         $subObjectVersion = eZContentObjectVersion::fetchVersion($deletionItem['contentobject_version'], $deletionItem['contentobject_id']);
         if ($subObjectVersion instanceof eZContentObjectVersion) {
             $subObjectVersion->removeThis();
         } else {
             eZDebug::writeError('Cleanup of subobject-version failed. Could not fetch object from relation list.\\n' . 'Requested subobject id: ' . $deletionItem['contentobject_id'] . '\\n' . 'Requested Subobject version: ' . $deletionItem['contentobject_version'], 'eZObjectRelationBrowseType::removeRelationObject');
         }
     }
 }