function __construct($id, $createIfNotExists = false, $options = array(), $remoteUrl = null)
 {
     $this->notifications = array(self::ERROR => array(), self::WARNING => array(), self::NOTICE => array());
     if ($remoteUrl !== NULL) {
         self::setRemoteUrl($remoteUrl);
     }
     $class = eZContentClass::fetch(intval($id));
     $this->options = $options;
     $this->data = new stdClass();
     if (!$class instanceof eZContentClass) {
         $class = eZContentClass::fetchByIdentifier($id);
     }
     if (!$class instanceof eZContentClass) {
         if (!$createIfNotExists) {
             throw new Exception("Classe {$id} non trovata");
         } else {
             if (!is_numeric($id)) {
                 eZDebug::writeWarning("Creazione della classe {$id}");
                 $class = $this->createNew($id);
                 if (!$class instanceof eZContentClass) {
                     throw new Exception("Fallita la creazionde della classe {$id}");
                 }
             } else {
                 throw new Exception("Per creare automaticamente una nuova classe è necessario fornire l'identificativo e non l'id numerico");
             }
         }
     }
     $this->currentClass = $class;
     $this->id = $this->currentClass->attribute('id');
     $this->identifier = $this->currentClass->attribute('identifier');
 }
예제 #2
0
 public function execute($process, $event)
 {
     $processParameters = $process->attribute('parameter_list');
     $object = eZContentObject::fetch($processParameters['object_id']);
     $targetClassIdentifier = $object->contentClass()->attribute('identifier');
     $iniGroups = eZINI::instance('ngindexer.ini')->groups();
     $targets = array();
     foreach ($iniGroups as $iniGroupName => $iniGroup) {
         $iniGroupNameArray = explode('/', $iniGroupName);
         if (is_array($iniGroupNameArray) && count($iniGroupNameArray) == 3) {
             $class = eZContentClass::fetchByIdentifier($iniGroupNameArray[0]);
             if ($class instanceof eZContentClass) {
                 $classAttribute = $class->fetchAttributeByIdentifier($iniGroupNameArray[1]);
                 if ($classAttribute instanceof eZContentClassAttribute) {
                     $indexTarget = isset($iniGroup['IndexTarget']) ? trim($iniGroup['IndexTarget']) : '';
                     $referencedClassIdentifiers = isset($iniGroup['ClassIdentifiers']) && is_array($iniGroup['ClassIdentifiers']) ? $iniGroup['ClassIdentifiers'] : null;
                     if ($referencedClassIdentifiers != null && (empty($referencedClassIdentifiers) || in_array($targetClassIdentifier, $referencedClassIdentifiers))) {
                         switch ($indexTarget) {
                             case 'parent':
                             case 'parent_line':
                                 $children = eZContentObjectTreeNode::subTreeByNodeID(array('ClassFilterType' => 'include', 'ClassFilterArray' => array($iniGroupNameArray[0]), 'Depth' => $indexTarget == 'parent' ? 1 : false), $object->mainNode()->attribute('node_id'));
                                 if (is_array($children)) {
                                     $targets = array_merge($targets, $children);
                                 }
                                 break;
                             case 'children':
                                 $parentNode = $object->mainNode()->fetchParent();
                                 if ($parentNode->classIdentifier() == $iniGroupNameArray[0]) {
                                     $targets[] = $parentNode;
                                 }
                                 break;
                             case 'subtree':
                                 $path = $object->mainNode()->fetchPath();
                                 foreach ($path as $pathNode) {
                                     if ($pathNode->classIdentifier() == $iniGroupNameArray[0]) {
                                         $targets[] = $parentNode;
                                     }
                                 }
                                 break;
                             default:
                                 continue;
                         }
                     }
                 }
             }
         }
     }
     $filteredTargets = array();
     foreach ($targets as $target) {
         $objectID = $target->attribute('contentobject_id');
         $version = $target->object()->attribute('current_version');
         if (!isset($filteredTargets[$objectID])) {
             $filteredTargets[$objectID] = $version;
             eZContentOperationCollection::registerSearchObject($objectID, $version);
         }
     }
     return eZWorkflowType::STATUS_ACCEPTED;
 }
예제 #3
0
파일: index.php 프로젝트: truffo/eep
 private function attribute_migrate($classIdentifier, $srcAttribute, $conversion, $destAttribute)
 {
     $contentClass = eZContentClass::fetchByIdentifier($classIdentifier);
     if (!$contentClass) {
         throw new Exception("Failed to instantiate content class [" . $classIdentifier . "]");
     }
     $classDataMap = $contentClass->attribute("data_map");
     if (!isset($classDataMap[$srcAttribute])) {
         throw new Exception("Content class '" . $classIdentifier . "' does not contain this attribute: [" . $srcAttribute . "]");
     }
     if (!isset($classDataMap[$destAttribute])) {
         throw new Exception("Content class '" . $classIdentifier . "' does not contain this attribute: [" . $destAttribute . "]");
     }
     $classId = $contentClass->attribute("id");
     $objects = eZContentObject::fetchSameClassList($classId, false);
     $numObjects = count($objects);
     $conversionFunc = null;
     switch ($conversion) {
         default:
             echo "This mapping is not supported: [" . $conversion . "]\n";
             return;
             break;
         case "rot13":
             $conversionFunc = "convertStringToRot13";
             break;
         case "time2integer":
             $conversionFunc = "convertTimeToInteger";
             break;
         case "trim":
             $conversionFunc = "convertTrim";
             break;
         case "date2ts":
             $conversionFunc = "dateToTS";
             break;
     }
     foreach ($objects as $n => $object) {
         $object = eZContentObject::fetch($object["id"]);
         if ($object) {
             // copy data with conversion
             $dataMap = $object->DataMap();
             $src = $dataMap[$srcAttribute];
             $dest = $dataMap[$destAttribute];
             $dest->fromString(eep::$conversionFunc($src->toString()));
             $dest->store();
             // publish to get changes recognized, eg object title updated
             eep::republishObject($object->attribute("id"));
         }
         echo "Percent complete: " . sprintf("% 3.3f", ($n + 1.0) / $numObjects * 100.0) . "%\r";
         // clear caches
         unset($GLOBALS["eZContentObjectContentObjectCache"]);
         unset($GLOBALS["eZContentObjectDataMapCache"]);
         unset($GLOBALS["eZContentObjectVersionCache"]);
         unset($object);
     }
     echo "\n";
 }
 /**
  * Ritorna l'elengo dei tag disponibili
  * 
  * @return eZTagsObject[]
  */
 public static function notificationAvailableTags()
 {
     $class = eZContentClass::fetchByIdentifier(self::CLASS_IDENTIFIER);
     if ($class instanceof eZContentClass) {
         $classAttribute = $class->fetchAttributeByIdentifier(self::TAG_ATTRIBUTE_IDENTIFIER);
         if ($classAttribute instanceof eZContentClassAttribute) {
             $tagRoot = eZTagsObject::fetch(intval($classAttribute->attribute(eZTagsType::SUBTREE_LIMIT_FIELD)));
             return $tagRoot->getChildren();
         }
     }
     return array();
 }
예제 #5
0
 function initSettings($parameters)
 {
     $siteINI = eZINI::instance();
     $classIdentifier = 'template_look';
     //get the class
     $class = eZContentClass::fetchByIdentifier($classIdentifier, true, eZContentClass::VERSION_STATUS_TEMPORARY);
     if (!$class) {
         $class = eZContentClass::fetchByIdentifier($classIdentifier, true, eZContentClass::VERSION_STATUS_DEFINED);
         if (!$class) {
             eZDebug::writeError("Warning, DEFINED version for class identifier {$classIdentifier} does not exist.");
             return;
         }
     }
     $classId = $class->attribute('id');
     $this->Settings['template_look_class_id'] = $classId;
     $objects = eZContentObject::fetchSameClassList($classId);
     if (!count($objects)) {
         eZDebug::writeError("Object of class {$classIdentifier} does not exist.");
         return;
     }
     $templateLookObject = $objects[0];
     $this->Settings['template_look_object'] = $templateLookObject;
     $this->Settings['template_look_object_id'] = $templateLookObject->attribute('id');
     if (!is_array($parameters)) {
         return;
     }
     $this->addSetting('admin_account_id', eZSiteInstaller::getParam($parameters, 'object_remote_map/1bb4fe25487f05527efa8bfd394cecc7', ''));
     $this->addSetting('guest_accounts_id', eZSiteInstaller::getParam($parameters, 'object_remote_map/5f7f0bdb3381d6a461d8c29ff53d908f', ''));
     $this->addSetting('anonymous_accounts_id', eZSiteInstaller::getParam($parameters, 'object_remote_map/15b256dbea2ae72418ff5facc999e8f9', ''));
     $this->addSetting('package_object', eZSiteInstaller::getParam($parameters, 'package_object', false));
     $this->addSetting('design_list', eZSiteInstaller::getParam($parameters, 'design_list', array()));
     $this->addSetting('main_site_design', strtolower($this->solutionName()));
     $this->addSetting('extension_list', array('ezwt', 'ezstarrating', 'ezgmaplocation', strtolower($this->solutionName())));
     $this->addSetting('version', $this->solutionVersion());
     $this->addSetting('locales', eZSiteInstaller::getParam($parameters, 'all_language_codes', array()));
     // usual user siteaccess like 'ezwebin_site'
     $this->addSetting('user_siteaccess', eZSiteInstaller::getParam($parameters, 'user_siteaccess', ''));
     // usual admin siteaccess like 'ezwebin_site_admin'
     $this->addSetting('admin_siteaccess', eZSiteInstaller::getParam($parameters, 'admin_siteaccess', ''));
     // extra siteaccess based on languages info, like 'eng', 'rus', ...
     $this->addSetting('language_based_siteaccess_list', $this->languageNameListFromLocaleList($this->setting('locales')));
     $this->addSetting('user_siteaccess_list', array_merge(array($this->setting('user_siteaccess')), $this->setting('language_based_siteaccess_list')));
     $this->addSetting('all_siteaccess_list', array_merge($this->setting('user_siteaccess_list'), array($this->setting('admin_siteaccess'))));
     $this->addSetting('access_type', eZSiteInstaller::getParam($parameters, 'site_type/access_type', ''));
     $this->addSetting('access_type_value', eZSiteInstaller::getParam($parameters, 'site_type/access_type_value', ''));
     $this->addSetting('admin_access_type_value', eZSiteInstaller::getParam($parameters, 'site_type/admin_access_type_value', ''));
     $this->addSetting('host', eZSiteInstaller::getParam($parameters, 'host', ''));
     $siteaccessUrls = array('admin' => $this->createSiteaccessUrls(array('siteaccess_list' => array($this->setting('admin_siteaccess')), 'access_type' => $this->setting('access_type'), 'access_type_value' => $this->setting('admin_access_type_value'), 'host' => $this->setting('host'), 'host_prepend_siteaccess' => false)), 'user' => $this->createSiteaccessUrls(array('siteaccess_list' => array($this->setting('user_siteaccess')), 'access_type' => $this->setting('access_type'), 'access_type_value' => $this->setting('access_type_value'), 'host' => $this->setting('host'), 'host_prepend_siteaccess' => false)), 'translation' => $this->createSiteaccessUrls(array('siteaccess_list' => $this->setting('language_based_siteaccess_list'), 'access_type' => $this->setting('access_type'), 'access_type_value' => $this->setting('access_type_value') + 1, 'host' => $this->setting('host'), 'exclude_port_list' => array($this->setting('admin_access_type_value'), $this->setting('access_type_value')))));
     $this->addSetting('siteaccess_urls', $siteaccessUrls);
     $this->addSetting('primary_language', eZSiteInstaller::getParam($parameters, 'all_language_codes/0', ''));
     $this->addSetting('var_dir', eZSiteInstaller::getParam($parameters, 'var_dir', 'var/' . $this->setting('user_siteaccess')));
 }
예제 #6
0
 public function __construct($classIdentifier, $parentNodeID = false, $creatorID = 14, $section = 1, $languageCode = false)
 {
     $this->class = eZContentClass::fetchByIdentifier($classIdentifier);
     if (!$this->class instanceof eZContentClass) {
         throw new ezcBaseValueException('class', isset($this->class) ? get_class($this->class) : null, 'eZContentClass ($classIdentifier was: ' . $classIdentifier . ' ) ', 'member');
     }
     $this->object = $this->class->instantiate($creatorID, $section, false, $languageCode);
     // Create main node
     if (is_numeric($parentNodeID)) {
         $this->mainNode = new ezpNode($this->object, $parentNodeID, true);
     }
     $this->nodes = array($this->mainNode);
 }
 /**
  * Unit test for eZContentClass::versionHistoryLimit() with object parameters
  *
  * Replica of testVersionHistoryLimit() but you cannot make calls
  * to the eZ API which relies on a database, as this is not present
  * in the provider methods.
  */
 public function testVersionHistoryLimitWithObjectParameter()
 {
     // different custom limits (article: 13, image: 6) and object as a parameter
     $INISettings = array(array('VersionHistoryClass', array('article' => 13, 'image' => 6)));
     $class = eZContentClass::fetchByIdentifier('image');
     $expectedLimit = 6;
     // change the INI limit settings
     foreach ($INISettings as $settings) {
         list($INIVariable, $INIValue) = $settings;
         ezpINIHelper::setINISetting('content.ini', 'VersionManagement', $INIVariable, $INIValue);
     }
     $limit = eZContentClass::versionHistoryLimit($class);
     self::assertEquals($expectedLimit, $limit);
     ezpINIHelper::restoreINISettings();
 }
 private function updateContentObject(eZContentObject $eZContentObject)
 {
     $mainNodeID = $eZContentObject->mainNodeID();
     $parentNodeID = eZContentObjectTreeNode::getParentNodeId($mainNodeID);
     $classIdentifier = $eZContentObject->ClassIdentifier;
     $remoteID = $eZContentObject->RemoteID;
     if (!eZContentClass::fetchByIdentifier($classIdentifier)) {
         throw new Exception("La classe" . $classIdentifier . "non esiste in questa installazione");
     }
     $params = array();
     $params['class_identifier'] = $classIdentifier;
     $params['remote_id'] = $remoteID;
     $params['parent_node_id'] = $parentNodeID;
     $params['attributes'] = $this->getAttributesStringArray($eZContentObject);
     $result = eZContentFunctions::updateAndPublishObject($eZContentObject, $params);
     return $result;
 }
 function modify(&$tpl, &$operatorName, &$operatorParameters, &$rootNamespace, &$currentNamespace, &$operatorValue, &$namedParameters)
 {
     switch ($operatorName) {
         case 'class_extra_parameters':
             $classIdentifier = $namedParameters['class_identifier'];
             $handler = $namedParameters['handler'];
             $class = eZContentClass::fetchByIdentifier($classIdentifier);
             if ($class instanceof eZContentClass) {
                 $extraParametersManager = OCClassExtraParametersManager::instance($class);
                 if (is_string($handler)) {
                     $operatorValue = $extraParametersManager->getHandler($handler);
                 } else {
                     $operatorValue = $extraParametersManager->getHandlers();
                 }
             }
             break;
     }
 }
예제 #10
0
 /**
  * Data provider for testGetFieldName
  **/
 public static function providerTestGetFieldName()
 {
     $providerArray = array();
     $providerArray[] = array(ezfSolrDocumentFieldBase::ATTR_FIELD_PREFIX . 'title_t', 'article/title');
     if ($contentClass = eZContentClass::fetchByIdentifier('article')) {
         $contentClassId = $contentClass->attribute('id');
         $providerArray[] = array(array('fieldName' => ezfSolrDocumentFieldBase::ATTR_FIELD_PREFIX . 'title_t', 'contentClassId' => $contentClassId), 'article/title', true);
     }
     /*
     if ( $contentClass = eZContentClass::fetchByIdentifier( 'article' ) )
     {
         $providerArray[] = array(
             ezfSolrDocumentFieldBase::SUBATTR_FIELD_PREFIX . 'image-alternative_text_t',
             'article/image/alternative_text'
         );
     }
     */
     return $providerArray;
 }
 public function fetch($parameters, $publishedAfter, $publishedBeforeOrAt)
 {
     $ini = eZINI::instance('block.ini');
     $limit = 5;
     if ($ini->hasVariable('Keywords', 'NumberOfValidItems')) {
         $limit = $ini->variable('Keywords', 'NumberOfValidItems');
     }
     if (isset($parameters['Source']) && $parameters['Source'] != '') {
         $nodeID = $parameters['Source'];
         $node = eZContentObjectTreeNode::fetch($nodeID, false, false);
         // not as an object
         if ($node && $node['modified_subnode'] <= $publishedAfter) {
             return array();
         }
     } else {
         $nodeID = false;
     }
     $sortBy = array('published', false);
     $classIDs = array();
     if (isset($parameters['Classes']) && $parameters['Classes'] != '') {
         $classIdentifiers = explode(',', $parameters['Classes']);
         foreach ($classIdentifiers as $classIdentifier) {
             $class = eZContentClass::fetchByIdentifier($classIdentifier, false);
             // not as an object
             if ($class) {
                 $classIDs[] = $class['id'];
             }
         }
     }
     if (isset($parameters['Keywords'])) {
         $keywords = $parameters['Keywords'];
     }
     $result = eZFunctionHandler::execute('content', 'keyword', array('alphabet' => $keywords, 'classid' => $classIDs, 'offset' => 0, 'limit' => $limit, 'parent_node_id' => $nodeID, 'include_duplicates' => false, 'sort_by' => $sortBy, 'strict_matching' => false));
     if ($result === null) {
         return array();
     }
     $fetchResult = array();
     foreach ($result as $item) {
         $fetchResult[] = array('object_id' => $item['link_object']->attribute('contentobject_id'), 'node_id' => $item['link_object']->attribute('node_id'), 'ts_publication' => $item['link_object']->object()->attribute('published'));
     }
     return $fetchResult;
 }
 function createObject($classIdentifier, $parentNodeID, $name)
 {
     $user = eZUser::currentUser();
     $Class = eZContentClass::fetchByIdentifier($classIdentifier);
     if (!$Class) {
         eZDebug::writeError("No class with identifier {$classIdentifier}", "classCreation");
         return false;
     }
     $contentObject = $Class->instantiate($user->attribute('contentobject_id'));
     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1));
     $nodeAssignment->store();
     $version = $contentObject->version(1);
     $version->setAttribute('modified', eZDateTime::currentTimeStamp());
     $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
     $version->store();
     $contentObjectID = $contentObject->attribute('id');
     $attributes = $contentObject->attribute('contentobject_attributes');
     $attributes[0]->fromString($name);
     $attributes[0]->store();
     $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1));
     return true;
 }
    /**
     * Unserialize xml structure. Creates an object from xml input.
     *
     * Transaction unsafe. If you call several transaction unsafe methods you must enclose
     * the calls within a db transaction; thus within db->begin and db->commit.
     *
     * @param mixed $package
     * @param DOMElement $domNode
     * @param array $options
     * @param int|bool $ownerID Override owner ID, null to use XML owner id (optional)
     * @param string $handlerType
     * @return array|bool|eZContentObject|null created object, false if could not create object/xml invalid
     */
    static function unserialize( $package, $domNode, &$options, $ownerID = false, $handlerType = 'ezcontentobject' )
    {
        if ( $domNode->localName != 'object' )
        {
            $retValue = false;
            return $retValue;
        }

        $initialLanguage = eZContentObject::mapLanguage( $domNode->getAttribute( 'initial_language' ), $options );
        if( $initialLanguage === 'skip' )
        {
            $retValue = true;
            return $retValue;
        }

        $sectionID = $domNode->getAttributeNS( 'http://ez.no/ezobject', 'section_id' );
        if ( $ownerID === false )
        {
            $ownerID = $domNode->getAttributeNS( 'http://ez.no/ezobject', 'owner_id' );
        }
        $remoteID = $domNode->getAttribute( 'remote_id' );
        $name = $domNode->getAttribute( 'name' );
        $classRemoteID = $domNode->getAttribute( 'class_remote_id' );
        $classIdentifier = $domNode->getAttributeNS( 'http://ez.no/ezobject', 'class_identifier' );
        $alwaysAvailable = ( $domNode->getAttributeNS( 'http://ez.no/ezobject', 'always_available' ) == '1' );

        $contentClass = eZContentClass::fetchByRemoteID( $classRemoteID );
        if ( !$contentClass )
        {
            $contentClass = eZContentClass::fetchByIdentifier( $classIdentifier );
        }

        if ( !$contentClass )
        {
            $options['error'] = array( 'error_code' => self::PACKAGE_ERROR_NO_CLASS,
                                       'element_id' => $remoteID,
                                       'description' => "Can't install object '$name': Unable to fetch class with remoteID: $classRemoteID." );
            $retValue = false;
            return $retValue;
        }

        /** @var DOMElement $versionListNode */
        $versionListNode = $domNode->getElementsByTagName( 'version-list' )->item( 0 );

        $importedLanguages = array();
        foreach( $versionListNode->getElementsByTagName( 'version' ) as $versionDOMNode )
        {
            /** @var DOMElement $versionDOMNode */
            foreach ( $versionDOMNode->getElementsByTagName( 'object-translation' ) as $versionDOMNodeChild )
            {
                /** @var DOMElement $versionDOMNodeChild */
                $importedLanguage = eZContentObject::mapLanguage( $versionDOMNodeChild->getAttribute( 'language' ), $options );
                $language = eZContentLanguage::fetchByLocale( $importedLanguage );
                // Check if the language is allowed in this setup.
                if ( $language )
                {
                    $hasTranslation = true;
                }
                else
                {
                    if ( $importedLanguage == 'skip' )
                        continue;

                    // if there is no needed translation in system then add it
                    $locale = eZLocale::instance( $importedLanguage );
                    $translationName = $locale->internationalLanguageName();
                    $translationLocale = $locale->localeCode();

                    if ( $locale->isValid() )
                    {
                        eZContentLanguage::addLanguage( $locale->localeCode(), $locale->internationalLanguageName() );
                        $hasTranslation = true;
                    }
                    else
                        $hasTranslation = false;
                }
                if ( $hasTranslation )
                {
                    $importedLanguages[] = $importedLanguage;
                    $importedLanguages = array_unique( $importedLanguages );
                }
            }
        }

        // If object exists we return a error.
        // Minimum install element is an object now.

        $contentObject = eZContentObject::fetchByRemoteID( $remoteID );
        // Figure out initial language
        if ( !$initialLanguage ||
             !in_array( $initialLanguage, $importedLanguages ) )
        {
            $initialLanguage = false;
            foreach ( eZContentLanguage::prioritizedLanguages() as $language )
            {
                if ( in_array( $language->attribute( 'locale' ), $importedLanguages ) )
                {
                    $initialLanguage = $language->attribute( 'locale' );
                    break;
                }
            }
        }
        if ( !$contentObject )
        {
            $firstVersion = true;
            $contentObject = $contentClass->instantiateIn( $initialLanguage, $ownerID, $sectionID );
        }
        else
        {
            $firstVersion = false;
            $description = "Object '$name' already exists.";

            $choosenAction = eZPackageHandler::errorChoosenAction( self::PACKAGE_ERROR_EXISTS,
                                                                   $options, $description, $handlerType, false );

            switch( $choosenAction )
            {
                case eZPackage::NON_INTERACTIVE:
                case self::PACKAGE_UPDATE:
                {
                    // Keep existing contentobject.
                } break;

                case self::PACKAGE_REPLACE:
                {
                    eZContentObjectOperations::remove( $contentObject->attribute( 'id' ) );

                    unset( $contentObject );
                    $contentObject = $contentClass->instantiateIn( $initialLanguage, $ownerID, $sectionID );
                    $firstVersion = true;
                } break;

                case self::PACKAGE_SKIP:
                {
                    $retValue = true;
                    return $retValue;
                } break;

                case self::PACKAGE_NEW:
                {
                    $contentObject->setAttribute( 'remote_id', eZRemoteIdUtility::generate( 'object' ) );
                    $contentObject->store();
                    unset( $contentObject );
                    $contentObject = $contentClass->instantiateIn( $initialLanguage, $ownerID, $sectionID );
                    $firstVersion = true;
                } break;

                default:
                {
                    $options['error'] = array( 'error_code' => self::PACKAGE_ERROR_EXISTS,
                                               'element_id' => $remoteID,
                                               'description' => $description,
                                               'actions' => array( self::PACKAGE_REPLACE => ezpI18n::tr( 'kernel/classes', 'Replace existing object' ),
                                                                   self::PACKAGE_SKIP    => ezpI18n::tr( 'kernel/classes', 'Skip object' ),
                                                                   self::PACKAGE_NEW     => ezpI18n::tr( 'kernel/classes', 'Keep existing and create a new one' ),
                                                                   self::PACKAGE_UPDATE  => ezpI18n::tr( 'kernel/classes', 'Update existing object' ) ) );
                    $retValue = false;
                    return $retValue;
                } break;
            }
        }

        $db = eZDB::instance();
        $db->begin();

        if ( $alwaysAvailable )
        {
            // Make sure always available bit is set.
            $contentObject->setAttribute( 'language_mask', (int)$contentObject->attribute( 'language_mask' ) | 1 );
        }

        $contentObject->setAttribute( 'section_id', $sectionID );
        $contentObject->store();
        $activeVersion = false;
        $lastVersion = false;
        $versionListActiveVersion = $versionListNode->getAttribute( 'active_version' );

        $contentObject->setAttribute( 'remote_id', $remoteID );
        $contentObject->setAttribute( 'contentclass_id', $contentClass->attribute( 'id' ) );
        $contentObject->store();

        $sectionObject = eZSection::fetch( $sectionID );
        if ( $sectionObject instanceof eZSection )
        {
            $updateWithParentSection = false;
        }
        else
        {
            $updateWithParentSection = true;
        }

        $options['language_array'] = $importedLanguages;
        $versionList = array();
        foreach( $versionListNode->getElementsByTagName( 'version' ) as $versionDOMNode )
        {
            unset( $nodeList );
            $nodeList = array();
            $contentObjectVersion = eZContentObjectVersion::unserialize( $versionDOMNode,
                                                                         $contentObject,
                                                                         $ownerID,
                                                                         $sectionID,
                                                                         $versionListActiveVersion,
                                                                         $firstVersion,
                                                                         $nodeList,
                                                                         $options,
                                                                         $package,
                                                                         'ezcontentobject',
                                                                         $initialLanguage );

            if ( !$contentObjectVersion )
            {
                $db->commit();

                $retValue = false;
                return $retValue;
            }

            $versionStatus = $versionDOMNode->getAttributeNS( 'http://ez.no/ezobject', 'status' );
            $versionList[$versionDOMNode->getAttributeNS( 'http://ez.no/ezobject', 'version' )] = array( 'node_list' => $nodeList,
                                                                                                         'status' =>    $versionStatus );
            unset( $versionStatus );

            $firstVersion = false;
            $lastVersion = $contentObjectVersion->attribute( 'version' );
            if ( $versionDOMNode->getAttribute( 'version' ) == $versionListActiveVersion )
            {
                $activeVersion = $contentObjectVersion->attribute( 'version' );
            }
            eZNodeAssignment::setNewMainAssignment( $contentObject->attribute( 'id' ), $lastVersion );

            eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $contentObject->attribute( 'id' ),
                                                                      'version' => $lastVersion ) );

            $mainNodeInfo = null;
            foreach ( $nodeList as $nodeInfo )
            {
                if ( $nodeInfo['is_main'] )
                {
                    $mainNodeInfo =& $nodeInfo;
                    break;
                }
            }
            if ( $mainNodeInfo )
            {
                $existingMainNode = eZContentObjectTreeNode::fetchByRemoteID( $mainNodeInfo['parent_remote_id'], false );
                if ( $existingMainNode )
                {
                    eZContentObjectTreeNode::updateMainNodeID( $existingMainNode['node_id'],
                                                               $mainNodeInfo['contentobject_id'],
                                                               $mainNodeInfo['contentobject_version'],
                                                               $mainNodeInfo['parent_node'],
                                                               $updateWithParentSection );
                }
            }
            unset( $mainNodeInfo );
            // Refresh $contentObject from DB.
            $contentObject = eZContentObject::fetch( $contentObject->attribute( 'id' ) );
        }
        if ( !$activeVersion )
        {
            $activeVersion = $lastVersion;
        }

        /*
        $contentObject->setAttribute( 'current_version', $activeVersion );
        */
        $contentObject->setAttribute( 'name', $name );
        if ( isset( $options['use_dates_from_package'] ) && $options['use_dates_from_package'] )
        {
            $contentObject->setAttribute( 'published', eZDateUtils::textToDate( $domNode->getAttributeNS( 'http://ez.no/ezobject', 'published' ) ) );
            $contentObject->setAttribute( 'modified', eZDateUtils::textToDate( $domNode->getAttributeNS( 'http://ez.no/ezobject', 'modified' ) ) );
        }
        $contentObject->store();

        $versions   = $contentObject->versions();
        $objectName = $contentObject->name();
        $objectID   = $contentObject->attribute( 'id' );
        foreach ( $versions as $version )
        {
            $versionNum       = $version->attribute( 'version' );
            $oldVersionStatus = $version->attribute( 'status' );
            $newVersionStatus = isset( $versionList[$versionNum] ) ? $versionList[$versionNum]['status'] : null;

            // set the correct status for non-published versions
            if ( isset( $newVersionStatus ) && $oldVersionStatus != $newVersionStatus && $newVersionStatus != eZContentObjectVersion::STATUS_PUBLISHED )
            {
                $version->setAttribute( 'status', $newVersionStatus );
                $version->store( array( 'status' ) );
            }

            // when translation does not have object name set then we copy object name from the current object version
            $translations = $version->translations( false );
            if ( !$translations )
                continue;
            foreach ( $translations as $translation )
            {
                if ( ! $contentObject->name( $versionNum, $translation ) )
                {
                    eZDebug::writeNotice( "Setting name '$objectName' for version ($versionNum) of the content object ($objectID) in language($translation)" );
                    $contentObject->setName( $objectName, $versionNum, $translation );
                }
            }
        }

        foreach ( $versionList[$versionListActiveVersion]['node_list'] as $nodeInfo )
        {
            unset( $parentNode );
            $parentNode = eZContentObjectTreeNode::fetchNode( $contentObject->attribute( 'id' ),
                                                               $nodeInfo['parent_node'] );
            if ( is_object( $parentNode ) )
            {
                $parentNode->setAttribute( 'priority', $nodeInfo['priority'] );
                $parentNode->store( array( 'priority' ) );
            }
        }

        $db->commit();

        return $contentObject;
    }
예제 #14
0
 /**
  * Returns the content class to use when creating the content object from
  * the file
  *
  * @param array $mimeData
  * @return eZContentClass
  * @throw RuntimeException if the found class identifier does not exists
  * @throw DomainException if objects of the found class are not allowed
  */
 public function getContentClass(array $mimeData)
 {
     $upload = new eZContentUpload();
     $classIdentifier = $upload->detectClassIdentifier($mimeData['name']);
     $class = eZContentClass::fetchByIdentifier($classIdentifier);
     if (!$class instanceof eZContentClass) {
         throw new RuntimeException(ezpI18n::tr('extension/ezjscore/ajaxuploader', 'Unable to load the class which identifier is "%class",' . ' this is probably a configuration issue in upload.ini.', null, array('%class' => $classIdentifier)));
     }
     $classContent = $this->attribute->attribute('class_content');
     if (!empty($classContent['class_constraint_list']) && !in_array($classIdentifier, $classContent['class_constraint_list'])) {
         throw new DomainException(ezpI18n::tr('extension/ezjscore/ajaxuploader', 'The file cannot be processed because' . ' it would result in a \'%class\' object and this relation' . ' does not accept this type of object.', null, array('%class' => $class->attribute('name'))));
     }
     return $class;
 }
예제 #15
0
}
if ($http->hasPostVariable('NewButton') || $module->isCurrentAction('NewObjectAddNodeAssignment')) {
    $hasClassInformation = false;
    $contentClassID = false;
    $contentClassIdentifier = false;
    $languageCode = false;
    $class = false;
    if ($http->hasPostVariable('ClassID')) {
        $contentClassID = $http->postVariable('ClassID');
        if ($contentClassID) {
            $hasClassInformation = true;
        }
    } else {
        if ($http->hasPostVariable('ClassIdentifier')) {
            $contentClassIdentifier = $http->postVariable('ClassIdentifier');
            $class = eZContentClass::fetchByIdentifier($contentClassIdentifier);
            if (is_object($class)) {
                $contentClassID = $class->attribute('id');
                if ($contentClassID) {
                    $hasClassInformation = true;
                }
            }
        }
    }
    if ($http->hasPostVariable('ContentLanguageCode')) {
        $languageCode = $http->postVariable('ContentLanguageCode');
        $languageID = eZContentLanguage::idByLocale($languageCode);
        if ($languageID === false) {
            eZDebug::writeError("The language code [{$languageCode}] specified in ContentLanguageCode does not exist in the system.");
            return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
        }
 /**
 * 
 * Récupère l'id numérique correspondant à un identifiant de classe
 * @param $classIdentifier : un identifiant de classe 
 * @return l'ID numérique de la classe (0 si la classe n'existe pas)
 *
 */
 public static function getClassID( $classIdentifier )
 {
     $classID = 0;
     $class = is_numeric( $classIdentifier ) ? 
     eZContentClass::fetch( $classIdentifier ) : 
     eZContentClass::fetchByIdentifier( $classIdentifier );
     if ( ! empty( $class ) )
     {
         $classID = (int)$class->ID;
     }
     return $classID;
 }
 public static function checkAccess($access, $contentObject, $contentClassID, $parentContentClassID, $languageCode = false)
 {
     if ($contentObject instanceof eZContentObjectTreeNode) {
         $contentObject = $contentObject->attribute('object');
     }
     if ($contentClassID !== false and !is_numeric($contentClassID)) {
         $class = eZContentClass::fetchByIdentifier($contentClassID);
         if (!$class) {
             return array('error' => array('error_type' => 'kernel', 'error_code' => eZError::KERNEL_NOT_FOUND));
         }
         $contentClassID = $class->attribute('id');
     }
     if ($access and $contentObject instanceof eZContentObject) {
         $result = $contentObject->checkAccess($access, $contentClassID, $parentContentClassID, false, $languageCode);
         return array('result' => $result);
     }
 }
    function createContentObject( $objectInformation )
    {
        $db = eZDB::instance();
        $contentObjectVersion = false;
        if ( $objectInformation['ownerID'] )
        {
            $userID = $objectInformation['ownerID'];
        }
        else
        {
            $user = eZUser::currentUser();
            $userID = $user->attribute( 'contentobject_id' );
        }
        if ( $objectInformation['remoteID'] )
        {
            $contentObject = eZContentObject::fetchByRemoteId( $objectInformation['remoteID'] );
            if (  $contentObject )
            {
                $this->writeMessage( "\t[".$objectInformation['remoteID']."] Object exists: " . $contentObject->attribute("name") . ". Creating new version.", 'notice' );
                $contentObjectVersion = $contentObject->createNewVersion();
            }
        }
        elseif ( $objectInformation['objectID'] )
        {
            $contentObject = eZContentObject::fetch( $objectInformation['objectID'] );
            if (  $contentObject )
            {
                $this->writeMessage( "\t[".$objectInformation['remoteID']."] Object exists: " . $contentObject->attribute("name") . ". Creating new version.", 'notice' );
                $contentObjectVersion = $contentObject->createNewVersion();
            }
        }

        if ( !$contentObjectVersion )
        {
            if ( is_numeric( $objectInformation['classID'] ) )
            {
                $contentClass = eZContentClass::fetch( $objectInformation['classID'] );
            }
            elseif ( is_string( $objectInformation['classID'] ) && $objectInformation['classID'] != "" )
            {
                $contentClass = eZContentClass::fetchByIdentifier( $objectInformation['classID'] );
            }
            else
            {
                $this->writeMessage( "\tNo class defined. Using class article.", 'warning' );
                $contentClass = eZContentClass::fetchByIdentifier( 'article' );
            }
            if ( !$contentClass )
            {
                $this->writeMessage( "\tCannot instantiate class '". $objectInformation['classID'] ."'." , 'error' );
                return false;
            }
            $contentObject = $contentClass->instantiate( $userID );
            $contentObject->setAttribute( 'remote_id',  $objectInformation['remoteID'] );
            if ( $contentObject )
            {
                $contentObjectVersion = $contentObject->currentVersion();
            }
        }
        if ( $contentObjectVersion )
        {
            $db->begin();
            $versionNumber  = $contentObjectVersion->attribute( 'version' );

            $sortField = intval( eZContentObjectTreeNode::sortFieldID( $objectInformation['sort_field'] ) );
            $sortOrder = strtolower( $objectInformation['sort_order'] ) == 'desc' ? eZContentObjectTreeNode::SORT_ORDER_DESC : eZContentObjectTreeNode::SORT_ORDER_ASC;

            $nodeAssignment = eZNodeAssignment::create(
                    array(  'contentobject_id'      => $contentObject->attribute( 'id' ),
                            'contentobject_version' => $versionNumber,
                            'parent_node'           => $objectInformation['parentNode'],
                            'is_main'               => 1,
                            'sort_field'			=> $sortField,
                            'sort_order'			=> $sortOrder,
                            )
            );
            $nodeAssignment->store();
            $dataMap = $contentObjectVersion->dataMap();
            foreach ( $objectInformation['attributes'] as $attributeName => $attributesContent )
            {
                if ( array_key_exists( $attributeName, $dataMap ) )
                {
                    $attribute = $dataMap[$attributeName];
                    $classAttributeID = $attribute->attribute( 'contentclassattribute_id' );
                    $dataType = $attribute->attribute( 'data_type_string' );
                    switch ( $dataType )
                    {
                        case 'ezstring':
                        case 'eztext':
                        case 'ezselection':
                        case 'ezemail':
                        {
                            if ( array_key_exists( 'parseReferences', $attributesContent ) && $attributesContent['parseReferences'] == "true" )
                            {
                                $attribute->setAttribute( 'data_text', $this->parseAndReplaceStringReferences( $attributesContent['content'] ) );
                            }
                            else
                            {
                                $attribute->setAttribute( 'data_text', $attributesContent['content'] );
                            }
                        } break;

                        case 'ezboolean':
                        case 'ezinteger':
                        {
                            $attribute->setAttribute( 'data_int', (int)$attributesContent['content'] );
                        } break;

                        case 'ezxmltext':
                        {
                            if ( array_key_exists( 'parseReferences', $attributesContent ) && $attributesContent['parseReferences'] == "true" )
                            {
                                $attributesContent['content'] = $this->parseAndReplaceStringReferences( $attributesContent['content'] );
                            }
                            if ( array_key_exists( 'htmlDecode', $attributesContent ) && $attributesContent['htmlDecode'] == "true" )
                            {
                                $content = html_entity_decode( $attributesContent['content'] );
                            }
                            else
                            {
                                $content = $attributesContent['content'];
                            }

                            if( array_key_exists( 'fullxml', $attributesContent ) && $attributesContent['fullxml'] == "true" )
                            {
                                $xml = $content;
                            }
                            else
                            {
                                $xml = '<?xml version="1.0" encoding="utf-8"?>'."\n".
                                        '<section xmlns:image="http://ez.no/namespaces/ezpublish3/image/"'."\n".
                                        '         xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/"'."\n".
                                        '         xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/">'."\n".
                                        '  <section>'."\n";
                                $xml .= '    <paragraph>' . $content . "</paragraph>\n";
                                $xml .= "  </section>\n</section>\n";
                            }

                            $attribute->setAttribute( 'data_text', $xml );
                        } break;

                        case 'ezprice':
                        case 'ezfloat':
                        {
                            $attribute->setAttribute( 'data_float', (float)$attributesContent['content'] );
                        } break;
                        case 'ezimage':
                        {
                            $imagePath = $this->setting( 'data_source' ) . '/' . $attributesContent['src'];
                            $imageName = $attributesContent['title'];
                            $path = realpath( $imagePath );
                            if ( file_exists( $path ) )
                            {
                                $content = $attribute->content();
                                $content->initializeFromFile( $path, $imageName, basename( $attributesContent['src'] ) );
                                $content->store( $attribute );
                            }
                            else
                            {
                                $this->writeMessage( "\tFile " . $path . " not found.", 'warning' );
                            }
                        } break;
                        case 'ezobjectrelation':
                        {
                            $relationContent = trim( $attributesContent['content'] );
                            if ( $relationContent != '' )
                            {
                                $objectID = $this->getReferenceID( $attributesContent['content'] );
                                if ( $objectID )
                                {
                                    $attribute->setAttribute( 'data_int', $objectID );
                                    eZContentObject::fetch( $objectID )->addContentObjectRelation( $objectID, $versionNumber, $contentObject->attribute( 'id' ), $attribute->attribute( 'contentclassattribute_id' ),    eZContentObject::RELATION_ATTRIBUTE );
                                }
                                else
                                {
                                    $this->writeMessage( "\tReference " . $attributesContent['content'] . " not set.", 'warning' );
                                }
                            }
                        } break;
                        case 'ezurl':
                        {
                            $url = '';
                            $title = '';
                            if (  array_key_exists( 'url', $attributesContent ) )
                                $url   = $attributesContent['url'];
                            if (  array_key_exists( 'title', $attributesContent ) )
                                $title   = $attributesContent['title'];

                            if ( array_key_exists( 'parseReferences', $attributesContent ) && $attributesContent['parseReferences'] == "true" )
                            {
                                $title = $this->parseAndReplaceStringReferences( $title );
                                $url   = $this->parseAndReplaceStringReferences( $url );
                            }

                            $attribute->setAttribute( 'data_text', $title );
                            $attribute->setContent( $url );
                        } break;
                        case 'ezuser':
                        {
                            $login    = '';
                            $email    = '';
                            $password = '';
                            if (  array_key_exists( 'login', $attributesContent ) )
                                $login    = $attributesContent['login'];
                            if (  array_key_exists( 'email', $attributesContent ) )
                                $email    = $attributesContent['email'];
                            if (  array_key_exists( 'password', $attributesContent ) )
                                $password = $attributesContent['password'];

                            $contentObjectID = $attribute->attribute( "contentobject_id" );

                            $user =& $attribute->content();
                            if ( $user === null )
                            {
                                $user = eZUser::create( $contentObjectID );
                            }

                            $ini =& eZINI::instance();
                            $generatePasswordIfEmpty = $ini->variable( "UserSettings", "GeneratePasswordIfEmpty" );
                            if (  $password == "" )
                            {
                                if ( $generatePasswordIfEmpty == 'true' )
                                {
                                    $passwordLength = $ini->variable( "UserSettings", "GeneratePasswordLength" );
                                    $password = $user->createPassword( $passwordLength );
                                }
                                else
                                {
                                    $password = null;
                                }
                            }

                            if ( $password == "_ezpassword" )
                            {
                                $password = false;
                                $passwordConfirm = false;
                            }

                            $user->setInformation( $contentObjectID, $login, $email, $password, $password );
                            $attribute->setContent( $user );
                        } break;
                        case 'ezkeyword':
                        {
                            $keyword = new eZKeyword();
                            $keyword->initializeKeyword( $attributesContent['content'] );
                            $attribute->setContent( $keyword );
                        } break;
                        case 'ezmatrix':
                        {
                            if ( is_array( $attributesContent ) )
                            {
                                $matrix = $attribute->attribute( 'content' );
                                $cells = array();
                                $matrix->Matrix['rows']['sequential'] = array();
                                $matrix->NumRows = 0;
                                foreach( $attributesContent as $key => $value )
                                {
                                    $cells = array_merge( $cells, $value );
                                    $newRow['columns'] = $value;
                                    $newRow['identifier'] =  'row_' . ( $matrix->NumRows + 1 );
                                    $newRow['name'] = 'Row_' . ( $matrix->NumRows + 1 );
                                    $matrix->NumRows++;
                                    $matrix->Matrix['rows']['sequential'][] = $newRow;
                                }
                                $matrix->Cells = $cells;
                                $attribute->setAttribute( 'data_text', $matrix->xmlString() );
                                $matrix->decodeXML( $attribute->attribute( 'data_text' ) );
                                $attribute->setContent( $matrix );
                            }
                        } break;

                        case 'ezobjectrelationlist':
                        {
                            $relationContent = explode( ',', $attributesContent['content'] );
                            if ( count( $relationContent ) )
                            {
                                $objectIDs = array();
                                foreach( $relationContent as $relation )
                                {
                                    $objectIDs[] = $this->getReferenceID( trim ( $relation ) );
                                }
                                $attribute->fromString( implode( '-', $objectIDs ) );
                            }
                            else
                            {
                                eZDebug::writeWarning( $attributesContent['content'], "No relation declared" );
                            }
                        } break;


                        case 'ezauthor':
                        case 'ezbinaryfile':
                        case 'ezcountry':
                        case 'ezdate':
                        case 'ezdatetime':
                        case 'ezenum':
                        case 'ezidentifier':
                        case 'ezinisetting':
                        case 'ezisbn':
                        case 'ezmedia':
                        case 'ezmultioption':
                        case 'ezmultiprice':
                        case 'ezoption':
                        case 'ezpackage':
                        case 'ezproductcategory':
                        case 'ezrangeoption':
                        case 'ezsubtreesubscription':
                        case 'eztime':
                        default:
                        {
                            try
                            {
                                $attribute->fromString($attributesContent['content']);
                            }
                            catch ( Exception $e )
                            {
                                $this->writeMessage( "\tDatatype " . $dataType . " fromString function rejected value " . $attributesContent['content'], 'warning' );
                            }
                        } break;

                    }
                    $attribute->store();
                }
            }
            if ( isset($objectInformation['sectionID']) && $objectInformation['sectionID'] != '' && $objectInformation['sectionID'] != 0 )
            {
                $contentObject->setAttribute( 'section_id',  $objectInformation['sectionID'] );
            }

            if ( isset($objectInformation['creatorID']) && $objectInformation['creatorID'] != '' && $objectInformation['creatorID'] != 0 )
            {
                $contentObjectVersion->setAttribute( 'creator_id',  $objectInformation['creatorID'] );
            }

            if ( isset($objectInformation['ownerID']) && $objectInformation['ownerID'] != '' && $objectInformation['ownerID'] != 0 )
            {
                $contentObject->setAttribute( 'owner_id',  $objectInformation['ownerID'] );
            }

            if( isset( $objectInformation['relations'] ) && is_array( $objectInformation['relations'] ) )
            {
                foreach( $objectInformation['relations'] as $toObjectID )
                {
                    $contentObject->addContentObjectRelation( $toObjectID );
                }
            }

            $contentObjectVersion->store();
            $contentObject->store();
            $db->commit();

            eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $contentObject->attribute( 'id' ), 'version'   => $versionNumber ) );

            $newNodeArray = eZContentObjectTreeNode::fetchByContentObjectID( $contentObject->attribute( 'id' ) );
            $refArray = false;
            if ( $newNodeArray && count($newNodeArray) >= 1 )
            {
                $newNode = $newNodeArray[0];
                if ( $newNode )
                {
                    $refArray = array( "node_id"   => $newNode->attribute( 'node_id' ),
                                       "name"      => $contentObjectVersion->attribute( 'name' ),
                                       "object_id" => $contentObject->attribute( 'id' ) );

                    if( $objectInformation['priority'] )
                    {
                        $this->updateNodePriority( $refArray['node_id'], $objectInformation['priority'] );
                    }
                }
            }
            unset($contentObjectVersion);
            unset($contentObject);
            return $refArray;
        }
    return false;
    }
예제 #19
0
<?php

$Module = $Params['Module'];
$tpl = eZTemplate::factory();
$newsletter_ini = eZINI::instance('jaj_newsletter.ini');
$newsletter_root_node_id = $newsletter_ini->variable('NewsletterSettings', 'RootFolderNodeId');
$node = eZContentObject::fetchByNodeID($newsletter_root_node_id);
if (!$node || !$node->canRead()) {
    return $Module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
}
switch (eZPreferences::value('admin_jaj_newsletter_newsletters_limit')) {
    case '25':
        $limit = 25;
        break;
    case '50':
        $limit = 50;
        break;
    default:
        $limit = 10;
        break;
}
$newsletter_content_class = eZContentClass::fetchByIdentifier('jaj_newsletter');
if ($newsletter_content_class) {
    $tpl->setVariable('newsletter_content_class_id', $newsletter_content_class->ID);
}
$viewParameters = array('offset' => $Params['Offset']);
$tpl->setVariable('node', $node);
$tpl->setVariable('set_limit', $limit);
$tpl->setVariable('view_parameters', $viewParameters);
$Result = array('content' => $tpl->fetch('design:jaj_newsletter/newsletters/index.tpl'), 'path' => array(array('url' => 'jaj_newsletter/index', 'text' => ezpI18n::tr('jaj_newsletter/navigation', 'Newsletter')), array('url' => false, 'text' => ezpI18n::tr('jaj_newsletter/navigation', 'Newsletters'))));
예제 #20
0
 /**
  * Content creation
  * <code>
  * $options = new SQLIContentOptions( array( 'class_identifier'     => 'article',
  *                                           'remote_id'            => 'myremoteid',
  *                                           'language'             => 'fre-FR' ) );
  * $article = SQLIContent::create( $options );
  * $article->fields->title = 'My Title';
  * $article->fields->body = '<tag>myxmlcontent</tag>';
  * </code>
  * @param SQLIContentOptions $options See {@link SQLIContentOptions::__set()} to see available options.
  *                                    Mandatory parameters are :
  *                                      - class_identifier
  */
 public static function create(SQLIContentOptions $options)
 {
     if (!isset($options['class_identifier'])) {
         throw new SQLIContentException('Cannot create content without "class_identifier" option');
     }
     $creatorID = $options['creator_id'];
     $sectionID = $options['section_id'];
     $lang = $options['language'];
     $contentObject = null;
     // If remote ID is set, first try to fetch content object from it
     if (isset($options['remote_id'])) {
         $contentObject = eZContentObject::fetchByRemoteID($options['remote_id']);
     }
     if (!$contentObject instanceof eZContentObject) {
         $db = eZDB::instance();
         $db->begin();
         $contentClass = eZContentClass::fetchByIdentifier($options['class_identifier']);
         $contentObject = $contentClass->instantiate($creatorID, $sectionID, false, $lang);
         if (isset($options['remote_id'])) {
             $contentObject->setAttribute('remote_id', $options['remote_id']);
             $contentObject->store();
         }
         $db->commit();
     }
     $content = self::fromContentObject($contentObject);
     if ($lang) {
         $content->setActiveLanguage($lang);
     }
     return $content;
 }
예제 #21
0
                $node = eZContentObjectTreeNode::fetch($nodeID );
                if (!$node) {
                    continue;
                }
                if ($node->canRemove()) {
                    $node->removeNodeFromTree($moveToTrash);
                    $removeCount++;
                }
            }
            $tpl->setVariable('remove_count', $removeCount);
        }
    }
}
$path = array(array('url' => 'classlists/list', 'text' => ezpI18n::tr('classlists/list', 'Lists by content class')));
if ($classIdentifier != '') {
    $classObject = eZContentClass::fetchByIdentifier($classIdentifier);
    if (is_object($classObject)) {
        $page_uri = trim($Module->redirectionURI('classlists', 'list', array($classIdentifier, $sortMethod, $sortOrder)), '/');
        $path[] = array('url' => $page_uri, 'text' => ezpI18n::tr('classlists/list', '%classname objects', false, array('%classname' => $classObject->attribute('name'))));
        $tpl->setVariable('class_identifier', $classIdentifier);
        $tpl->setVariable('page_uri', $page_uri);
    } else {
        $page_uri = trim($Module->redirectionURI('classlists', 'list', array('', $sortMethod, $sortOrder)), '/');
        $tpl->setVariable('page_uri', $page_uri);
        $tpl->setVariable('class_identifier', false);
        $tpl->setVariable('error', ezpI18n::tr('classlists/list', '%class_identifier is not a valid content class identifier.', false, array('%class_identifier' => $classIdentifier)));
    }
} else {
    $tpl->setVariable('page_uri', 'classlists/list//' . $sortMethod . '/' . $sortOrder);
    $tpl->setVariable('class_identifier', false);
}
예제 #22
0
 function createSubNode($node, $name)
 {
     $namedChildrenArray = $node->childrenByName($name);
     $subNode = false;
     //pk
     if (!$node->canCreate()) {
         $this->setError(self::ERROR_ACCESSDENIED, ezpI18n::tr('extension/ezodf/import/error', "Folder for images could not be created, access denied."));
         return false;
     }
     if (empty($namedChildrenArray)) {
         $class = eZContentClass::fetchByIdentifier("folder");
         $creatorID = $this->currentUserID;
         //$creatorID = 14; // 14 == admin
         $parentNodeID = $placeNodeID;
         $contentObject = $class->instantiate($creatorID, 1);
         $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $node->attribute('node_id'), 'is_main' => 1));
         $nodeAssignment->store();
         $version = $contentObject->version(1);
         $version->setAttribute('modified', eZDateTime::currentTimeStamp());
         $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
         $version->store();
         $contentObjectID = $contentObject->attribute('id');
         $dataMap = $contentObject->dataMap();
         $titleAttribudeIdentifier = 'name';
         $dataMap[$titleAttribudeIdentifier]->setAttribute('data_text', $name);
         $dataMap[$titleAttribudeIdentifier]->store();
         $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1));
         $subNode = $contentObject->mainNode();
     } else {
         if (count($namedChildrenArray) == 1) {
             $subNode = $namedChildrenArray[0];
         }
     }
     return $subNode;
 }
 protected function __construct($classIdentifier)
 {
     $this->contentClass = eZContentClass::fetchByIdentifier($classIdentifier);
     if (!$this->contentClass instanceof eZContentClass) {
         throw new Exception("Class {$classIdentifier} not found");
     }
 }
예제 #24
0
 /**
  * Returns a valid limitation value to be saved in database
  *
  * @since 1.2.0
  * @param string $limitationType	Limitation type
  * @param string $limitationValue	Human readable input value
  * @return string	Value to be saved in database
  */
 private function getLimitationValue($limitationType, $limitationValue)
 {
     $limitationValue = $this->getReferenceID($limitationValue);
     switch ($limitationType) {
         case 'Class':
         case 'ParentClass':
             if (!is_int($limitationValue)) {
                 $class = eZContentClass::fetchByIdentifier($limitationValue);
                 if ($class) {
                     $limitationValue = $class->ID;
                 }
             }
             break;
         case 'Subtree':
             //Subtree limitations need to store path_string instead of node_id
             $val = (int) $limitationValue;
             if ($val > 0) {
                 $node = eZContentObjectTreeNode::fetch($val);
                 $limitationValue = $node->attribute('path_string');
             }
             break;
         case 'SiteAccess':
             //siteaccess name must be crc32'd
             if (!is_int($limitationValue)) {
                 $limitationValue = eZSys::ezcrc32($limitationValue);
             }
             break;
         case 'Section':
             if (!is_int($limitationValue)) {
                 $section = eZSection::fetchByIdentifier($limitationValue);
                 if ($section) {
                     $limitationValue = $section->attribute('id');
                 }
             }
             break;
     }
     return $limitationValue;
 }
 function initializePackage($siteType, &$accessMap, $charset, &$extraLanguageCodes, &$allLanguages, &$primaryLanguage, &$admin, &$resultArray)
 {
     // Time limit #3:
     // We set the time limit to 5 minutes to ensure we have enough time
     // to initialize the site. However we only set if the current limit
     // is too small
     $maxTime = ini_get('max_execution_time');
     if ($maxTime != 0 and $maxTime < 5 * 60) {
         @set_time_limit(5 * 60);
     }
     switch ($siteType['access_type']) {
         case 'port':
             $userSiteaccessName = $siteType['identifier'] . '_' . 'user';
             $adminSiteaccessName = $siteType['identifier'] . '_' . 'admin';
             $accessMap['port'][$siteType['access_type_value']] = $userSiteaccessName;
             $accessMap['port'][$siteType['admin_access_type_value']] = $adminSiteaccessName;
             break;
         case 'hostname':
             $userSiteaccessName = $siteType['identifier'] . '_' . 'user';
             $adminSiteaccessName = $siteType['identifier'] . '_' . 'admin';
             $accessMap['hostname'][$siteType['access_type_value']] = $userSiteaccessName;
             $accessMap['hostname'][$siteType['admin_access_type_value']] = $adminSiteaccessName;
             break;
         case 'url':
         default:
             $userSiteaccessName = $siteType['access_type_value'];
             $adminSiteaccessName = $siteType['admin_access_type_value'];
             $accessMap['url'][$siteType['access_type_value']] = $userSiteaccessName;
             $accessMap['url'][$siteType['admin_access_type_value']] = $adminSiteaccessName;
             break;
     }
     $accessMap['accesses'][] = $userSiteaccessName;
     $accessMap['accesses'][] = $adminSiteaccessName;
     $accessMap['sites'][] = $userSiteaccessName;
     $userDesignName = $siteType['identifier'];
     $languageObjects = $allLanguages;
     $databaseMap = eZSetupDatabaseMap();
     $databaseInfo = $this->PersistenceList['database_info'];
     $databaseInfo['info'] = $databaseMap[$databaseInfo['type']];
     $dbServer = $databaseInfo['server'];
     $dbPort = $databaseInfo['port'];
     //        $dbName = $databaseInfo['dbname'];
     $dbSocket = $databaseInfo['socket'];
     $dbUser = $databaseInfo['user'];
     $dbPwd = $databaseInfo['password'];
     $dbCharset = $charset;
     $dbDriver = $databaseInfo['info']['driver'];
     $dbName = $siteType['database'];
     $dbParameters = array('server' => $dbServer, 'port' => $dbPort, 'user' => $dbUser, 'password' => $dbPwd, 'socket' => $dbSocket, 'database' => $dbName, 'charset' => $dbCharset);
     $db = eZDB::instance($dbDriver, $dbParameters, true);
     if (!$db->isConnected()) {
         $resultArray['errors'][] = array('code' => 'EZSW-005', 'text' => "Failed connecting to database {$dbName}\n" . $db->errorMessage());
         return false;
     }
     eZDB::setInstance($db);
     $result = true;
     // Initialize the database by inserting schema and data
     if (!isset($siteType['existing_database'])) {
         $siteType['existing_database'] = false;
     }
     if ($siteType['existing_database'] == eZStepInstaller::DB_DATA_REMOVE) {
         eZDBTool::cleanup($db);
     }
     if ($siteType['existing_database'] != eZStepInstaller::DB_DATA_KEEP) {
         $result = true;
         $schemaArray = eZDbSchema::read('share/db_schema.dba', true);
         if (!$schemaArray) {
             $resultArray['errors'][] = array('code' => 'EZSW-001', 'message' => "Failed loading database schema file share/db_schema.dba");
             $result = false;
         }
         if ($result) {
             $result = true;
             $dataArray = eZDbSchema::read('share/db_data.dba', true);
             if (!$dataArray) {
                 $resultArray['errors'][] = array('code' => 'EZSW-002', 'text' => "Failed loading database data file share/db_data.dba");
                 $result = false;
             }
             if ($result) {
                 $schemaArray = array_merge($schemaArray, $dataArray);
                 $schemaArray['type'] = strtolower($db->databaseName());
                 $schemaArray['instance'] = $db;
                 $result = true;
                 $dbSchema = eZDbSchema::instance($schemaArray);
                 if (!$dbSchema) {
                     $resultArray['errors'][] = array('code' => 'EZSW-003', 'text' => "Failed loading " . $db->databaseName() . " schema handler");
                     $result = false;
                 }
                 if ($result) {
                     $result = true;
                     // This will insert the schema, then the data and
                     // run any sequence value correction SQL if required
                     $params = array('schema' => true, 'data' => true);
                     if ($db->databaseName() == 'mysql') {
                         $engines = $db->arrayQuery('SHOW ENGINES');
                         foreach ($engines as $engine) {
                             if ($engine['Engine'] == 'InnoDB' && in_array($engine['Support'], array('YES', 'DEFAULT'))) {
                                 $params['table_type'] = 'innodb';
                                 break;
                             }
                         }
                     }
                     if (!$dbSchema->insertSchema($params)) {
                         $resultArray['errors'][] = array('code' => 'EZSW-004', 'text' => "Failed inserting data to " . $db->databaseName() . "\n" . $db->errorMessage());
                         $result = false;
                     }
                 }
             }
         }
         if ($result) {
             // Inserting data from the dba-data files of the datatypes
             eZDataType::loadAndRegisterAllTypes();
             $registeredDataTypes = eZDataType::registeredDataTypes();
             foreach ($registeredDataTypes as $dataType) {
                 if (!$dataType->importDBDataFromDBAFile()) {
                     $resultArray['errors'][] = array('code' => 'EZSW-002', 'text' => "Failed importing datatype related data into database: \n" . 'datatype - ' . $dataType->DataTypeString . ", \n" . 'dba-data file - ' . $dataType->getDBAFilePath());
                 }
             }
         }
     }
     if (!$result) {
         return false;
     }
     // Database initialization done
     // Prepare languages
     $primaryLanguageLocaleCode = $primaryLanguage->localeCode();
     $primaryLanguageName = $primaryLanguage->languageName();
     $prioritizedLanguages = array_merge(array($primaryLanguageLocaleCode), $extraLanguageCodes);
     $installParameters = array('path' => '.');
     $installParameters['ini'] = array();
     $siteINIChanges = array();
     $url = $siteType['url'];
     if (preg_match("#^[a-zA-Z0-9]+://(.*)\$#", $url, $matches)) {
         $url = $matches[1];
     }
     $siteINIChanges['SiteAccessSettings'] = array('RelatedSiteAccessList' => $accessMap['accesses']);
     $siteINIChanges['ContentSettings'] = array('TranslationList' => implode(';', $extraLanguageCodes));
     $siteINIChanges['SiteSettings'] = array('SiteName' => $siteType['title'], 'SiteURL' => $url);
     $siteINIChanges['DatabaseSettings'] = array('DatabaseImplementation' => $dbDriver, 'Server' => $dbServer, 'Port' => $dbPort, 'Database' => $dbName, 'User' => $dbUser, 'Password' => $dbPwd, 'Charset' => false);
     $siteINIChanges['FileSettings'] = array('VarDir' => 'var/' . $siteType['identifier']);
     if (trim($dbSocket) != '') {
         $siteINIChanges['DatabaseSettings']['Socket'] = $dbSocket;
     } else {
         $siteINIChanges['DatabaseSettings']['Socket'] = 'disabled';
     }
     if ($admin['email']) {
         $siteINIChanges['InformationCollectionSettings'] = array('EmailReceiver' => false);
         $siteINIChanges['UserSettings'] = array('RegistrationEmail' => false);
         $siteINIChanges['MailSettings'] = array('AdminEmail' => $admin['email'], 'EmailSender' => false);
     }
     $siteINIChanges['RegionalSettings'] = array('Locale' => $primaryLanguage->localeFullCode(), 'ContentObjectLocale' => $primaryLanguage->localeCode(), 'SiteLanguageList' => $prioritizedLanguages);
     if ($primaryLanguage->localeCode() == 'eng-GB') {
         $siteINIChanges['RegionalSettings']['TextTranslation'] = 'disabled';
     } else {
         $siteINIChanges['RegionalSettings']['TextTranslation'] = 'enabled';
     }
     $installParameters['ini']['siteaccess'][$adminSiteaccessName]['site.ini.append'] = $siteINIChanges;
     $installParameters['ini']['siteaccess'][$userSiteaccessName]['site.ini.append'] = $siteINIChanges;
     $installParameters['ini']['siteaccess'][$userSiteaccessName]['site.ini']['DesignSettings'] = array('SiteDesign' => $userDesignName);
     $installParameters['variables']['user_siteaccess'] = $userSiteaccessName;
     $installParameters['variables']['admin_siteaccess'] = $adminSiteaccessName;
     $installParameters['variables']['design'] = $userDesignName;
     $tmpSiteINI = eZINI::create('site.ini');
     // Set ReadOnlySettingsCheck to false: towards
     // Ignore site.ini[eZINISettings].ReadonlySettingList[] settings when saving ini variables.
     $tmpSiteINI->setReadOnlySettingsCheck(false);
     $tmpSiteINI->setVariable('FileSettings', 'VarDir', $siteINIChanges['FileSettings']['VarDir']);
     // Change the current translation variables, before other parts start using them
     $tmpSiteINI->setVariable('RegionalSettings', 'Locale', $siteINIChanges['RegionalSettings']['Locale']);
     $tmpSiteINI->setVariable('RegionalSettings', 'ContentObjectLocale', $siteINIChanges['RegionalSettings']['ContentObjectLocale']);
     $tmpSiteINI->setVariable('RegionalSettings', 'TextTranslation', $siteINIChanges['RegionalSettings']['TextTranslation']);
     $tmpSiteINI->save(false, '.append.php', false, true, "settings/siteaccess/{$userSiteaccessName}");
     /*
     $typeFunctionality = eZSetupFunctionality( $siteType['identifier'] );
     $extraFunctionality = array_merge( isset( $this->PersistenceList['additional_packages'] ) ?
                                        $this->PersistenceList['additional_packages'] :
                                        array(),
                                        $typeFunctionality['required'] );
     $extraFunctionality = array_unique( $extraFunctionality );
     */
     // Add a policy to permit editors using OE
     eZPolicy::createNew(3, array('ModuleName' => 'ezoe', 'FunctionName' => '*'));
     // Install site package and it's required packages
     $sitePackageName = $this->chosenSitePackage();
     $sitePackage = eZPackage::fetch($sitePackageName);
     if (!is_object($sitePackage)) {
         $resultArray['errors'][] = array('code' => 'EZSW-041', 'text' => " Could not fetch site package: '{$sitePackageName}'");
         return false;
     }
     $dependecies = $sitePackage->attribute('dependencies');
     $requires = $dependecies['requires'];
     $requiredPackages = array();
     // Include setting files
     $settingsFiles = $sitePackage->attribute('settings-files');
     foreach ($settingsFiles as $settingsFileName) {
         if (file_exists($sitePackage->path() . '/settings/' . $settingsFileName)) {
             include_once $sitePackage->path() . '/settings/' . $settingsFileName;
         }
     }
     // Call user function for additional setup tasks.
     if (function_exists('eZSitePreInstall')) {
         eZSitePreInstall($siteType);
     }
     // Make sure objects use the selected main language instead of eng-GB
     if ($primaryLanguageLocaleCode != 'eng-GB') {
         $engLanguageObj = eZContentLanguage::fetchByLocale('eng-GB');
         $engLanguageID = (int) $engLanguageObj->attribute('id');
         $updateSql = "UPDATE ezcontent_language\nSET\nlocale='{$primaryLanguageLocaleCode}',\nname='{$primaryLanguageName}'\nWHERE\nid={$engLanguageID}";
         $db->query($updateSql);
         eZContentLanguage::expireCache();
         $primaryLanguageObj = eZContentLanguage::fetchByLocale($primaryLanguageLocaleCode);
         // Add it if it is missing (most likely)
         if (!$primaryLanguageObj) {
             $primaryLanguageObj = eZContentLanguage::addLanguage($primaryLanguageLocaleCode, $primaryLanguageName);
         }
         $primaryLanguageID = (int) $primaryLanguageObj->attribute('id');
         // Find objects which are always available
         if ($db->databaseName() == 'oracle') {
             $sql = "SELECT id\nFROM\nezcontentobject\nWHERE\nbitand( language_mask, 1 ) = 1";
         } else {
             $sql = "SELECT id\nFROM\nezcontentobject\nWHERE\nlanguage_mask & 1 = 1";
         }
         $objectList = array();
         $list = $db->arrayQuery($sql);
         foreach ($list as $row) {
             $objectList[] = (int) $row['id'];
         }
         $inSql = 'IN ( ' . implode(', ', $objectList) . ')';
         // Updates databases that have eng-GB data to the new locale.
         $updateSql = "UPDATE ezcontentobject_name\nSET\ncontent_translation='{$primaryLanguageLocaleCode}',\nreal_translation='{$primaryLanguageLocaleCode}',\nlanguage_id={$primaryLanguageID}\nWHERE\ncontent_translation='eng-GB' OR\nreal_translation='eng-GB'";
         $db->query($updateSql);
         // Fix always available
         $updateSql = "UPDATE ezcontentobject_name\nSET\nlanguage_id=language_id+1\nWHERE\ncontentobject_id {$inSql}";
         $db->query($updateSql);
         // attributes
         $updateSql = "UPDATE ezcontentobject_attribute\nSET\nlanguage_code='{$primaryLanguageLocaleCode}',\nlanguage_id={$primaryLanguageID}\nWHERE\nlanguage_code='eng-GB'";
         $db->query($updateSql);
         // Fix always available
         $updateSql = "UPDATE ezcontentobject_attribute\nSET\nlanguage_id=language_id+1\nWHERE\ncontentobject_id {$inSql}";
         $db->query($updateSql);
         // version
         $updateSql = "UPDATE ezcontentobject_version\nSET\ninitial_language_id={$primaryLanguageID},\nlanguage_mask={$primaryLanguageID}\nWHERE\ninitial_language_id={$engLanguageID}";
         $db->query($updateSql);
         // Fix always available
         $updateSql = "UPDATE ezcontentobject_version\nSET\nlanguage_mask=language_mask+1\nWHERE\ncontentobject_id {$inSql}";
         $db->query($updateSql);
         // object
         $updateSql = "UPDATE ezcontentobject\nSET\ninitial_language_id={$primaryLanguageID},\nlanguage_mask={$primaryLanguageID}\nWHERE\ninitial_language_id={$engLanguageID}";
         $db->query($updateSql);
         // Fix always available
         $updateSql = "UPDATE ezcontentobject\nSET\nlanguage_mask=language_mask+1\nWHERE\nid {$inSql}";
         $db->query($updateSql);
         // content object state groups & states
         $mask = $primaryLanguageID | 1;
         $db->query("UPDATE ezcobj_state_group\n                         SET language_mask = {$mask}, default_language_id = {$primaryLanguageID}\n                         WHERE default_language_id = {$engLanguageID}");
         $db->query("UPDATE ezcobj_state\n                         SET language_mask = {$mask}, default_language_id = {$primaryLanguageID}\n                         WHERE default_language_id = {$engLanguageID}");
         $db->query("UPDATE ezcobj_state_group_language\n                         SET language_id = {$primaryLanguageID}\n                         WHERE language_id = {$engLanguageID}");
         $db->query("UPDATE ezcobj_state_language\n                         SET language_id = {$primaryLanguageID}\n                         WHERE language_id = {$engLanguageID}");
         // ezcontentclass_name
         $updateSql = "UPDATE ezcontentclass_name\nSET\nlanguage_locale='{$primaryLanguageLocaleCode}'\nWHERE\nlanguage_locale='eng-GB'";
         $db->query($updateSql);
         // use high-level api, because it's impossible to update serialized names with direct sqls.
         // use direct access to 'NameList' to avoid unnecessary sql-requests and because
         // we do 'replacement' of existing language(with some 'id') with another language code.
         $contentClassList = eZContentClass::fetchList();
         foreach ($contentClassList as $contentClass) {
             $classAttributes = $contentClass->fetchAttributes();
             foreach ($classAttributes as $classAttribute) {
                 $classAttribute->NameList->setName($classAttribute->NameList->name('eng-GB'), $primaryLanguageLocaleCode);
                 $classAttribute->NameList->setAlwaysAvailableLanguage($primaryLanguageLocaleCode);
                 $classAttribute->NameList->removeName('eng-GB');
                 $classAttribute->store();
             }
             $contentClass->NameList->setName($contentClass->NameList->name('eng-GB'), $primaryLanguageLocaleCode);
             $contentClass->NameList->setAlwaysAvailableLanguage($primaryLanguageLocaleCode);
             $contentClass->NameList->removeName('eng-GB');
             $contentClass->NameList->setHasDirtyData(false);
             // to not update 'ezcontentclass_name', because we've already updated it.
             $contentClass->store();
         }
     }
     // Setup all languages
     foreach ($allLanguages as $languageObject) {
         $primaryLanguageObj = eZContentLanguage::fetchByLocale($languageObject->localeCode());
         // Add it if it is missing (most likely)
         if (!$primaryLanguageObj) {
             $primaryLanguageObj = eZContentLanguage::addLanguage($languageObject->localeCode(), $languageObject->internationalLanguageName());
         }
     }
     eZContentLanguage::expireCache();
     // Make sure priority list is changed to the new chosen languages
     eZContentLanguage::setPrioritizedLanguages($prioritizedLanguages);
     if ($siteType['existing_database'] != eZStepInstaller::DB_DATA_KEEP) {
         $user = eZUser::instance(14);
         // Must be initialized to make node assignments work correctly
         if (!is_object($user)) {
             $resultArray['errors'][] = array('code' => 'EZSW-020', 'text' => "Could not fetch administrator user object");
             return false;
         }
         // Make sure Admin is the currently logged in user
         // This makes sure all new/changed objects get this as creator
         $user->loginCurrent();
         // by default(if 'language_map' is not set) create all necessary languages
         $languageMap = isset($this->PersistenceList['package_info']) && isset($this->PersistenceList['package_info']['language_map']) ? $this->PersistenceList['package_info']['language_map'] : true;
         if (is_array($languageMap) && count($languageMap) > 0) {
             //
             // Create necessary languages and set them as "prioritized languages" to avoid
             // drawbacks in fetch functions, like eZContentObjectTreeNode::fetch().
             //
             $prioritizedLanguageObjects = eZContentLanguage::prioritizedLanguages();
             // returned objects
             foreach ($languageMap as $fromLanguage => $toLanguage) {
                 if ($toLanguage != 'skip') {
                     $prioritizedLanguageObjects[] = eZContentLanguage::fetchByLocale($toLanguage, true);
                 }
             }
             $prioritizedLanguageLocales = array();
             foreach ($prioritizedLanguageObjects as $language) {
                 $locale = $language->attribute('locale');
                 if (!in_array($locale, $prioritizedLanguageLocales)) {
                     $prioritizedLanguageLocales[] = $locale;
                 }
             }
             eZContentLanguage::setPrioritizedLanguages($prioritizedLanguageLocales);
         }
         foreach ($requires as $require) {
             if ($require['type'] != 'ezpackage') {
                 continue;
             }
             $packageName = $require['name'];
             $package = eZPackage::fetch($packageName, false, false, false);
             if (is_object($package)) {
                 $requiredPackages[] = $package;
                 if ($package->attribute('install_type') == 'install') {
                     $installParameters = array('use_dates_from_package' => true, 'site_access_map' => array('*' => $userSiteaccessName), 'top_nodes_map' => array('*' => 2), 'design_map' => array('*' => $userDesignName), 'language_map' => $languageMap, 'restore_dates' => true, 'user_id' => $user->attribute('contentobject_id'), 'non-interactive' => true);
                     $status = $package->install($installParameters);
                     if (!$status) {
                         $errorText = "Unable to install package '{$packageName}'";
                         if (isset($installParameters['error']['description'])) {
                             $errorText .= ": " . $installParameters['error']['description'];
                         }
                         $resultArray['errors'][] = array('code' => 'EZSW-051', 'text' => $errorText);
                         return false;
                     }
                 }
             } else {
                 $resultArray['errors'][] = array('code' => 'EZSW-050', 'text' => "Could not fetch required package: '{$packageName}'");
                 return false;
             }
             unset($package);
         }
     }
     $GLOBALS['eZContentObjectDefaultLanguage'] = $primaryLanguageLocaleCode;
     $nodeRemoteMap = array();
     $rows = $db->arrayQuery("SELECT node_id, remote_id FROM ezcontentobject_tree");
     foreach ($rows as $row) {
         $remoteID = $row['remote_id'];
         if (strlen(trim($remoteID)) > 0) {
             $nodeRemoteMap[$remoteID] = $row['node_id'];
         }
     }
     $objectRemoteMap = array();
     $rows = $db->arrayQuery("SELECT id, remote_id FROM ezcontentobject");
     foreach ($rows as $row) {
         $remoteID = $row['remote_id'];
         if (strlen(trim($remoteID)) > 0) {
             $objectRemoteMap[$remoteID] = $row['id'];
         }
     }
     $classRemoteMap = array();
     $rows = $db->arrayQuery("SELECT id, identifier, remote_id FROM ezcontentclass");
     foreach ($rows as $row) {
         $remoteID = $row['remote_id'];
         if (strlen(trim($remoteID)) > 0) {
             $classRemoteMap[$remoteID] = array('id' => $row['id'], 'identifier' => $row['identifier']);
         }
     }
     $siteCSS = false;
     $classesCSS = false;
     foreach ($requiredPackages as $package) {
         if ($package->attribute('type') == 'sitestyle') {
             $fileList = $package->fileList('default');
             foreach ($fileList as $file) {
                 $fileIdentifier = $file["variable-name"];
                 if ($fileIdentifier == 'sitecssfile') {
                     $siteCSS = $package->fileItemPath($file, 'default');
                 } else {
                     if ($fileIdentifier == 'classescssfile') {
                         $classesCSS = $package->fileItemPath($file, 'default');
                     }
                 }
             }
         }
     }
     $parameters = array('node_remote_map' => $nodeRemoteMap, 'object_remote_map' => $objectRemoteMap, 'class_remote_map' => $classRemoteMap, 'preview_design' => $userDesignName, 'design_list' => array($userDesignName, 'admin2', 'admin'), 'user_siteaccess' => $userSiteaccessName, 'admin_siteaccess' => $adminSiteaccessName, 'package_object' => $sitePackage, 'siteaccess_urls' => $this->siteaccessURLs(), 'access_map' => $accessMap, 'site_type' => $siteType, 'all_language_codes' => $prioritizedLanguages);
     $siteINIStored = false;
     $siteINIAdminStored = false;
     $designINIStored = false;
     if (function_exists('eZSiteINISettings')) {
         $extraSettings = eZSiteINISettings($parameters);
     } else {
         $extraSettings = array();
     }
     if (function_exists('eZSiteAdminINISettings')) {
         $extraAdminSettings = eZSiteAdminINISettings($parameters);
     } else {
         $extraAdminSettings = array();
     }
     if (function_exists('eZSiteCommonINISettings')) {
         $extraCommonSettings = eZSiteCommonINISettings($parameters);
     } else {
         $extraCommonSettings = array();
     }
     $isUntranslatedSettingAdded = false;
     foreach ($extraAdminSettings as $key => $extraAdminSetting) {
         if ($extraAdminSetting['name'] == 'site.ini') {
             $extraAdminSettings[$key]['settings']['RegionalSettings']['ShowUntranslatedObjects'] = 'enabled';
             $isUntranslatedSettingAdded = true;
             break;
         }
     }
     if (!$isUntranslatedSettingAdded) {
         $extraAdminSettings[] = array('name' => 'site.ini', 'settings' => array('RegionalSettings' => array('ShowUntranslatedObjects' => 'enabled')));
     }
     // Enable OE and ODF extensions by default
     $extensionsToEnable = array();
     // Included in "fat" install, needs to override $extraCommonSettings extensions
     $extensionsPrepended = array('ezjscore', 'ezoe', 'ezformtoken');
     foreach (array('ezie', 'ezodf', 'ezprestapiprovider', 'ezmultiupload', 'eztags', 'ezautosave', 'ez_network', 'ez_network_demo') as $extension) {
         if (file_exists("extension/{$extension}")) {
             $extensionsToEnable[] = $extension;
         }
     }
     $settingAdded = false;
     foreach ($extraCommonSettings as $key => $extraCommonSetting) {
         if ($extraCommonSetting['name'] == 'site.ini' && isset($extraCommonSettings[$key]['settings']['ExtensionSettings']['ActiveExtensions'])) {
             $settingAdded = true;
             $extraCommonSettings[$key]['settings']['ExtensionSettings']['ActiveExtensions'] = array_merge($extensionsPrepended, $extraCommonSettings[$key]['settings']['ExtensionSettings']['ActiveExtensions'], $extensionsToEnable);
             break;
         }
     }
     if (!$settingAdded) {
         $extraCommonSettings[] = array('name' => 'site.ini', 'settings' => array('ExtensionSettings' => array('ActiveExtensions' => array_merge($extensionsPrepended, $extensionsToEnable))));
     }
     // Enable dynamic tree menu for the admin interface by default
     $enableDynamicTreeMenuAdded = false;
     foreach ($extraAdminSettings as $key => $extraSetting) {
         if ($extraSetting['name'] == 'contentstructuremenu.ini') {
             if (isset($extraSetting['settings']['TreeMenu'])) {
                 $extraAdminSettings[$key]['settings']['TreeMenu']['Dynamic'] = 'enabled';
             } else {
                 $extraAdminSettings[$key]['settings'] = array('TreeMenu' => array('Dynamic' => 'enabled'));
             }
             $enableDynamicTreeMenuAdded = true;
             break;
         }
     }
     if (!$enableDynamicTreeMenuAdded) {
         $extraAdminSettings[] = array('name' => 'contentstructuremenu.ini', 'settings' => array('TreeMenu' => array('Dynamic' => 'enabled')));
     }
     $resultArray['common_settings'] = $extraCommonSettings;
     foreach ($extraSettings as $extraSetting) {
         if ($extraSetting === false) {
             continue;
         }
         $iniName = $extraSetting['name'];
         $settings = $extraSetting['settings'];
         $resetArray = false;
         if (isset($extraSetting['reset_arrays'])) {
             $resetArray = $extraSetting['reset_arrays'];
         }
         $tmpINI = eZINI::create($iniName);
         // Set ReadOnlySettingsCheck to false: towards
         // Ignore site.ini[eZINISettings].ReadonlySettingList[] settings when saving ini variables.
         $tmpINI->setReadOnlySettingsCheck(false);
         $tmpINI->setVariables($settings);
         if ($iniName == 'site.ini') {
             $siteINIStored = true;
             $tmpINI->setVariables($siteINIChanges);
             $tmpINI->setVariable('DesignSettings', 'SiteDesign', $userDesignName);
             $tmpINI->setVariable('DesignSettings', 'AdditionalSiteDesignList', array('base'));
         } else {
             if ($iniName == 'design.ini') {
                 if ($siteCSS) {
                     $tmpINI->setVariable('StylesheetSettings', 'SiteCSS', $siteCSS);
                 }
                 if ($classesCSS) {
                     $tmpINI->setVariable('StylesheetSettings', 'ClassesCSS', $classesCSS);
                 }
                 $designINIStored = true;
             }
         }
         $tmpINI->save(false, '.append.php', false, true, "settings/siteaccess/{$userSiteaccessName}", $resetArray);
         if ($siteType['existing_database'] != eZStepInstaller::DB_DATA_KEEP) {
             // setting up appropriate data in look&feel object
             $templateLookClass = eZContentClass::fetchByIdentifier('template_look', true);
             if ($templateLookClass) {
                 $objectList = $templateLookClass->objectList();
                 if ($objectList and count($objectList) > 0) {
                     $templateLookObject = current($objectList);
                     $dataMap = $templateLookObject->fetchDataMap();
                     if (isset($dataMap['title'])) {
                         $dataMap['title']->setAttribute('data_text', $siteINIChanges['SiteSettings']['SiteName']);
                         $dataMap['title']->store();
                     }
                     if (isset($dataMap['siteurl'])) {
                         $dataMap['siteurl']->setAttribute('data_text', $siteINIChanges['SiteSettings']['SiteURL']);
                         $dataMap['siteurl']->store();
                     }
                     if (isset($dataMap['email'])) {
                         $dataMap['email']->setAttribute('data_text', $siteINIChanges['MailSettings']['AdminEmail']);
                         $dataMap['email']->store();
                     }
                     $objectName = $templateLookClass->contentObjectName($templateLookObject);
                     $templateLookObject->setName($objectName);
                     $templateLookObject->store();
                 }
             }
         }
     }
     foreach ($extraAdminSettings as $extraSetting) {
         if ($extraSetting === false) {
             continue;
         }
         $iniName = $extraSetting['name'];
         $settings = $extraSetting['settings'];
         $resetArray = false;
         if (isset($extraSetting['reset_arrays'])) {
             $resetArray = $extraSetting['reset_arrays'];
         }
         $tmpINI = eZINI::create($iniName);
         $tmpINI->setVariables($settings);
         if ($iniName == 'site.ini') {
             $siteINIAdminStored = true;
             $tmpINI->setVariables($siteINIChanges);
             $tmpINI->setVariable('SiteAccessSettings', 'RequireUserLogin', 'true');
             $tmpINI->setVariable('DesignSettings', 'SiteDesign', 'admin2');
             $tmpINI->setVariable('DesignSettings', 'AdditionalSiteDesignList', array('admin'));
             $tmpINI->setVariable('SiteSettings', 'LoginPage', 'custom');
             $tmpINI->setVariable('SiteSettings', 'DefaultPage', 'content/dashboard');
         }
         $tmpINI->save(false, '.append.php', false, true, "settings/siteaccess/{$adminSiteaccessName}", $resetArray);
     }
     if (!$siteINIAdminStored) {
         $siteINI = eZINI::create('site.ini');
         // Set ReadOnlySettingsCheck to false: towards
         // Ignore site.ini[eZINISettings].ReadonlySettingList[] settings when saving ini variables.
         $siteINI->setReadOnlySettingsCheck(false);
         $siteINI->setVariables($siteINIChanges);
         $siteINI->setVariable('SiteAccessSettings', 'RequireUserLogin', 'true');
         $siteINI->setVariable('DesignSettings', 'SiteDesign', 'admin2');
         $tmpINI->setVariable('DesignSettings', 'AdditionalSiteDesignList', array('admin'));
         $siteINI->setVariable('SiteSettings', 'LoginPage', 'custom');
         $siteINI->setVariable('SiteSettings', 'DefaultPage', 'content/dashboard');
         $siteINI->save(false, '.append.php', false, false, "settings/siteaccess/{$adminSiteaccessName}", true);
     }
     if (!$siteINIStored) {
         $siteINI = eZINI::create('site.ini');
         // Set ReadOnlySettingsCheck to false: towards
         // Ignore site.ini[eZINISettings].ReadonlySettingList[] settings when saving ini variables.
         $siteINI->setReadOnlySettingsCheck(false);
         $siteINI->setVariables($siteINIChanges);
         $siteINI->setVariable('DesignSettings', 'SiteDesign', $userDesignName);
         $siteINI->setVariable('DesignSettings', 'AdditionalSiteDesignList', array('base'));
         $siteINI->save(false, '.append.php', false, true, "settings/siteaccess/{$userSiteaccessName}", true);
     }
     if (!$designINIStored) {
         $designINI = eZINI::create('design.ini');
         // Set ReadOnlySettingsCheck to false: towards
         // Ignore site.ini[eZINISettings].ReadonlySettingList[] settings when saving ini variables.
         $designINI->setReadOnlySettingsCheck(false);
         if ($siteCSS) {
             $designINI->setVariable('StylesheetSettings', 'SiteCSS', $siteCSS);
         }
         if ($classesCSS) {
             $designINI->setVariable('StylesheetSettings', 'ClassesCSS', $classesCSS);
         }
         $designINI->save(false, '.append.php', false, true, "settings/siteaccess/{$userSiteaccessName}");
     }
     eZDir::mkdir("design/" . $userDesignName);
     eZDir::mkdir("design/" . $userDesignName . "/templates");
     eZDir::mkdir("design/" . $userDesignName . "/stylesheets");
     eZDir::mkdir("design/" . $userDesignName . "/images");
     eZDir::mkdir("design/" . $userDesignName . "/override");
     eZDir::mkdir("design/" . $userDesignName . "/override/templates");
     if ($siteType['existing_database'] == eZStepInstaller::DB_DATA_KEEP) {
         return true;
     }
     // Try and remove user/login without limitation from the anonymous user
     $anonRole = eZRole::fetchByName('Anonymous');
     if (is_object($anonRole)) {
         $anonPolicies = $anonRole->policyList();
         foreach ($anonPolicies as $anonPolicy) {
             if ($anonPolicy->attribute('module_name') == 'user' and $anonPolicy->attribute('function_name') == 'login') {
                 $anonPolicy->removeThis();
                 break;
             }
         }
     }
     // Setup all roles according to site chosen and addons
     if (function_exists('eZSiteRoles')) {
         $extraRoles = eZSiteRoles($parameters);
         foreach ($extraRoles as $extraRole) {
             if (!$extraRole) {
                 continue;
             }
             $extraRoleName = $extraRole['name'];
             $role = eZRole::fetchByName($extraRoleName);
             if (!is_object($role)) {
                 $role = eZRole::create($extraRoleName);
                 $role->store();
             }
             $roleID = $role->attribute('id');
             if (isset($extraRole['policies'])) {
                 $extraPolicies = $extraRole['policies'];
                 foreach ($extraPolicies as $extraPolicy) {
                     if (isset($extraPolicy['limitation'])) {
                         $role->appendPolicy($extraPolicy['module'], $extraPolicy['function'], $extraPolicy['limitation']);
                     } else {
                         $role->appendPolicy($extraPolicy['module'], $extraPolicy['function']);
                     }
                 }
             }
             if (isset($extraRole['assignments'])) {
                 $roleAssignments = $extraRole['assignments'];
                 foreach ($roleAssignments as $roleAssignment) {
                     $assignmentIdentifier = false;
                     $assignmentValue = false;
                     if (isset($roleAssignment['limitation'])) {
                         $assignmentIdentifier = $roleAssignment['limitation']['identifier'];
                         $assignmentValue = $roleAssignment['limitation']['value'];
                     }
                     $role->assignToUser($roleAssignment['user_id'], $assignmentIdentifier, $assignmentValue);
                 }
             }
         }
     }
     // Setup user preferences based on the site chosen and addons
     if (function_exists('eZSitePreferences')) {
         $prefs = eZSitePreferences($parameters);
         foreach ($prefs as $prefEntry) {
             if (!$prefEntry) {
                 continue;
             }
             $prefUserID = $prefEntry['user_id'];
             foreach ($prefEntry['preferences'] as $pref) {
                 $prefName = $pref['name'];
                 $prefValue = $pref['value'];
                 if (!eZPreferences::setValue($prefName, $prefValue, $prefUserID)) {
                     $resultArray['errors'][] = array('code' => 'EZSW-070', 'text' => "Could not create ezpreference '{$prefValue}' for {$prefUserID}");
                     return false;
                 }
             }
         }
     }
     $publishAdmin = false;
     $userAccount = eZUser::fetch(14);
     if (!is_object($userAccount)) {
         $resultArray['errors'][] = array('code' => 'EZSW-020', 'text' => "Could not fetch administrator user object");
         return false;
     }
     $userObject = $userAccount->attribute('contentobject');
     if (!is_object($userObject)) {
         $resultArray['errors'][] = array('code' => 'EZSW-021', 'text' => "Could not fetch administrator content object");
         return false;
     }
     $newUserObject = $userObject->createNewVersion(false, false);
     if (!is_object($newUserObject)) {
         $resultArray['errors'][] = array('code' => 'EZSW-022', 'text' => "Could not create new version of administrator content object");
         return false;
     }
     $dataMap = $newUserObject->attribute('data_map');
     $error = false;
     if (trim($admin['email'])) {
         if (!isset($dataMap['user_account'])) {
             $resultArray['errors'][] = array('code' => 'EZSW-023', 'text' => "Administrator content object does not have a 'user_account' attribute");
             return false;
         }
         $userAccount->setInformation(14, 'admin', $admin['email'], $admin['password'], $admin['password']);
         $dataMap['user_account']->setContent($userAccount);
         $dataMap['user_account']->store();
         $publishAdmin = true;
         $userAccount->store();
     }
     if (trim($admin['first_name']) or trim($admin['last_name'])) {
         if (!isset($dataMap['first_name'])) {
             $resultArray['errors'][] = array('code' => 'EZSW-023', 'text' => "Administrator content object does not have a 'first_name' field");
             $error = true;
         }
         if (!isset($dataMap['last_name'])) {
             $resultArray['errors'][] = array('code' => 'EZSW-024', 'text' => "Administrator content object does not have a 'last_name' field");
             $error = true;
         }
         if ($error) {
             return false;
         }
         $dataMap['first_name']->setAttribute('data_text', $admin['first_name']);
         $dataMap['first_name']->store();
         $dataMap['last_name']->setAttribute('data_text', $admin['last_name']);
         $dataMap['last_name']->store();
         $newUserObject->store();
         $publishAdmin = true;
     }
     if ($publishAdmin) {
         $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $newUserObject->attribute('contentobject_id'), 'version' => $newUserObject->attribute('version')));
         if ($operationResult['status'] != eZModuleOperationInfo::STATUS_CONTINUE) {
             $resultArray['errors'][] = array('code' => 'EZSW-025', 'text' => "Failed to properly publish the administrator object");
             return false;
         }
     }
     // Call user function for additional setup tasks.
     if (function_exists('eZSitePostInstall')) {
         eZSitePostInstall($parameters);
     }
     // get all siteaccesses. do it via 'RelatedSiteAccessesList' settings.
     $adminSiteINI = eZINI::instance('site.ini' . '.append.php', "settings/siteaccess/{$adminSiteaccessName}");
     $relatedSiteAccessList = $adminSiteINI->variable('SiteAccessSettings', 'RelatedSiteAccessList');
     // Adding override for 'tiny_image' view for 'multi-option2' datatype
     foreach ($relatedSiteAccessList as $siteAccess) {
         $tmpOverrideINI = new eZINI('override.ini' . '.append.php', "settings/siteaccess/{$siteAccess}", null, null, null, true, true);
         $tmpOverrideINI->setVariable('tiny_image', 'Source', 'content/view/tiny.tpl');
         $tmpOverrideINI->setVariable('tiny_image', 'MatchFile', 'tiny_image.tpl');
         $tmpOverrideINI->setVariable('tiny_image', 'Subdir', 'templates');
         $tmpOverrideINI->setVariable('tiny_image', 'Match', array('class_identifier' => 'image'));
         $tmpOverrideINI->save();
     }
     $accessMap = $parameters['access_map'];
     // Call user function for some text which will be displayed at 'Finish' screen
     if (function_exists('eZSiteFinalText')) {
         $text = eZSiteFinalText($parameters);
         if (!isset($this->PersistenceList['final_text'])) {
             $this->PersistenceList['final_text'] = array();
         }
         $this->PersistenceList['final_text'][] = $text;
     }
     // ensure that evaluated policy wildcards in the user info cache
     // will be up to date with the currently activated modules
     eZCache::clearByID('user_info_cache');
     return true;
 }
예제 #26
0
 /**
  * Fetches the uploaded file, figures out its MIME-type and creates the
  * proper content object out of it.
  *
  * @param array $result
  *        Result data, will be filled with information which the client can
  *        examine, contains: errors An array with errors, each element is
  *        an array with a 'description' entry containing the text
  * @param string $httpFileIdentifier
  *        The HTTP identifier of the uploaded file, this must match the
  *        name of the input tag.
  * @param mixed $location
  *        The node ID which the new object will be placed or the string
  *        'auto' for automatic placement of type.
  * @param eZContentObjectTreeNode|false $existingNode
  *        Pass a contentobjecttreenode object to let the uploading be done
  *        to an existing object, if not it will create one from scratch.
  * @param string $nameString
  *        The name of the new object/new version
  * @param string|false $localeCode
  *        Locale code (eg eng-GB, fre-FR, ...) to use when creating the
  *        object or the version.
  * @param boolean $publish whether to publish the new created content object
  *
  * @return boolean
  */
 function handleUpload(&$result, $httpFileIdentifier, $location, $existingNode, $nameString = '', $localeCode = false, $publish = true)
 {
     $result = array('errors' => array(), 'notices' => array(), 'result' => false, 'redirect_url' => false);
     $this->fetchHTTPFile($httpFileIdentifier, $result['errors'], $file, $mimeData);
     if (!$file) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'No HTTP file found, cannot fetch uploaded file.'));
         return false;
     }
     $mime = $mimeData['name'];
     if ($mime == '') {
         $mime = $file->attribute("mime_type");
     }
     $handler = $this->findHandler($result, $mimeData);
     if ($handler === false) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'There was an error trying to instantiate content upload handler.'));
         return false;
     }
     // If this is an object we have a special handler for the file
     // The handler will be responsible for the rest of the execution.
     if (is_object($handler)) {
         $filePath = $file->attribute("filename");
         $originalFilename = $file->attribute("original_filename");
         $handlerResult = $handler->handleFile($this, $result, $filePath, $originalFilename, $mimeData, $location, $existingNode);
         if (is_object($result['contentobject'])) {
             return $handlerResult;
         }
     }
     $object = false;
     $class = false;
     // Figure out class identifier from an existing node
     // if not we will have to detect it from the mimetype
     if (is_object($existingNode)) {
         $object = $existingNode->object();
         $class = $object->contentClass();
         $classIdentifier = $class->attribute('identifier');
     } else {
         $classIdentifier = $this->detectClassIdentifier($mime);
     }
     if (!$classIdentifier) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'No matching class identifier found.'));
         return false;
     }
     if (!is_object($class)) {
         $class = eZContentClass::fetchByIdentifier($classIdentifier);
     }
     if (!$class) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'The class %class_identifier does not exist.', null, array('%class_identifier' => $classIdentifier)));
         return false;
     }
     $parentNodes = false;
     $parentMainNode = false;
     // If do not have an existing node we need to figure
     // out the locations from $location and $classIdentifier
     if (!is_object($existingNode)) {
         $locationOK = $this->detectLocations($classIdentifier, $class, $location, $parentNodes, $parentMainNode);
         if ($locationOK === false) {
             $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'Was not able to figure out placement of object.'));
             return false;
         } elseif ($locationOK === null) {
             $result['status'] = eZContentUpload::STATUS_PERMISSION_DENIED;
             $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'Permission denied'));
             return false;
         }
     }
     $uploadINI = eZINI::instance('upload.ini');
     $iniGroup = $classIdentifier . '_ClassSettings';
     if (!$uploadINI->hasGroup($iniGroup)) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'No configuration group in upload.ini for class identifier %class_identifier.', null, array('%class_identifier' => $classIdentifier)));
         return false;
     }
     $fileAttribute = $uploadINI->variable($iniGroup, 'FileAttribute');
     $dataMap = $class->dataMap();
     if ($classIdentifier == 'image') {
         $classAttribute = $dataMap['image'];
         $maxSize = 1024 * 1024 * $classAttribute->attribute('data_int1');
         if ($maxSize != 0 && $file->attribute('filesize') > $maxSize) {
             $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'The size of the uploaded file exceeds the limit set for this site: %1 bytes.', null, array($maxSize)));
             return false;
         }
     }
     $fileAttribute = $this->findHTTPFileAttribute($dataMap, $fileAttribute);
     if (!$fileAttribute) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'No matching file attribute found, cannot create content object without this.'));
         return false;
     }
     $nameAttribute = $uploadINI->variable($iniGroup, 'NameAttribute');
     if (!$nameAttribute) {
         $nameAttribute = $this->findStringAttribute($dataMap, $nameAttribute);
     }
     if (!$nameAttribute) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'No matching name attribute found, cannot create content object without this.'));
         return false;
     }
     $variables = array('original_filename' => $file->attribute('original_filename'), 'mime_type' => $mime);
     $variables['original_filename_base'] = $mimeData['basename'];
     $variables['original_filename_suffix'] = $mimeData['suffix'];
     if (!$nameString) {
         $namePattern = $uploadINI->variable($iniGroup, 'NamePattern');
         $nameString = $this->processNamePattern($variables, $namePattern);
     }
     $db = eZDB::instance();
     $db->begin();
     // If we have an existing node we need to create
     // a new version in it.
     // If we don't we have to make a new object
     if (is_object($existingNode)) {
         if ($existingNode->canEdit() != '1') {
             $result['status'] = eZContentUpload::STATUS_PERMISSION_DENIED;
             $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'Permission denied'));
             $db->commit();
             return false;
         }
         $version = $object->createNewVersion(false, true, $localeCode);
         unset($dataMap);
         $dataMap = $version->dataMap();
         $publishVersion = $version->attribute('version');
     } else {
         $object = $class->instantiateIn($localeCode);
         unset($dataMap);
         $dataMap = $object->dataMap();
         $publishVersion = $object->attribute('current_version');
     }
     unset($dataMap);
     $dataMap = $object->dataMap();
     if ($localeCode === false) {
         $localeCode = eZContentObject::defaultLanguage();
     }
     $status = $dataMap[$fileAttribute]->insertHTTPFile($object, $publishVersion, $localeCode, $file, $mimeData, $storeResult);
     if ($status === null) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'The attribute %class_identifier does not support HTTP file storage.', null, array('%class_identifier' => $classIdentifier)));
         $db->commit();
         return false;
     } else {
         if (!$status) {
             $result['errors'] = array_merge($result['errors'], $storeResult['errors']);
             $db->commit();
             return false;
         }
     }
     if ($storeResult['require_storage']) {
         $dataMap[$fileAttribute]->store();
     }
     $status = $dataMap[$nameAttribute]->insertSimpleString($object, $publishVersion, $localeCode, $nameString, $storeResult);
     if ($status === null) {
         $result['errors'][] = array('description' => ezpI18n::tr('kernel/content/upload', 'The attribute %class_identifier does not support simple string storage.', null, array('%class_identifier' => $classIdentifier)));
         $db->commit();
         return false;
     } else {
         if (!$status) {
             $result['errors'] = array_merge($result['errors'], $storeResult['errors']);
             $db->commit();
             return false;
         }
     }
     if ($storeResult['require_storage']) {
         $dataMap[$nameAttribute]->store();
     }
     if (is_array($parentNodes)) {
         foreach ($parentNodes as $key => $parentNode) {
             $object->createNodeAssignment($parentNode, $parentNode == $parentMainNode);
         }
     }
     $object->setName($class->contentObjectName($object));
     $object->store();
     if ($publish) {
         $tmpresult = $this->publishObject($result, $result['errors'], $result['notices'], $object, $publishVersion, $class, $parentNodes, $parentMainNode);
     } else {
         $tmpresult = $result;
         $tmpresult['contentobject'] = $object;
         $tmpresult['contentobject_id'] = $object->attribute('id');
         $tmpresult['contentobject_version'] = $publishVersion;
         $tmpresult['contentobject_main_node'] = false;
         $tmpresult['contentobject_main_node_id'] = false;
         $this->setResult(array('node_id' => 0, 'object_id' => $object->attribute('id'), 'object_version' => $publishVersion));
     }
     $db->commit();
     return $tmpresult;
 }
예제 #27
0
 /**
  * Get an array of class attribute identifiers based on either a class attribute
  * list, or a content classes list
  *
  * @param array $classIDArray
  *        Classes to search in. Either an array of class ID, class identifiers,
  *        a class ID or a class identifier.
  *        Using numerical attribute/class identifiers for $classIDArray is more efficient.
  * @param array $classAttributeID
  *        Class attributes to search in. Either an array of class attribute id,
  *        or a single class attribute. Literal identifiers are not allowed.
  * @param array $fieldTypeExcludeList
  *        filter list. List of field types to exclude. ( set to empty array by default ).
  *
  * @return array List of solr field names.
  */
 protected function getClassAttributes($classIDArray = false, $classAttributeIDArray = false, $fieldTypeExcludeList = null)
 {
     eZDebug::createAccumulator('Class attribute list', 'eZ Find');
     eZDebug::accumulatorStart('Class attribute list');
     $fieldArray = array();
     $classAttributeArray = array();
     // classAttributeIDArray = simple integer (content class attribute ID)
     if (is_numeric($classAttributeIDArray) and $classAttributeIDArray > 0) {
         $classAttributeArray[] = eZContentClassAttribute::fetch($classAttributeIDArray);
     } else {
         if (is_array($classAttributeIDArray)) {
             foreach ($classAttributeIDArray as $classAttributeID) {
                 $classAttributeArray[] = eZContentClassAttribute::fetch($classAttributeID);
             }
         }
     }
     // no class attribute list given, we need a class list
     // this block will create the class attribute array based on $classIDArray
     if (empty($classAttributeArray)) {
         // Fetch class list.
         $condArray = array("is_searchable" => 1, "version" => eZContentClass::VERSION_STATUS_DEFINED);
         if (!$classIDArray) {
             $classIDArray = array();
         } else {
             if (!is_array($classIDArray)) {
                 $classIDArray = array($classIDArray);
             }
         }
         // literal class identifiers are converted to numerical ones
         $tmpClassIDArray = $classIDArray;
         $classIDArray = array();
         foreach ($tmpClassIDArray as $key => $classIdentifier) {
             if (!is_numeric($classIdentifier)) {
                 if (!($contentClass = eZContentClass::fetchByIdentifier($classIdentifier, false))) {
                     eZDebug::writeWarning("Unknown content class identifier '{$classIdentifier}'", __METHOD__);
                 } else {
                     $classIDArray[] = $contentClass['id'];
                 }
             } else {
                 $classIDArray[] = $classIdentifier;
             }
         }
         if (!empty($classIDArray)) {
             $condArray['contentclass_id'] = array($classIDArray);
         }
         $classAttributeArray = eZContentClassAttribute::fetchFilteredList($condArray);
     }
     // $classAttributeArray now contains a list of eZContentClassAttribute
     // we can use to construct the list of fields solr should search in
     // @TODO : retrieve sub attributes here. Mind the types !
     foreach ($classAttributeArray as $classAttribute) {
         $fieldArray = array_merge(ezfSolrDocumentFieldBase::getFieldNameList($classAttribute, $fieldTypeExcludeList), $fieldArray);
     }
     // the array is unified + sorted in order to make it consistent
     $fieldArray = array_unique($fieldArray);
     sort($fieldArray);
     eZDebug::accumulatorStop('Class attribute list');
     return $fieldArray;
 }
예제 #28
0
    function classByIdentifier( $params )
    {
        $classIdentifier = $params['identifier'];

        $contentClass = eZContentClass::fetchByIdentifier( $classIdentifier );
        if( !is_object( $contentClass ) )
        {
            eZDebug::writeWarning( "Content class with identifier '$classIdentifier' doesn't exist.", __METHOD__ );
        }

        return $contentClass;
    }
예제 #29
0
 function install($package, $installType, $parameters, $name, $os, $filename, $subdirectory, $content, &$installParameters, &$installData)
 {
     $serializedNameListNode = $content->getElementsByTagName('serialized-name-list')->item(0);
     $serializedNameList = $serializedNameListNode ? $serializedNameListNode->textContent : false;
     $classNameList = new eZContentClassNameList($serializedNameList);
     if ($classNameList->isEmpty()) {
         $classNameList->initFromString($content->getElementsByTagName('name')->item(0)->textContent);
         // for backward compatibility( <= 3.8 )
     }
     $classNameList->validate();
     $serializedDescriptionListNode = $content->getElementsByTagName('serialized-description-list')->item(0);
     $serializedDescriptionList = $serializedDescriptionListNode ? $serializedDescriptionListNode->textContent : false;
     $classDescriptionList = new eZSerializedObjectNameList($serializedDescriptionList);
     $classIdentifier = $content->getElementsByTagName('identifier')->item(0)->textContent;
     $classRemoteID = $content->getElementsByTagName('remote-id')->item(0)->textContent;
     $classObjectNamePattern = $content->getElementsByTagName('object-name-pattern')->item(0)->textContent;
     $classURLAliasPattern = is_object($content->getElementsByTagName('url-alias-pattern')->item(0)) ? $content->getElementsByTagName('url-alias-pattern')->item(0)->textContent : null;
     $classIsContainer = $content->getAttribute('is-container');
     if ($classIsContainer !== false) {
         $classIsContainer = $classIsContainer == 'true' ? 1 : 0;
     }
     $classRemoteNode = $content->getElementsByTagName('remote')->item(0);
     $classID = $classRemoteNode->getElementsByTagName('id')->item(0)->textContent;
     $classGroupsNode = $classRemoteNode->getElementsByTagName('groups')->item(0);
     $classCreated = $classRemoteNode->getElementsByTagName('created')->item(0)->textContent;
     $classModified = $classRemoteNode->getElementsByTagName('modified')->item(0)->textContent;
     $classCreatorNode = $classRemoteNode->getElementsByTagName('creator')->item(0);
     $classModifierNode = $classRemoteNode->getElementsByTagName('modifier')->item(0);
     $classAttributesNode = $content->getElementsByTagName('attributes')->item(0);
     $dateTime = time();
     $classCreated = $dateTime;
     $classModified = $dateTime;
     $userID = false;
     if (isset($installParameters['user_id'])) {
         $userID = $installParameters['user_id'];
     }
     $class = eZContentClass::fetchByRemoteID($classRemoteID);
     if ($class) {
         $className = $class->name();
         $description = ezpI18n::tr('kernel/package', "Class '%classname' already exists.", false, array('%classname' => $className));
         $choosenAction = $this->errorChoosenAction(self::ERROR_EXISTS, $installParameters, $description, $this->HandlerType);
         switch ($choosenAction) {
             case eZPackage::NON_INTERACTIVE:
             case self::ACTION_REPLACE:
                 if (eZContentClassOperations::remove($class->attribute('id')) == false) {
                     eZDebug::writeWarning("Unable to remove class '{$className}'.");
                     return true;
                 }
                 eZDebug::writeNotice("Class '{$className}' will be replaced.", 'eZContentClassPackageHandler');
                 break;
             case self::ACTION_SKIP:
                 return true;
             case self::ACTION_NEW:
                 $class->setAttribute('remote_id', eZRemoteIdUtility::generate('class'));
                 $class->store();
                 $classNameList->appendGroupName(" (imported)");
                 break;
             default:
                 $installParameters['error'] = array('error_code' => self::ERROR_EXISTS, 'element_id' => $classRemoteID, 'description' => $description, 'actions' => array());
                 if ($class->isRemovable()) {
                     $errorMsg = ezpI18n::tr('kernel/package', "Replace existing class");
                     $objectsCount = eZContentObject::fetchSameClassListCount($class->attribute('id'));
                     if ($objectsCount) {
                         $errorMsg .= ' ' . ezpI18n::tr('kernel/package', "(Warning! {$objectsCount} content object(s) and their sub-items will be removed)");
                     }
                     $installParameters['error']['actions'][self::ACTION_REPLACE] = $errorMsg;
                 }
                 $installParameters['error']['actions'][self::ACTION_SKIP] = ezpI18n::tr('kernel/package', 'Skip installing this class');
                 $installParameters['error']['actions'][self::ACTION_NEW] = ezpI18n::tr('kernel/package', 'Keep existing and create a new one');
                 return false;
         }
     }
     unset($class);
     // Try to create a unique class identifier
     $currentClassIdentifier = $classIdentifier;
     $unique = false;
     while (!$unique) {
         $classList = eZContentClass::fetchByIdentifier($currentClassIdentifier);
         if ($classList) {
             // "increment" class identifier
             if (preg_match('/^(.*)_(\\d+)$/', $currentClassIdentifier, $matches)) {
                 $currentClassIdentifier = $matches[1] . '_' . ($matches[2] + 1);
             } else {
                 $currentClassIdentifier = $currentClassIdentifier . '_1';
             }
         } else {
             $unique = true;
         }
         unset($classList);
     }
     $classIdentifier = $currentClassIdentifier;
     $values = array('version' => 0, 'serialized_name_list' => $classNameList->serializeNames(), 'serialized_description_list' => $classDescriptionList->serializeNames(), 'create_lang_if_not_exist' => true, 'identifier' => $classIdentifier, 'remote_id' => $classRemoteID, 'contentobject_name' => $classObjectNamePattern, 'url_alias_name' => $classURLAliasPattern, 'is_container' => $classIsContainer, 'created' => $classCreated, 'modified' => $classModified);
     if ($content->hasAttribute('sort-field')) {
         $values['sort_field'] = eZContentObjectTreeNode::sortFieldID($content->getAttribute('sort-field'));
     } else {
         eZDebug::writeNotice('The sort field was not specified in the content class package. ' . 'This property is exported and imported since eZ Publish 4.0.2', __METHOD__);
     }
     if ($content->hasAttribute('sort-order')) {
         $values['sort_order'] = $content->getAttribute('sort-order');
     } else {
         eZDebug::writeNotice('The sort order was not specified in the content class package. ' . 'This property is exported and imported since eZ Publish 4.0.2', __METHOD__);
     }
     if ($content->hasAttribute('always-available')) {
         $values['always_available'] = $content->getAttribute('always-available') === 'true' ? 1 : 0;
     } else {
         eZDebug::writeNotice('The default object availability was not specified in the content class package. ' . 'This property is exported and imported since eZ Publish 4.0.2', __METHOD__);
     }
     // create class
     $class = eZContentClass::create($userID, $values);
     $class->store();
     $classID = $class->attribute('id');
     if (!isset($installData['classid_list'])) {
         $installData['classid_list'] = array();
     }
     if (!isset($installData['classid_map'])) {
         $installData['classid_map'] = array();
     }
     $installData['classid_list'][] = $class->attribute('id');
     $installData['classid_map'][$classID] = $class->attribute('id');
     // create class attributes
     $classAttributeList = $classAttributesNode->getElementsByTagName('attribute');
     foreach ($classAttributeList as $classAttributeNode) {
         $isNotSupported = strtolower($classAttributeNode->getAttribute('unsupported')) == 'true';
         if ($isNotSupported) {
             continue;
         }
         $attributeDatatype = $classAttributeNode->getAttribute('datatype');
         $attributeIsRequired = strtolower($classAttributeNode->getAttribute('required')) == 'true';
         $attributeIsSearchable = strtolower($classAttributeNode->getAttribute('searchable')) == 'true';
         $attributeIsInformationCollector = strtolower($classAttributeNode->getAttribute('information-collector')) == 'true';
         $attributeIsTranslatable = strtolower($classAttributeNode->getAttribute('translatable')) == 'true';
         $attributeSerializedNameListNode = $classAttributeNode->getElementsByTagName('serialized-name-list')->item(0);
         $attributeSerializedNameListContent = $attributeSerializedNameListNode ? $attributeSerializedNameListNode->textContent : false;
         $attributeSerializedNameList = new eZSerializedObjectNameList($attributeSerializedNameListContent);
         if ($attributeSerializedNameList->isEmpty()) {
             $attributeSerializedNameList->initFromString($classAttributeNode->getElementsByTagName('name')->item(0)->textContent);
         }
         // for backward compatibility( <= 3.8 )
         $attributeSerializedNameList->validate();
         $attributeSerializedDescriptionListNode = $classAttributeNode->getElementsByTagName('serialized-description-list')->item(0);
         $attributeSerializedDescriptionListContent = $attributeSerializedDescriptionListNode ? $attributeSerializedDescriptionListNode->textContent : false;
         $attributeSerializedDescriptionList = new eZSerializedObjectNameList($attributeSerializedDescriptionListContent);
         $attributeCategoryNode = $classAttributeNode->getElementsByTagName('category')->item(0);
         $attributeCategory = $attributeCategoryNode ? $attributeCategoryNode->textContent : '';
         $attributeSerializedDataTextNode = $classAttributeNode->getElementsByTagName('serialized-description-text')->item(0);
         $attributeSerializedDataTextContent = $attributeSerializedDataTextNode ? $attributeSerializedDataTextNode->textContent : false;
         $attributeSerializedDataText = new eZSerializedObjectNameList($attributeSerializedDataTextContent);
         $attributeIdentifier = $classAttributeNode->getElementsByTagName('identifier')->item(0)->textContent;
         $attributePlacement = $classAttributeNode->getElementsByTagName('placement')->item(0)->textContent;
         $attributeDatatypeParameterNode = $classAttributeNode->getElementsByTagName('datatype-parameters')->item(0);
         $classAttribute = $class->fetchAttributeByIdentifier($attributeIdentifier);
         if (!$classAttribute) {
             $classAttribute = eZContentClassAttribute::create($class->attribute('id'), $attributeDatatype, array('version' => 0, 'identifier' => $attributeIdentifier, 'serialized_name_list' => $attributeSerializedNameList->serializeNames(), 'serialized_description_list' => $attributeSerializedDescriptionList->serializeNames(), 'category' => $attributeCategory, 'serialized_data_text' => $attributeSerializedDataText->serializeNames(), 'is_required' => $attributeIsRequired, 'is_searchable' => $attributeIsSearchable, 'is_information_collector' => $attributeIsInformationCollector, 'can_translate' => $attributeIsTranslatable, 'placement' => $attributePlacement));
             $dataType = $classAttribute->dataType();
             $classAttribute->store();
             $dataType->unserializeContentClassAttribute($classAttribute, $classAttributeNode, $attributeDatatypeParameterNode);
             $classAttribute->sync();
         }
     }
     // add class to a class group
     $classGroupsList = $classGroupsNode->getElementsByTagName('group');
     foreach ($classGroupsList as $classGroupNode) {
         $classGroupName = $classGroupNode->getAttribute('name');
         $classGroup = eZContentClassGroup::fetchByName($classGroupName);
         if (!$classGroup) {
             $classGroup = eZContentClassGroup::create();
             $classGroup->setAttribute('name', $classGroupName);
             $classGroup->store();
         }
         $classGroup->appendClass($class);
     }
     return true;
 }
예제 #30
0
/**
 * Returns publisher folders related to given cluster
 * @param string $clusterIdentifier
 * @throws Exception
 * @return array:
 */
function fetchPublisherFoldersForCluster( $clusterIdentifier )
{
	$remoteID      = 'country_' . $clusterIdentifier;
	$clusterObject = eZContentObject::fetchByRemoteId($remoteID);

	if ( !$clusterObject instanceof eZContentObject )
		throw new Exception( 'No node found for cluster ' . $clusterIdentifier );

	$clusterNodeID = $clusterObject->mainNode()->attribute('node_id');
	$class         = eZContentClass::fetchByIdentifier( CLASS_IDENTIFIER_PUBLISHER_FOLDER );
	$attributeID   = (int) $class->fetchAttributeByIdentifier( ATTRIBUTE_TARGET_CONTENT_SERVICE )->ID;
	$limit         = 200;
	$offset        = 0;
	$result        = array();

	while ( true )
	{
		$params = array(
				'Depth' => 1,
				'AsObject' => true,
				'ClassFilterType' => 'include',
				'ClassFilterArray' => array(
						CLASS_IDENTIFIER_APPLICATION_FOLDER
				),
				'Limit' => $limit,
				'Offset' => $offset,
		);

		$fetchedNodes = eZContentObjectTreeNode::subTreeByNodeID( $params, $clusterNodeID );

		if ( empty( $fetchedNodes ) )
			break;

		foreach ( $fetchedNodes as $node )
		{
			$object = $node->ContentObject;

			$publisherFolders = $object->relatedObjects( false, false, $attributeID, false, array(
					'AllRelations' => eZContentObject::RELATION_ATTRIBUTE
			), true );

			foreach ( $publisherFolders as $publisherFolder )
			{
				$result['objects'][] = $publisherFolder;
				$result['questions'][] = str_replace( 'publisher_folder-', '',  $publisherFolder->RemoteID );
			}
		}

		$offset += $limit;
	}
	return $result;
}