/**
  * Test FetchByContentObjectList
  */
 public function testFetchByContentObjectIDList()
 {
     $language = eZContentLanguage::fetchByLocale('eng-GB');
     $languageID = $language->attribute('id');
     $time = time();
     $comment1 = array('contentobject_id' => 15, 'language_id' => $languageID, 'created' => $time, 'modified' => $time, 'text' => 'comment1', 'user_id' => 15);
     $comment2 = array('contentobject_id' => 15, 'language_id' => $languageID, 'created' => $time + 1, 'modified' => $time + 1, 'text' => 'comment2', 'user_id' => 15);
     $comment3 = array('contentobject_id' => 15, 'language_id' => $languageID, 'created' => $time + 2, 'modified' => $time + 2, 'text' => 'comment3', 'user_id' => 15);
     $comment4 = array('contentobject_id' => 14, 'language_id' => $languageID, 'created' => $time + 3, 'modified' => $time + 3, 'text' => 'comment4', 'user_id' => 14);
     $comment = ezcomComment::create($comment1);
     $comment->store();
     $comment = ezcomComment::create($comment2);
     $comment->store();
     $comment = ezcomComment::create($comment3);
     $comment->store();
     $comment = ezcomComment::create($comment4);
     $comment->store();
     // test null contentobject id and user id
     $result = ezcomComment::fetchByContentObjectIDList(null, 15, 'eng-GB', null, array('modified' => 'desc'), 0);
     $this->assertEquals('comment3', $result[0]->attribute('text'));
     $this->assertEquals('comment1', $result[2]->attribute('text'));
     // test null contentobject id array and empty user_id
     $result = ezcomComment::fetchByContentObjectIDList(null, null, 'eng-GB', null, array('modified' => 'desc'), 0);
     $this->assertEquals('comment1', $result[3]->attribute('text'));
     // test one contentobject id array
     $result = ezcomComment::fetchByContentObjectIDList(array(14), null, 'eng-GB', null, array('modified' => 'desc'), 0);
     $this->assertEquals('comment4', $result[0]->attribute('text'));
     // test many contentobjects array and sort
     $result = ezcomComment::fetchByContentObjectIDList(array(14, 15), null, 'eng-GB', null, array('modified' => 'asc'), 0);
     $this->assertEquals('comment3', $result[2]->attribute('text'));
     // test length with all null
     $result = ezcomComment::fetchByContentObjectIDList(null, null, null, null, null, null, 3);
     $this->assertEquals(3, count($result));
 }
    /**
     * Test that fetching the language listing, works after languages
     * have been altered in database, and then later refetched.
     *
     * @link http://issues.ez.no/15484
     */
    public function testMapLanguage()
    {
        $db = eZDB::instance();
        eZContentLanguage::addLanguage('nno-NO', 'Nynorsk');
        $localeToChangeInto = 'dan-DK';
        $languageNameToChangeInto = 'Danish';
        $langObject = eZContentLanguage::fetchByLocale('nno-NO');
        $langId = (int) $langObject->attribute('id');
        $updateSql = <<<END
UPDATE ezcontent_language
SET
locale='{$localeToChangeInto}',
name='{$languageNameToChangeInto}'
WHERE
id={$langId}
END;
        $db->query($updateSql);
        eZContentLanguage::expireCache();
        $newLangObject = eZContentLanguage::fetchByLocale($localeToChangeInto);
        if (!$newLangObject instanceof eZContentLanguage) {
            self::fail("Language object not returned. Old version provided by cache?");
        }
        $newLangId = (int) $newLangObject->attribute('id');
        self::assertEquals($langId, $newLangId, "New language not mapped to existing language");
    }
Exemplo n.º 3
0
 /**
  * Initialize ezpClass object
  *
  * @param string $name
  * @param string $identifier
  * @param string $contentObjectName
  * @param int $creatorID
  * @param string $language
  * @param int $groupID
  * @param string $groupName
  */
 public function __construct($name = 'Test class', $identifier = 'test_class', $contentObjectName = '<test_attribute>', $creatorID = 14, $language = 'eng-GB', $groupID = 1, $groupName = 'Content')
 {
     if (eZContentLanguage::fetchByLocale($language) === false) {
         $topPriorityLanguage = eZContentLanguage::topPriorityLanguage();
         if ($topPriorityLanguage) {
             $language = $topPriorityLanguage->attribute('locale');
         }
     }
     $this->language = $language;
     $this->class = eZContentClass::create($creatorID, array(), $this->language);
     $this->class->setName($name, $this->language);
     $this->class->setAttribute('contentobject_name', $contentObjectName);
     $this->class->setAttribute('identifier', $identifier);
     $this->class->store();
     $languageID = eZContentLanguage::idByLocale($this->language);
     $this->class->setAlwaysAvailableLanguageID($languageID);
     $this->classGroup = eZContentClassClassGroup::create($this->id, $this->version, $groupID, $groupName);
     $this->classGroup->store();
 }
Exemplo n.º 4
0
 public static function checkContentRequirements($module, $http)
 {
     // Check that the object params are 'ok'
     if (!$http->hasPostVariable('ContentObjectID')) {
         eZDebug::writeError('No content object id is provided', 'ezcomments');
         return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
     }
     $contentObjectId = (int) $http->postVariable('ContentObjectID');
     // Either use provided language code, or fallback on siteaccess default
     if ($http->hasPostVariable('CommentLanguageCode')) {
         $languageCode = $http->postVariable('CommentLanguageCode');
         $language = eZContentLanguage::fetchByLocale($languageCode);
         if ($language === false) {
             eZDebug::writeError("The language code [{$languageCode}] given is not valid in the system.", 'ezcomments');
             return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
         }
     } else {
         $defaultLanguage = eZContentLanguage::topPriorityLanguage();
         $languageCode = $defaultLanguage->attribute('locale');
     }
     // Check that our object is actually a valid holder of comments
     $contentObject = eZContentObject::fetch($contentObjectId);
     if (!$contentObject instanceof eZContentObject) {
         eZDebug::writeError('No content object exists for the given id.', 'ezcomments');
         return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
     }
     $dataMap = $contentObject->fetchDataMap(false, $languageCode);
     $foundCommentAttribute = false;
     foreach ($dataMap as $attr) {
         if ($attr->attribute('data_type_string') === 'ezcomcomments') {
             $foundCommentAttribute = $attr;
             break;
         }
     }
     // if there is no ezcomcomments attribute inside the content, return
     if (!$foundCommentAttribute) {
         eZDebug::writeError("Content object with id [{$contentObjectId}], does not contain an ezcomments attribute.", 'ezcomments');
         return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
     }
     return compact('contentObjectId', 'languageCode', 'contentObject', 'foundCommentAttribute');
 }
 function setParameters($parm_array)
 {
     if (!isset($parm_array['original_locale'])) {
         return 'Missing locale identifier of original';
     }
     if (!isset($parm_array['new_locale'])) {
         return 'Missing new locale identifier';
     }
     $this->orgLocale = $parm_array['original_locale'];
     $language = eZContentLanguage::fetchByLocale($this->orgLocale);
     if ($language) {
         $this->orgLangID = $language->attribute('id');
     } else {
         return 'Missing original locale to be copied in database';
     }
     $this->newLocale = $parm_array['new_locale'];
     $language = eZContentLanguage::fetchByLocale($this->newLocale);
     if ($language) {
         $this->newLangID = $language->attribute('id');
     } else {
         return 'Missing alternative locale in database';
     }
     return true;
 }
 function setParameters($parm_array)
 {
     if (!isset($parm_array['remove_locale'])) {
         return 'Missing locale identifier to be removed';
     }
     if (!isset($parm_array['alternative_locale'])) {
         return 'Missing alternative locale identifier';
     }
     $this->remLocale = $parm_array['remove_locale'];
     $language = eZContentLanguage::fetchByLocale($this->remLocale);
     if ($language) {
         $this->remLangID = $language->attribute('id');
     } else {
         return 'Missing locale to be removed in database';
     }
     $this->altLocale = $parm_array['alternative_locale'];
     $language = eZContentLanguage::fetchByLocale($this->altLocale);
     if ($language) {
         $this->altLangID = $language->attribute('id');
     } else {
         return 'Missing alternative locale in database';
     }
     return true;
 }
Exemplo n.º 7
0
#!/usr/bin/env php
<?php 
require 'autoload.php';
$cli = eZCLI::instance();
$script = eZScript::instance(array('description' => '\\nInitializes tag translations for upgrade to eZ Tags 2.0.\\n', 'use-session' => false, 'use-modules' => false, 'use-extensions' => true));
$script->startup();
$options = $script->getOptions('[locale:]', '', array('locale' => 'Locale to initialize tag translations with'));
$script->initialize();
if (!isset($options['locale'])) {
    $cli->error("Locale parameter is needed by the script but wasn't specified.");
    $script->shutdown(1);
}
/** @var eZContentLanguage $language */
$language = eZContentLanguage::fetchByLocale($options['locale']);
if (!$language instanceof eZContentLanguage) {
    $cli->error("Invalid locale specified.");
    $script->shutdown(1);
}
$db = eZDB::instance();
$db->begin();
$languageID = (int) $language->attribute('id');
$locale = $db->escapeString($language->attribute('locale'));
$ini = eZINI::instance('eztags.ini');
$alwaysAvailable = $ini->variable('GeneralSettings', 'DefaultAlwaysAvailable');
$alwaysAvailable = $alwaysAvailable === 'true' ? 1 : 0;
$db->query("UPDATE eztags SET main_language_id = {$languageID}, language_mask = {$languageID} + {$alwaysAvailable}");
$db->query("INSERT INTO eztags_keyword\n             SELECT id, {$languageID} + {$alwaysAvailable}, keyword, '{$locale}', 1 FROM eztags");
$db->commit();
$script->shutdown();
        eZDebug::writeDebug($translationName, 'translationName');
        eZDebug::writeDebug($translationLocale, 'translationLocale');
    }
    // Make sure the locale string is valid, if not we try to extract a valid part of it
    if (!preg_match("/^" . eZLocale::localeRegexp(false, false) . "\$/", $translationLocale)) {
        if (preg_match("/(" . eZLocale::localeRegexp(false, false) . ")/", $translationLocale, $matches)) {
            $translationLocale = $matches[1];
        } else {
            // The locale cannot be used so we show the edit page again.
            $tpl->setVariable('is_edit', $Module->isCurrentAction('Edit'));
            $Result['content'] = $tpl->fetch('design:content/translationnew.tpl');
            $Result['path'] = array(array('text' => ezpI18n::tr('kernel/content', 'Translation'), 'url' => false), array('text' => 'New', 'url' => false));
            return;
        }
    }
    if (!eZContentLanguage::fetchByLocale($translationLocale)) {
        $locale = eZLocale::instance($translationLocale);
        if ($locale->isValid()) {
            $translation = eZContentLanguage::addLanguage($locale->localeCode(), $translationName);
            ezpEvent::getInstance()->notify('content/translations/cache', array($translation->attribute('id')));
        } else {
            // The locale cannot be used so we show the edit page again.
            $tpl->setVariable('is_edit', $Module->isCurrentAction('Edit'));
            $Result['content'] = $tpl->fetch('design:content/translationnew.tpl');
            $Result['path'] = array(array('text' => ezpI18n::tr('kernel/content', 'Translation'), 'url' => false), array('text' => 'New', 'url' => false));
            return;
        }
    }
}
if ($Module->isCurrentAction('Remove')) {
    $seletedIDList = $Module->actionParameter('SelectedTranslationList');
Exemplo n.º 9
0
 /**
  * Test that url data for translations in all node locations are removed,
  * when a translations is removed.
  */
 public function testNodeRemovalMultipleLocationsWithTranslations()
 {
     $folder1 = new ezpObject("folder", 2);
     $folder1->name = __FUNCTION__;
     $folder1->publish();
     $child = new ezpObject("article", $folder1->mainNode->node_id);
     $child->title = "Tester";
     $child->publish();
     $languageCode = "nor-NO";
     $trData = array("title" => "NorTester");
     $child->addTranslation($languageCode, $trData);
     $folder2 = new ezpObject("folder", 2);
     $folder2->name = __FUNCTION__ . "-Other";
     $folder2->publish();
     $newPlacement = $child->addNode($folder2->mainNode->node_id);
     $child->removeTranslation($languageCode);
     // Verify that all norwegian url entries are also removed
     $language = eZContentLanguage::fetchByLocale($languageCode, false);
     $languageId = (int) $language->attribute('id');
     $fetchNorUrlEntriesSql = self::buildSql(array($child->mainNode->node_id, $newPlacement->attribute('node_id')), $languageId);
     $db = eZDB::instance();
     $norUrlEntries = $db->arrayQuery($fetchNorUrlEntriesSql);
     self::assertEquals(0, count($norUrlEntries), "There should be no nor-NO url entries left");
 }
{
    $thisUrl .= '/' . $object->attribute( 'id' );
    $tpl->setVariable( 'elevatedObject', $object );

    // check language
    $languageFilter = false;

    if ( $http->hasPostVariable( 'ezfind-elevationdetail-filter-language' ) )
        $languageFilter = $http->postVariable( 'ezfind-elevationdetail-filter-language' );
    elseif ( $Params['Language'] !== false and $Params['Language'] != '' )
        $languageFilter = $Params['Language'];

    if ( $languageFilter and $languageFilter != $wildcard )
    {
        $viewParameters = array_merge( $viewParameters, array( 'language' => htmlspecialchars( $languageFilter, ENT_QUOTES ) ) );
        $tpl->setVariable( 'selectedLocale', eZContentLanguage::fetchByLocale( $languageFilter ) );
    }

    // check fuzzy filter
    $fuzzyFilter = false;

    if ( $http->hasPostVariable( 'ezfind-elevationdetail-filter-fuzzy' ) )
        $fuzzyFilter = true;
    elseif ( $Params['FuzzyFilter'] !== false )
        $fuzzyFilter = true;

    if ( $fuzzyFilter )
    {
        $viewParameters = array_merge( $viewParameters, array( 'fuzzy_filter' => $fuzzyFilter ) );
    }
 /**
  * Adds a new translation and creates a new dedicated fieldset.
  * If $lang is an invalid locale (ie. malformed or not declared in site.ini/RegionalSettings.Locale), will throw a SQLIContentException
  * @param string $lang Translation code to add, as a locale (xxx-XX)
  * @throws SQLIContentException
  */
 public function addTranslation($lang)
 {
     $language = eZContentLanguage::fetchByLocale($lang, true);
     if (!$language instanceof eZContentLanguage) {
         throw new SQLIContentException("Invalid language '{$lang}'. Must be a valid locale declared in site.ini, RegionalSettings.Locale !");
     }
     $db = eZDB::instance();
     $db->begin();
     $version = $this->getCurrentDraft($lang);
     $versionNumber = $version->attribute('version');
     $objectID = $this->contentObject->attribute('id');
     $translatedDataMap = $this->contentObject->fetchDataMap($versionNumber, $lang);
     // Check if data map exists for this language in the current draft
     // Indeed, several translations can be created for only one publication of an object
     if (!$translatedDataMap) {
         $classAttributes = $this->contentObject->fetchClassAttributes();
         foreach ($classAttributes as $classAttribute) {
             // TODO : Check if attribute is translatable
             $classAttribute->instantiate($objectID, $lang, $versionNumber);
         }
         // Now clears in-memory cache for this datamap (it was fetched once above)
         // Then re-fetch the newly created translated data map
         global $eZContentObjectDataMapCache;
         unset($eZContentObjectDataMapCache[$objectID][$versionNumber][$lang]);
         unset($this->contentObject->ContentObjectAttributes[$versionNumber][$lang]);
         unset($this->contentObject->DataMap[$versionNumber][$lang]);
         $translatedDataMap = $this->contentObject->fetchDataMap($versionNumber, $lang);
     }
     $version->setAttribute('initial_language_id', $language->attribute('id'));
     $version->updateLanguageMask();
     $version->store();
     $db->commit();
     $set = SQLIContentFieldset::fromDataMap($translatedDataMap);
     $set->setLanguage($lang);
     $this->fieldsets[$lang] = $set;
     $this->initIterator();
 }
Exemplo n.º 12
0
 function languageInfo($withLanguageNames = false)
 {
     $langaugeInfo = array();
     $classHandler = eZPackage::packageHandler('ezcontentclass');
     $objectHandler = eZPackage::packageHandler('ezcontentobject');
     $explainClassInfo = array('language_info');
     $packageItems = $this->installItemsList();
     foreach ($packageItems as $item) {
         $itemLanguageInfo = array();
         if ($item['type'] == 'ezcontentclass') {
             $classInfo = $classHandler->explainInstallItem($this, $item, $explainClassInfo);
             $itemLanguageInfo = isset($classInfo['language_info']) ? $classInfo['language_info'] : array();
         } else {
             if ($item['type'] == 'ezcontentobject') {
                 $objectsInfo = $objectHandler->explainInstallItem($this, $item);
                 // merge objects info
                 foreach ($objectsInfo as $objectInfo) {
                     $objectLanguages = isset($objectInfo['language_info']) ? $objectInfo['language_info'] : array();
                     foreach ($objectLanguages as $objectLanguage) {
                         if (!in_array($objectLanguage, $itemLanguageInfo)) {
                             $itemLanguageInfo[] = $objectLanguage;
                         }
                     }
                 }
             }
         }
         // merge class and objects infos
         foreach ($itemLanguageInfo as $languageLocale) {
             if (!in_array($languageLocale, $langaugeInfo)) {
                 $langaugeInfo[] = $languageLocale;
             }
         }
     }
     if ($withLanguageNames) {
         $langaugeInfoWithNames = array();
         foreach ($langaugeInfo as $languageLocale) {
             $language = eZContentLanguage::fetchByLocale($languageLocale);
             $languageName = $language->attribute('name');
             $langaugeInfoWithNames[$languageLocale] = $languageName;
         }
         $langaugeInfo = $langaugeInfoWithNames;
     }
     return $langaugeInfo;
 }
 public function testChoosePrioritizedRow()
 {
     // Make sure we can see all languages
     ezpINIHelper::setINISetting('site.ini', 'RegionalSettings', 'ShowUntranslatedObjects', 'enabled');
     $action = "eznode:" . mt_rand();
     $name = __FUNCTION__ . mt_rand();
     $engGB = eZContentLanguage::fetchByLocale('eng-GB');
     $norNO = eZContentLanguage::fetchByLocale('nor-NO');
     // Create an english entry
     $url1 = eZURLAliasML::create($name . " en", $action, 0, $engGB->attribute('id'));
     $url1->store();
     // Create a norwegian entry
     $url2 = eZURLAliasML::create($name . " no", $action, 0, $norNO->attribute('id'));
     $url2->store();
     // Fetch the created entries. choosePrioritizedRow() wants rows from the
     // database so our eZURLAliasML objects wont work.
     $db = eZDB::instance();
     $rows = $db->arrayQuery("SELECT * FROM ezurlalias_ml where action = '{$action}'");
     // -------------------------------------------------------------------
     // TEST PART 1 - NORMAL PRIORITIZATION -------------------------------
     // The order of the language array also determines the prioritization.
     // In this case 'eng-GB' should be prioritized before 'nor-NO'.
     $languageList = array("eng-GB", "nor-NO");
     ezpINIHelper::setINISetting('site.ini', 'RegionalSettings', 'SiteLanguageList', $languageList);
     eZContentLanguage::clearPrioritizedLanguages();
     $row = eZURLAliasML::choosePrioritizedRow($rows);
     // The prioritzed language should be 'eng-GB'
     self::assertEquals($engGB->attribute('id'), $row["lang_mask"]);
     // -------------------------------------------------------------------
     // TEST PART 2 - REVERSED PRIORITIZATION -----------------------------
     // Reverse the order of the specified languages, this will also
     // reverse the priority.
     $languageList = array_reverse($languageList);
     ezpINIHelper::setINISetting('site.ini', 'RegionalSettings', 'SiteLanguageList', $languageList);
     eZContentLanguage::clearPrioritizedLanguages();
     $row = eZURLAliasML::choosePrioritizedRow($rows);
     // The prioritzed language should be 'nor-NO'
     self::assertEquals($norNO->attribute('id'), $row["lang_mask"]);
     // -------------------------------------------------------------------
     // TEST TEAR DOWN ----------------------------------------------------
     ezpINIHelper::restoreINISettings();
     // -------------------------------------------------------------------
 }
Exemplo n.º 14
0
    static function unserialize( $domNode, $contentObject, $ownerID, $sectionID, $activeVersion, $firstVersion, &$nodeList, &$options, $package, $handlerType = 'ezcontentobject' )
    {

        $oldVersion = $domNode->getAttributeNS( 'http://ez.no/ezobject', 'version' );
        $status = $domNode->getAttributeNS( 'http://ez.no/ezobject', 'status' );
        $languageNodeArray = $domNode->getElementsByTagName( 'object-translation' );

        $initialLanguage   = false;
        $importedLanguages = $options['language_array'];
        $currentLanguages  = array();
        foreach( $languageNodeArray as $languageNode )
        {
            $language = eZContentObjectVersion::mapLanguage( $languageNode->getAttribute( 'language' ), $options );
            if ( in_array( $language, $importedLanguages ) )
            {
                $currentLanguages[] = $language;
            }
        }
        foreach ( eZContentLanguage::prioritizedLanguages() as $language )
        {
            if ( in_array( $language->attribute( 'locale' ), $currentLanguages ) )
            {
                $initialLanguage = $language->attribute( 'locale' );
                break;
            }
        }
        if ( !$initialLanguage )
        {
            $initialLanguage = $currentLanguages[0];
        }

        if ( $firstVersion )
        {
            $contentObjectVersion = $contentObject->version( 1 );
        }
        else
        {
            // Create new version in specific language but with empty data.
            $contentObjectVersion = $contentObject->createNewVersionIn( $initialLanguage );
        }

        $created = eZDateUtils::textToDate( $domNode->getAttributeNS( 'http://ez.no/ezobject', 'created' ) );
        $modified = eZDateUtils::textToDate( $domNode->getAttributeNS( 'http://ez.no/ezobject', 'modified' ) );
        $contentObjectVersion->setAttribute( 'created', $created );
        $contentObjectVersion->setAttribute( 'modified', $modified );

        $contentObjectVersion->setAttribute( 'status', eZContentObjectVersion::STATUS_DRAFT );
        $contentObjectVersion->store();

        $db = eZDB::instance();
        $db->begin();
        foreach( $languageNodeArray as $languageNode )
        {
            $language = eZContentObjectVersion::mapLanguage( $languageNode->getAttribute( 'language' ), $options );
            // Only import allowed languages.
            if ( !in_array( $language, $importedLanguages ) )
            {
                continue;
            }

            $attributeArray = $contentObjectVersion->contentObjectAttributes( $language );
            if ( count( $attributeArray ) == 0)
            {
                $hasTranslation = eZContentLanguage::fetchByLocale( $language );

                if ( !$hasTranslation )
                {
                    // if there is no needed translation in system then add it
                    $locale = eZLocale::instance( $language );

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

                if ( $hasTranslation )
                {
                    // Add translated attributes for the translation
                    $originalContentAttributes = $contentObjectVersion->contentObjectAttributes( $initialLanguage );
                    foreach ( $originalContentAttributes as $originalContentAttribute )
                    {
                        $contentAttribute = $originalContentAttribute->translateTo( $language );
                        $contentAttribute->sync();
                        $attributeArray[] = $contentAttribute;
                    }
                }

                // unserialize object name in current version-translation
                $objectName = $languageNode->getAttribute( 'object_name' );
                if ( $objectName )
                    $contentObject->setName( $objectName, $contentObjectVersion->attribute( 'version' ), $language );
            }

            $xpath = new DOMXPath( $domNode->ownerDocument );
            $xpath->registerNamespace( 'ezobject', 'http://ez.no/object/' );
            $xpath->registerNamespace( 'ezremote', 'http://ez.no/ezobject' );

            foreach( $attributeArray as $attribute )
            {
                $attributeIdentifier = $attribute->attribute( 'contentclass_attribute_identifier' );
                $xpathQuery = "ezobject:attribute[@ezremote:identifier='$attributeIdentifier']";
                $attributeDomNodes = $xpath->query( $xpathQuery, $languageNode );
                $attributeDomNode = $attributeDomNodes->item( 0 );
                if ( !$attributeDomNode )
                {
                    continue;
                }
                $attribute->unserialize( $package, $attributeDomNode );
                $attribute->store();
            }
        }

        $objectRelationList = $domNode->getElementsByTagName( 'object-relation-list' )->item( 0 );
        if ( $objectRelationList )
        {
            $objectRelationArray = $objectRelationList->getElementsByTagName( 'related-object-remote-id' );
            foreach( $objectRelationArray as $objectRelation )
            {
                $relatedObjectRemoteID = $objectRelation->textContent;
                if ( $relatedObjectRemoteID )
                {
                    $object = eZContentObject::fetchByRemoteID( $relatedObjectRemoteID );
                    $relatedObjectID = ( $object !== null ) ? $object->attribute( 'id' ) : null;

                    if ( $relatedObjectID )
                    {
                        $contentObject->addContentObjectRelation( $relatedObjectID, $contentObjectVersion->attribute( 'version' ) );
                    }
                    else
                    {
                        if ( !isset( $options['suspended-relations'] ) )
                        {
                            $options['suspended-relations'] = array();
                        }

                        $options['suspended-relations'][] = array( 'related-object-remote-id' => $relatedObjectRemoteID,
                                                                   'contentobject-id'         => $contentObject->attribute( 'id' ),
                                                                   'contentobject-version'    => $contentObjectVersion->attribute( 'version' ) );
                    }
                }
            }
        }

        $nodeAssignmentNodeList = $domNode->getElementsByTagName( 'node-assignment-list' )->item( 0 );
        $nodeAssignmentNodeArray = $nodeAssignmentNodeList->getElementsByTagName( 'node-assignment' );
        foreach( $nodeAssignmentNodeArray as $nodeAssignmentNode )
        {
            $result = eZContentObjectTreeNode::unserialize( $nodeAssignmentNode,
                                                            $contentObject,
                                                            $contentObjectVersion->attribute( 'version' ),
                                                            ( $oldVersion == $activeVersion ? 1 : 0 ),
                                                            $nodeList,
                                                            $options,
                                                            $handlerType );
            if ( $result === false )
            {
                $db->commit();
                $retValue = false;
                return $retValue;
            }
        }

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

        return $contentObjectVersion;
    }
 function validate($param = true)
 {
     $languageMap = is_array($param) && count($param) > 0 ? $param : false;
     $createLanguageIfNotExist = $param === true ? true : false;
     $nameList = $this->nameList();
     foreach ($nameList as $nameLanguageLocale => $name) {
         if ($nameLanguageLocale != eZSerializedObjectNameList::ALWAYS_AVAILABLE_STR) {
             $language = false;
             if ($createLanguageIfNotExist) {
                 $language = eZContentLanguage::fetchByLocale($nameLanguageLocale, true);
             } else {
                 if (is_array($languageMap)) {
                     $languageLocale = isset($languageMap[$nameLanguageLocale]) ? $languageMap[$nameLanguageLocale] : false;
                     if ($languageLocale && $languageLocale != 'skip') {
                         $language = eZContentLanguage::fetchByLocale($languageLocale, true);
                     }
                 } else {
                     // just check '$nameLanguageLocale' language if '$languageMap' is not specified.
                     $language = eZContentLanguage::fetchByLocale($nameLanguageLocale, false);
                 }
             }
             $languageLocale = is_object($language) ? $language->attribute('locale') : false;
             if ($languageLocale != $nameLanguageLocale) {
                 if ($languageLocale) {
                     // map name's language.
                     $this->removeName($nameLanguageLocale);
                     $this->setName($name, $languageLocale);
                 } else {
                     $this->removeName($nameLanguageLocale);
                 }
             }
         }
     }
     // update always-available(probably original 'always-available' was skiped)
     $this->updateAlwaysAvailable();
 }
Exemplo n.º 16
0
 /**
  * \static
  * Returns id of the language specified.
  *
  * \param locale String specifying locale code of the language, e. g. 'slk-SK'
  * \return ID of the language specified by locale or false if the language is not set on the site.
  */
 static function idByLocale($locale)
 {
     $language = eZContentLanguage::fetchByLocale($locale);
     if ($language) {
         return (int) $language->attribute('id');
     } else {
         return false;
     }
 }
Exemplo n.º 17
0
 /**
  * Returns array with language name and locale for this instance
  *
  * @return array
  */
 public function languageName()
 {
     /** @var eZContentLanguage $language */
     $language = eZContentLanguage::fetchByLocale($this->attribute('locale'));
     if ($language instanceof eZContentLanguage) {
         return array('locale' => $language->attribute('locale'), 'name' => $language->attribute('name'));
     }
     return false;
 }
Exemplo n.º 18
0
    function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters )
    {
        switch ( $operatorName )
        {
            // note: these functions are not cache-block safe
            // as in: if called inside a cache-block then they will not be called when cache is used.
            case 'ezpagedata_set':
            case 'ezpagedata_append':
            {
                self::setPersistentVariable( $namedParameters['key'], $namedParameters['value'], $tpl, $operatorName === 'ezpagedata_append' );
            }break;
            case 'ezpagedata':
            {
                $currentNodeId = 0;
                $pageData      = array();
                $parameters    = $namedParameters['params'];

                // Get module_result for later use
                if ( $tpl->hasVariable('module_result') )
                {
                   $moduleResult = $tpl->variable('module_result');
                }
                else
                {
                    $moduleResult = array();
                }

                if ( isset( $moduleResult['content_info'] ) )
                {
                    $contentInfo = $moduleResult['content_info'];
                }
                else
                {
                    $contentInfo = array();
                }

                // Get persistent_variable
                if ( isset( $contentInfo['persistent_variable'] ) && is_array( $contentInfo['persistent_variable'] ) )
                {
                    $pageData['persistent_variable'] = $contentInfo['persistent_variable'];
                }
                else
                {
                     $pageData['persistent_variable'] = self::getPersistentVariable();
                     if ( $pageData['persistent_variable'] === null )
                     {
                         $pageData['persistent_variable'] = array();
                     }
                }

                // Merge parameters with persistent_variable
                $parameters = array_merge( $parameters, $pageData['persistent_variable'] );

                // Figgure out current node id
                if ( isset( $parameters['current_node_id'] ) )
                {
                   $currentNodeId = (int) $parameters['current_node_id'];

                   // Allow parameters to set current path
                   if ( isset( $parameters['set_current_node_path'] ) && $parameters['set_current_node_path'] )
                   {
                       if ( $setPath = self::getNodePath( $currentNodeId ) )
                       {
                           $moduleResult['path'] = $setPath['path'];
                           $moduleResult['title_path'] = $setPath['title_path'];
                           $tpl->setVariable( 'module_result', $moduleResult );
                       }
                       else
                       {
                           eZDebug::writeWarning( "Could not fetch 'current_node_id'", 'eZPageData::getNodePath()' );
                       }
                   }
                }
                else if ( $tpl->hasVariable('current_node_id') )
                {
                   $currentNodeId = (int) $tpl->variable('current_node_id');
                }
                else if ( isset( $moduleResult['node_id'] ) )
                {
                   $currentNodeId = (int) $moduleResult['node_id'];
                }
                else if ( isset( $moduleResult['path'][count( $moduleResult['path'] ) - 1]['node_id'] ) )
                {
                   $currentNodeId = (int) $moduleResult['path'][count( $moduleResult['path'] ) - 1]['node_id'];
                }

                // Init variables and return values
                $ini                      = eZINI::instance( 'site.ini' );
                $menuIni                  = eZINI::instance( 'menu.ini' );
                $contentIni               = eZINI::instance( 'content.ini' );
                $uiContext                = $tpl->variable('ui_context');
                $uriString                = $tpl->variable('uri_string');
                $pageData['main_node_id'] = isset( $contentInfo['main_node_id'] ) ? $contentInfo['main_node_id'] : $currentNodeId;
                $pageData['show_path']           = 'path';
                $pageData['website_toolbar']     = false;
                $pageData['node_id']             = $currentNodeId;
                $pageData['is_edit']             = false;
                $pageData['page_root_depth']     = 0;
                $pageData['page_depth']          = count( $moduleResult['path'] );
                $pageData['root_node']           = (int) $contentIni->variable( 'NodeSettings', 'RootNode' );
                $pageData['canonical_url']       = false;
                $pageData['canonical_language_url'] = false;

                // is_edit if not on user/edit and not on content/action when
                // you get info collector warning about missing attributes
                if ( $uiContext === 'edit'
                  && strpos( $uriString, 'user/edit' ) === false
                  && ( empty( $contentInfo ) || strpos( $uriString, 'content/action' ) === false ) )
                {
                    $pageData['is_edit'] = true;
                }

                if ( isset( $contentInfo['viewmode'] ) )
                {
                    $viewMode = $contentInfo['viewmode'];
                }
                else
                {
                    $viewMode = '';
                }

                // canonical url, to let search engines know about main location on content with multiple locations
                if ( isset( $parameters['canonical_url'] ) )
                {
                    $pageData['canonical_url'] = $parameters['canonical_url'];
                }
                elseif ( isset( $contentInfo['main_node_url_alias'] ) && $contentInfo['main_node_url_alias'] )
                {
                    $pageData['canonical_url'] = $contentInfo['main_node_url_alias'];
                }
                elseif ( isset( $contentInfo['current_language'] )
                      && $contentInfo['current_language'] !== $ini->variable( 'RegionalSettings', 'ContentObjectLocale' ) )
                {
                    $siteaccess = eZSiteAccess::saNameByLanguage( $contentInfo['current_language'] );
                    if ( $siteaccess !== null )
                    {
                        $lang = eZContentLanguage::fetchByLocale( $ini->variable( 'RegionalSettings', 'ContentObjectLocale' ) );
                        if ( ( $contentInfo['language_mask'] & $lang->attribute('id') ) < 1 )
                        {
                            $handlerOptions = new ezpExtensionOptions();
                            $handlerOptions->iniFile = 'site.ini';
                            $handlerOptions->iniSection = 'RegionalSettings';
                            $handlerOptions->iniVariable = 'LanguageSwitcherClass';
                            $handlerOptions->handlerParams = array( array( 'Parameters' => array( 'sa', $currentNodeId ),
                                                                           'UserParameters' => array() ) );
                            $langSwitch = eZExtension::getHandlerClass( $handlerOptions );

                            $langSwitch->setDestinationSiteAccess( $siteaccess );
                            $langSwitch->process();
                            $pageData['canonical_language_url'] = $langSwitch->destinationUrl();
                        }
                    }
                }

                /*
                  RootNodeDepth is a setting for letting you have a very simple multisite, single database and singe siteaccess setup.
                  The content of the menues will be the same on all system pages like user/login, content/edit
                  and so on, and also when you surf bellow the defined page_root_depth.
                  The sites will also share siteaccess and thus also the same ez publish design and templates.
                  You can however custimize the design with css using the class on div#page html output:
                  subtree_level_x_node_id_y class

                  Note: It is recommended to turn it of by setting it to 0 for normal sites!

                  Example having 2 or more 'sub-sites' with RootNodeDepth=2:
                    root (menu shows sub sites as menu choices like it will on system pages)
                    - sub site 1 (menu show content of this sub site)
                    - sub site 2 (-- " --)
                    - sub site 3 (-- " --)
                    - sub site 4 (-- " --)
                    - sub site 5 (-- " --)
                */
                if ( $currentNodeId &&
                     isset( $moduleResult['path'][0]['node_id'] ) &&
                     $moduleResult['path'][0]['node_id'] == '2' &&
                     $ini->hasVariable( 'SiteSettings', 'RootNodeDepth' ) &&
                     $ini->variable( 'SiteSettings', 'RootNodeDepth' ) !== '0' )
                {
                    $pageData['page_root_depth']  = $ini->variable( 'SiteSettings', 'RootNodeDepth' ) -1;

                    if ( isset( $moduleResult['path'][ $pageData['page_root_depth'] ]['node_id'] ))
                    {
                        $pageData['root_node'] = $moduleResult['path'][$pageData['page_root_depth'] ]['node_id'];
                    }
                }

                // Get class identifier for easier access in tempaltes
                $pageData['class_identifier'] = '';
                if ( isset( $contentInfo['class_identifier'] ) )
                {
                    $pageData['class_identifier'] = $contentInfo['class_identifier'];
                }

                // Use custom path template. bool|string ( default: path )
                if ( isset( $parameters['show_path'] ) )
                {
                    $pageData['show_path'] = $parameters['show_path'] === true ? 'path' : $parameters['show_path'];
                }
                else if ( $viewMode === 'sitemap' || $viewMode === 'tagcloud' )
                {
                    $pageData['show_path'] = false;
                }

                // See if we should show website toolbar. bool ( default: false )
                if ( isset( $parameters['website_toolbar'] ) )
                {
                    $pageData['website_toolbar'] = $parameters['website_toolbar'];
                }
                else if ( $viewMode === 'sitemap' || $viewMode === 'tagcloud' || strpos( $uriString, 'content/versionview' ) === 0 )
                {
                    $pageData['website_toolbar'] = false;
                }
                else if ( $tpl->hasVariable('current_user') )
                {
                    $currentUser = $tpl->variable('current_user');
                    $pageData['website_toolbar'] = ( $currentNodeId && $currentUser->attribute('is_logged_in') );
                }

                // Init default menu settings
                $pageData['top_menu']     = $menuIni->variable('SelectedMenu', 'TopMenu');
                $pageData['left_menu']    = $menuIni->variable('SelectedMenu', 'LeftMenu');
                $pageData['current_menu'] = $menuIni->variable('SelectedMenu', 'CurrentMenu');
                $pageData['extra_menu']   = 'extra_info';
                $pageData['extra_menu_node_id']    = $currentNodeId;
                $pageData['extra_menu_subitems']   = 0;
                $pageData['extra_menu_class_list'] = array( 'infobox' );

                // BC: Setting to hide left and extra menu by class identifier
                if ( $menuIni->hasVariable('MenuSettings', 'HideLeftMenuClasses') )
                {
                    $hideMenuClasses = in_array( $pageData['class_identifier'], $menuIni->variable('MenuSettings', 'HideLeftMenuClasses') );
                }
                else
                {
                    $hideMenuClasses = false;
                }

                // Use custom top menu template. bool|string ( default: from menu.ini[SelectedMenu]TopMenu )
                if ( isset( $parameters['top_menu'] ) && $parameters['top_menu'] !== true )
                {
                    $pageData['top_menu'] = $parameters['top_menu'];
                }

                // Use custom left menu template. bool|string ( default: from menu.ini[SelectedMenu]LeftMenu )
                if ( isset( $parameters['left_menu'] ) )
                {
                    if ( $parameters['left_menu'] !== true )
                        $pageData['left_menu'] = $parameters['left_menu'];
                }
                else if ( $hideMenuClasses )
                {
                    $pageData['left_menu'] = false;
                }

                // Use custom extra menu template. bool|string (default: extra_info)
                if ( isset( $parameters['extra_menu'] ) )
                {
                   if ( $parameters['extra_menu'] !== true )
                        $pageData['extra_menu'] = $parameters['extra_menu'];
                }
                else if ( $hideMenuClasses )
                {
                    $pageData['extra_menu'] = false;
                }

                // Use custom node id. int|array (default: current node id)
                if ( isset( $parameters['extra_menu_node_id'] ) )
                {
                    $pageData['extra_menu_node_id'] = $parameters['extra_menu_node_id'];
                }

                // Use custom extra menu identifier list. false|array (default: infobox)
                if ( isset( $parameters['extra_menu_class_list'] ) )
                {
                    $pageData['extra_menu_class_list'] = $parameters['extra_menu_class_list'];
                }
                else if ( $menuIni->hasVariable('MenuContentSettings', 'ExtraIdentifierList') )
                {
                    $pageData['extra_menu_class_list'] = $menuIni->variable('MenuContentSettings', 'ExtraIdentifierList');
                }

                if ( $menuIni->variable( 'MenuSettings', 'AlwaysAvailable' ) === 'false' )
                {
                    // A set of cases where left/extra menu's are hidden unless set by parameters
                    if ( $pageData['is_edit'] || strpos( $uriString, 'content/versionview' ) === 0 )
                    {
                        if ( !isset( $parameters['left_menu'] ) ) $pageData['left_menu']  = false;
                        if ( !isset( $parameters['extra_menu'] ) ) $pageData['extra_menu'] = false;
                    }
                    else if ( !$currentNodeId || $uiContext === 'browse' )
                    {
                        if ( !isset( $parameters['left_menu'] ) ) $pageData['left_menu']  = false;
                        if ( !isset( $parameters['extra_menu'] ) ) $pageData['extra_menu'] = false;
                    }
                }

                // Count extra menu objects if all extra menu settings are present
                if ( isset( $parameters['extra_menu_subitems'] ) )
                {
                    $pageData['extra_menu_subitems'] = $parameters['extra_menu_subitems'];
                    if ( !$pageData['extra_menu_subitems'] ) $pageData['extra_menu'] = false;
                }
                else if ( $pageData['extra_menu'] && $pageData['extra_menu_class_list'] && $pageData['extra_menu_node_id'] )
                {
                    if ( $menuIni->variable( 'MenuContentSettings', 'ExtraMenuSubitemsCheck' ) === 'enabled' )
                    {
                        $pageData['extra_menu_subitems'] = eZContentObjectTreeNode::subTreeCountByNodeID( array( 'Depth' => 1,
                                                                                                                 'DepthOperator'    => 'eq',
                                                                                                                 'ClassFilterType'  => 'include',
                                                                                                                 'ClassFilterArray' => $pageData['extra_menu_class_list'] ),
                                                                                                          $pageData['extra_menu_node_id'] );
                        if ( !$pageData['extra_menu_subitems'] ) $pageData['extra_menu'] = false;
                    }
                }

                // Init path parameters
                $pageData['path_array']      = array();
                $pageData['path_id_array']   = array();
                $pageData['path_normalized'] = '';

                // Creating menu css classes for div#page
                $pageData['css_classes']     = '';

                // Add section css class for div#page
                if ( isset( $moduleResult['section_id'] ))
                {
                    $pageData['css_classes'] .= ' section_id_' . $moduleResult['section_id'];
                }

                // Generate relative path array as well full path id array and path css classes for div#page
                $path = ( isset( $moduleResult['path'] ) && is_array( $moduleResult['path'] ) ) ? $moduleResult['path'] : array();
                foreach ( $path as $key => $item )
                {
                    if ( $key >= $pageData['page_root_depth'])
                    {
                        $pageData['path_array'][] = $item;
                    }
                    if ( isset( $item['node_id'] ) )
                    {
                        $pageData['path_normalized'] .= ' subtree_level_' . $key . '_node_id_' . $item['node_id'];
                        $pageData['path_id_array'][] = $item['node_id'];
                    }
                }
                $pageData['css_classes'] .= $pageData['path_normalized'];

                if ( isset( $pageData['persistent_variable']['pagestyle_css_classes'] )
                        && is_array( $pageData['persistent_variable']['pagestyle_css_classes'] ) )
                {
                    $pageData['css_classes'] .= ' ' . implode( ' ', $pageData['persistent_variable']['pagestyle_css_classes'] );
                }

                $pageData['inner_column_size'] = 8;
                if ( $pageData['left_menu'] && $pageData['extra_menu'] )
                    $pageData['inner_column_size'] = 6;
                if ( !$pageData['left_menu'] && !$pageData['extra_menu'] )
                    $pageData['inner_column_size'] = 12;

                $pageData['outer_column_size'] = 4;
                if ( $pageData['left_menu'] && $pageData['extra_menu'] )
                    $pageData['outer_column_size'] = 3;

                $operatorValue = $pageData;
            } break;
        }
    }
 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;
 }
    /**
     * 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;
    }
Exemplo n.º 21
0
                 $textMD5 = $matches[2];
                 $language = $matches[3];
                 eZURLAliasML::removeSingleEntry($parentID, $textMD5, $language);
             }
         }
         $infoCode = "feedback-removed";
     }
 } else {
     if ($Module->isCurrentAction('NewAlias')) {
         $aliasText = trim($Module->actionParameter('AliasText'));
         $parentIsRoot = false;
         if ($http->hasPostVariable('ParentIsRoot') && strlen(trim($http->postVariable('ParentIsRoot'))) > 0) {
             $parentIsRoot = true;
         }
         $languageCode = $Module->actionParameter('LanguageCode');
         $language = eZContentLanguage::fetchByLocale($languageCode);
         $aliasRedirects = $http->hasPostVariable('AliasRedirects') && $http->postVariable('AliasRedirects');
         if (!$language) {
             $infoCode = "error-invalid-language";
             $infoData['language'] = $languageCode;
         } else {
             if (strlen($aliasText) == 0) {
                 $infoCode = "error-no-alias-text";
             } else {
                 $parentID = 0;
                 $linkID = 0;
                 $filter = new eZURLAliasQuery();
                 $filter->actions = array('eznode:' . $node->attribute('node_id'));
                 $filter->type = 'name';
                 $filter->limit = false;
                 $existingElements = $filter->fetchAll();
Exemplo n.º 22
0
 /**
  * Fetch object by object id list. available since 1.1
  * If $objectIDList is null, it will fetch all comments regardless of content id
  * If $userID is null, it will fetch all user's comments
  * If $languageCode is null, it will fetch comments on currrent site access language code
  * If $status is null, it will fetch comment regardless of status
  *
  * @param array|null $objectIDList
  * @param integer|null $userID
  * @param string|null $languageCode
  * @param integer|null $status
  * @param array|null $sorts
  * @param integer|null $offset
  * @param integer|null $length
  * @param array $extraCondition extra condition according to condition standard in eZPersistentObject::fetchObjectList
  * @return array<ezcomComment>|null|array()
  */
 public static function fetchByContentObjectIDList($objectIDList = null, $userID = null, $languageCode = null, $status = null, $sorts = null, $offset = null, $length = null, $extraCondition = array())
 {
     $cond = array();
     // object id list
     if ($objectIDList !== null && !is_array($objectIDList)) {
         return null;
     }
     if (is_array($objectIDList)) {
         $cond['contentobject_id'] = array($objectIDList);
     }
     // user id
     if ($userID !== null) {
         $cond['user_id'] = $userID;
     }
     // language id
     if ($languageCode === null) {
         $ini = eZINI::instance();
         $languageCode = $ini->variable('RegionalSettings', 'ContentObjectLocale');
     }
     $languageID = eZContentLanguage::fetchByLocale($languageCode)->attribute('id');
     $cond['language_id'] = $languageID;
     // status
     if ($status !== null) {
         $cond['status'] = $status;
     }
     $cond = array_merge($cond, $extraCondition);
     $limit = array('offset' => $offset, 'length' => $length);
     $result = eZPersistentObject::fetchObjectList(self::definition(), null, $cond, $sorts, $limit);
     return $result;
 }
 /**
  *	@desc		Get the language's id by local
  *	@author 	David LE RICHE <*****@*****.**>
  *	@return		int
  *	@copyright	2012
  *	@version 	1.1
  */
 public function getLanguageIdByLocale($locale)
 {
     $language = eZContentLanguage::fetchByLocale($locale);
     return $language->ID;
 }
 /**
  * Returns the SQL where-condition for selecting the rows (with object names, attributes etc.) in the correct language,
  * i. e. in the most prioritized language from those in which an object exists.
  *
  * @param string $languageTable Name of the table containing the attribute with the language id.
  * @param string $languageListTable Name of the table containing the attribute with the available languages bitmap.
  * @param string $languageAttributeName Optional. Name of the attribute in $languageTable which contains
  *                               the language id. 'language_id' by default.
  * @param string $languageListAttributeName Optional. Name of the attribute in $languageListTable which contains
  *                                  the bitmap mask. 'language_mask' by default.
  * @param string $lang Language code of the most prioritized language
  * @return string
  */
 static function sqlFilter($languageTable, $languageListTable = null, $languageAttributeName = 'language_id', $languageListAttributeName = 'language_mask', $lang = false)
 {
     $db = eZDB::instance();
     if ($languageListTable === null) {
         $languageListTable = $languageTable;
     }
     $prioritizedLanguages = eZContentLanguage::prioritizedLanguages();
     if (is_string($lang)) {
         $lang = eZContentLanguage::fetchByLocale($lang);
     }
     if ($lang instanceof eZContentLanguage) {
         array_unshift($prioritizedLanguages, $lang);
     }
     if ($db->databaseName() == 'oracle') {
         $leftSide = "bitand( {$languageListTable}.{$languageListAttributeName} - bitand( {$languageListTable}.{$languageListAttributeName}, {$languageTable}.{$languageAttributeName} ), 1 )\n";
         $rightSide = "bitand( {$languageTable}.{$languageAttributeName}, 1 )\n";
     } else {
         $leftSide = "    ( (   {$languageListTable}.{$languageListAttributeName} - ( {$languageListTable}.{$languageListAttributeName} & {$languageTable}.{$languageAttributeName} ) ) & 1 )\n";
         $rightSide = "  ( {$languageTable}.{$languageAttributeName} & 1 )\n";
     }
     for ($index = count($prioritizedLanguages) - 1, $multiplier = 2; $index >= 0; $index--, $multiplier *= 2) {
         $id = $prioritizedLanguages[$index]->attribute('id');
         if ($db->databaseName() == 'oracle') {
             $leftSide .= "   + bitand( {$languageListTable}.{$languageListAttributeName} - bitand( {$languageListTable}.{$languageListAttributeName}, {$languageTable}.{$languageAttributeName} ), {$id} )";
             $rightSide .= "   + bitand( {$languageTable}.{$languageAttributeName}, {$id} )";
         } else {
             $leftSide .= "   + ( ( ( {$languageListTable}.{$languageListAttributeName} - ( {$languageListTable}.{$languageListAttributeName} & {$languageTable}.{$languageAttributeName} ) ) & {$id} )";
             $rightSide .= "   + ( ( {$languageTable}.{$languageAttributeName} & {$id} )";
         }
         if ($multiplier > $id) {
             $factor = $multiplier / $id;
             if ($db->databaseName() == 'oracle') {
                 $factorTerm = ' * ' . $factor;
             } else {
                 for ($shift = 0; $factor > 1; $factor = $factor / 2, $shift++) {
                 }
                 $factorTerm = ' << ' . $shift;
             }
             $leftSide .= $factorTerm;
             $rightSide .= $factorTerm;
         } else {
             if ($multiplier < $id) {
                 $factor = $id / $multiplier;
                 if ($db->databaseName() == 'oracle') {
                     $factorTerm = ' / ' . $factor;
                 } else {
                     for ($shift = 0; $factor > 1; $factor = $factor / 2, $shift++) {
                     }
                     $factorTerm = ' >> ' . $shift;
                 }
                 $leftSide .= $factorTerm;
                 $rightSide .= $factorTerm;
             }
         }
         if ($db->databaseName() != 'oracle') {
             $leftSide .= " )\n";
             $rightSide .= " )\n";
         }
     }
     if ($db->databaseName() == 'oracle') {
         $sql = "bitand( {$languageTable}.{$languageAttributeName}, {$languageListTable}.{$languageListAttributeName} ) > 0";
     } else {
         $sql = "{$languageTable}.{$languageAttributeName} & {$languageListTable}.{$languageListAttributeName} > 0";
     }
     return "\n ( {$sql} AND\n {$leftSide}   <\n   {$rightSide} ) \n";
 }
Exemplo n.º 25
0
 /**
  * Removes a translation with language $languageCode
  *
  * @param string $languageCode (nor-NO, eng-GB)
  * @return void
  */
 public function removeTranslation($languageCode)
 {
     // Log in as admin first because removeTranslation() checks for permissions.
     $adminUser = eZUser::fetch(14);
     $adminUser->loginCurrent();
     $language = eZContentLanguage::fetchByLocale($languageCode, false);
     $success = $this->object->removeTranslation($language->attribute('id'));
     if (!$success) {
         throw new Exception("Unable to remove translation {$languageCode}");
     }
     // $this->publish();
 }
Exemplo n.º 26
0
 /**
  * Sets the current language
  *
  * @param string $locale the locale code
  * @return boolean true if the language was found and set, false if the language was not found
  */
 public function setCurrentLanguage($locale)
 {
     $lang = eZContentLanguage::fetchByLocale($locale);
     $langID = $lang->attribute('id');
     foreach ($this->translations() as $translation) {
         if ($translation->attribute('language_id') == $langID) {
             $this->setLanguageObject($translation);
             return true;
         }
     }
     return false;
 }
Exemplo n.º 27
0
 /**
  * Save the draft with the provided POST fields like a click on the Store
  * draft button except that a validation issue on an attribute does not
  * prevent the others attributes to be stored.
  *
  * @param array $args array( content object id, version number, locale code )
  * @return array
  */
 public static function saveDraft($args)
 {
     // force text/plain to make IE happy...
     header('Content-Type: text/plain', true);
     $result = array('unvalidated-attributes' => array(), 'stored-attributes' => array(), 'valid' => true);
     $http = eZHTTPTool::instance();
     // workaround to the eZContentObjectEditHandler API that needs a Module
     $Module = false;
     if (count($args) != 3) {
         throw new InvalidArgumentException(ezpI18n::tr('extension/ezautosave/autosave', 'This action requires 3 parameters'));
     }
     if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
         throw new InvalidArgumentException(ezpI18n::tr('extension/ezautosave/autosave', "A POST request is expected"));
     }
     if (count($_POST) === 0) {
         throw new InvalidArgumentException(ezpI18n::tr('extension/ezautosave/autosave', "No POST data found, it's probably because you tried to upload a too big file"));
     }
     $contentObject = eZContentObject::fetch((int) $args[0]);
     if (!$contentObject instanceof eZContentObject) {
         throw new InvalidArgumentException(ezpI18n::tr('extension/ezautosave/autosave', 'Unable to load the content #%objectid', null, array('%objectid' => (int) $args[0])));
     }
     if ($contentObject->attribute('status') == eZContentObject::STATUS_ARCHIVED) {
         throw new InvalidArgumentException(ezpI18n::tr('extension/ezautosave/autosave', 'The content #%objectid is archived', null, array('%objectid' => $contentObject->attribute('id'))));
     }
     $version = $contentObject->version((int) $args[1]);
     if (!$version instanceof eZContentObjectVersion) {
         throw new InvalidArgumentException(ezpI18n::tr('extension/ezautosave/autosave', 'Unable to load version #%versionr of content #%objectid', null, array('%versionr' => (int) $args[1], '%objectid' => $contentObject->attribute('id'))));
     }
     if ($version->attribute('status') != eZContentObjectVersion::STATUS_DRAFT && $version->attribute('status') != eZContentObjectVersion::STATUS_INTERNAL_DRAFT) {
         throw new RuntimeException(ezpI18n::tr('extension/ezautosave/autosave', "Version #%versionr of content #%objectid is not a draft", null, array('%versionr' => $version->attribute('version'), '%objectid' => $version->attribute('contentobject_id'))));
     }
     if ($version->attribute('creator_id') != eZUser::currentUserID()) {
         throw new RuntimeException(ezpI18n::tr('extension/ezautosave/autosave', "You're not allowed to store a version that is not yours"));
     }
     $editLanguage = $args[2];
     $language = eZContentLanguage::fetchByLocale($editLanguage);
     if (!$language instanceof eZContentLanguage) {
         throw new InvalidArgumentException(ezpI18n::tr('extension/ezautosave/autosave', "Unable to load the language '%localeCode'", null, array('%localeCode' => $editLanguage)));
     }
     $class = eZContentClass::fetch($contentObject->attribute('contentclass_id'));
     $contentObjectAttributes = $version->contentObjectAttributes($editLanguage);
     $validationParameters = array('skip-isRequired' => true);
     $attributeDataBaseName = 'ContentObjectAttribute';
     $validationResult = $contentObject->validateInput($contentObjectAttributes, $attributeDataBaseName, false, $validationParameters);
     if ($validationResult['require-fixup']) {
         $contentObject->fixupInput($contentObjectAttributes, $attributeDataBaseName);
     }
     $customValidationResult = eZContentObjectEditHandler::validateInputHandlers($Module, $class, $contentObject, $version, $contentObjectAttributes, $version->attribute('version'), $editLanguage, false, $validationParameters);
     $result['valid'] = $validationResult['input-validated'] && $customValidationResult['validated'];
     $invalidAttributeIds = array();
     foreach ($validationResult['unvalidated-attributes'] as $info) {
         $invalidAttributeIds[$info['id']] = true;
         $result['unvalidated-attributes'][] = $info;
     }
     eZContentObjectEditHandler::executeInputHandlers($Module, $class, $contentObject, $version, $contentObjectAttributes, $version->attribute('version'), $editLanguage, false);
     $customActionAttributeArray = array();
     $fetchResult = $contentObject->fetchInput($contentObjectAttributes, $attributeDataBaseName, $customActionAttributeArray, array());
     $version->setAttribute('modified', time());
     $status = eZContentObjectVersion::STATUS_INTERNAL_DRAFT;
     if ($http->hasPostVariable('StoreExitButton')) {
         $status = eZContentObjectVersion::STATUS_DRAFT;
     }
     $version->setAttribute('status', $status);
     $attributesToStore = array();
     foreach ($fetchResult['attribute-input-map'] as $id => $value) {
         if (!isset($invalidAttributeIds[$id])) {
             $result['stored-attributes'][$id] = $id;
             $attributesToStore[$id] = true;
         }
     }
     $db = eZDB::instance();
     $db->begin();
     $version->store();
     $contentObject->storeInput($contentObjectAttributes, $attributesToStore);
     $contentObject->setName($class->contentObjectName($contentObject, $version->attribute('version'), $editLanguage), $version->attribute('version'), $editLanguage);
     $db->commit();
     $time = eZLocale::instance()->formatShortTime($version->attribute('modified'));
     $result['message_success'] = ezpI18n::tr('extension/ezautosave', "Draft saved at %time", null, array('%time' => $time));
     $result['message_ago'] = ezpI18n::tr('extension/ezautosave', "(%min minutes ago)", null, array('%min' => 0));
     $result['timestamp'] = $version->attribute('modified');
     return $result;
 }
 public static function fetchPathByActionList($actionName, $actionValues, $locale = null)
 {
     if (!is_array($actionValues) || count($actionValues) == 0) {
         eZDebug::writeError("Action values array must not be empty", __METHOD__);
         return null;
     }
     $db = eZDB::instance();
     $actionList = array();
     foreach ($actionValues as $i => $value) {
         $actionList[] = "'" . $db->escapeString($actionName . ":" . $value) . "'";
     }
     $actionStr = join(", ", $actionList);
     $filterSQL = trim(eZContentLanguage::languagesSQLFilter('ezurlalias_ml', 'lang_mask'));
     $query = "SELECT id, parent, lang_mask, text, action FROM ezurlalias_ml WHERE ( {$filterSQL} ) AND action in ( {$actionStr} ) AND is_original = 1 AND is_alias=0";
     $rows = $db->arrayQuery($query);
     $objects = eZContentObject::fetchByNodeID($actionValues);
     $actionMap = array();
     foreach ($rows as $row) {
         $action = $row['action'];
         if (!isset($actionMap[$action])) {
             $actionMap[$action] = array();
         }
         $actionMap[$action][] = $row;
     }
     if ($locale !== null && is_string($locale) && !empty($locale)) {
         $selectedLanguage = eZContentLanguage::fetchByLocale($locale);
         $prioritizedLanguages = eZContentLanguage::prioritizedLanguages();
         // Add $selectedLanguage on top of $prioritizedLanguages to take it into account with the highest priority
         if ($selectedLanguage instanceof eZContentLanguage) {
             array_unshift($prioritizedLanguages, $selectedLanguage);
         }
     } else {
         $prioritizedLanguages = eZContentLanguage::prioritizedLanguages();
     }
     $path = array();
     $lastID = false;
     foreach ($actionValues as $actionValue) {
         $action = $actionName . ":" . $actionValue;
         if (!isset($actionMap[$action])) {
             //                eZDebug::writeError( "The action '{$action}' was not found in the database for the current language language filter, cannot calculate path." );
             return null;
         }
         $actionRows = $actionMap[$action];
         $defaultRow = null;
         foreach ($prioritizedLanguages as $language) {
             foreach ($actionRows as $row) {
                 $langMask = (int) $row['lang_mask'];
                 $wantedMask = (int) $language->attribute('id');
                 if (($wantedMask & $langMask) > 0) {
                     $defaultRow = $row;
                     break 2;
                 }
                 // If the 'always available' bit is set AND it corresponds to the main language, then choose it as the default
                 if ($langMask & 1 && $objects[$actionValue]->attribute('initial_language_id') & $langMask) {
                     $defaultRow = $row;
                 }
             }
         }
         if ($defaultRow) {
             $id = (int) $defaultRow['id'];
             $paren = (int) $defaultRow['parent'];
             // If the parent is 0 it means the element is at the top, ie. reset the path and lastID
             if ($paren == 0) {
                 $lastID = false;
                 $path = array();
             }
             $path[] = $defaultRow['text'];
             // Check for a valid path
             if ($lastID !== false && $lastID != $paren) {
                 eZDebug::writeError("The parent ID {$paren} of element with ID {$id} does not point to the last entry which had ID {$lastID}, incorrect path would be calculated, aborting");
                 return null;
             }
             $lastID = $id;
         } else {
             // No row was found
             eZDebug::writeError("Fatal error, no row was chosen for action " . $actionName . ":" . $actionValue);
             return null;
         }
     }
     return join("/", $path);
 }
Exemplo n.º 29
0
 /**
  * Sets the main translation of the tag to provided locale
  *
  * @param string $locale
  *
  * @return bool
  */
 public function updateMainTranslation($locale)
 {
     $trans = $this->translationByLocale($locale);
     /** @var eZContentLanguage $language */
     $language = eZContentLanguage::fetchByLocale($locale);
     if (!$trans instanceof eZTagsKeyword || !$language instanceof eZContentLanguage) {
         return false;
     }
     $this->setAttribute('main_language_id', $language->attribute('id'));
     $keyword = $this->getKeyword($locale);
     $this->setAttribute('keyword', $keyword);
     $this->store();
     $isAlwaysAvailable = $this->isAlwaysAvailable();
     foreach ($this->getTranslations() as $translation) {
         if (!$isAlwaysAvailable) {
             $languageID = (int) $translation->attribute('language_id') & ~1;
         } else {
             if ($translation->attribute('locale') != $language->attribute('locale')) {
                 $languageID = (int) $translation->attribute('language_id') & ~1;
             } else {
                 $languageID = (int) $translation->attribute('language_id') | 1;
             }
         }
         $translation->setAttribute('language_id', $languageID);
         $translation->store();
     }
     return true;
 }