/**
  * test fetchChildListByVersionStatus
  */
 public function testFetchChildListByVersionStatus()
 {
     //create object
     $top = new ezpObject('article', 2);
     $top->name = 'TOP ARTICLE';
     $top->publish();
     $child = new ezpObject('article', $top->mainNode->node_id);
     $child->name = 'THIS IS AN ARTICLE';
     $child->publish();
     $child2 = new ezpObject('article', $top->mainNode->node_id);
     $child2->name = 'THIS IS AN ARTICLE2';
     $child2->publish();
     $pendingChild = new ezpObject('article', $top->mainNode->node_id);
     $pendingChild->name = 'THIS IS A PENDING ARTICLE';
     $pendingChild->publish();
     $version = $pendingChild->currentVersion();
     $version->setAttribute('status', eZContentObjectVersion::STATUS_PENDING);
     $version->store();
     $idList = array($top->mainNode->node_id);
     $arrayResult = eZNodeAssignment::fetchChildListByVersionStatus($idList, eZContentObjectVersion::STATUS_PENDING, false);
     $this->assertEquals($pendingChild->id, $arrayResult[0]['contentobject_id']);
     $arrayResult = eZNodeAssignment::fetchChildListByVersionStatus($idList, eZContentObjectVersion::STATUS_PUBLISHED, true);
     $this->assertEquals($child->id, $arrayResult[0]->attribute('contentobject_id'));
     $countResult = eZNodeAssignment::fetchChildCountByVersionStatus($idList, eZContentObjectVersion::STATUS_PENDING);
     $this->assertEquals(1, $countResult);
     $countResult = eZNodeAssignment::fetchChildCountByVersionStatus($idList, eZContentObjectVersion::STATUS_PUBLISHED);
     $this->assertEquals(2, $countResult);
 }
示例#2
0
 /**
  * Creates a user with provided auth data
  *
  * @param array $authResult
  *
  * @return bool|eZUser
  */
 public static function createUser($authResult)
 {
     $ngConnectINI = eZINI::instance('ngconnect.ini');
     $siteINI = eZINI::instance('site.ini');
     $defaultUserPlacement = $ngConnectINI->variable('LoginMethod_' . $authResult['login_method'], 'DefaultUserPlacement');
     $placementNode = eZContentObjectTreeNode::fetch($defaultUserPlacement);
     if (!$placementNode instanceof eZContentObjectTreeNode) {
         $defaultUserPlacement = $siteINI->variable('UserSettings', 'DefaultUserPlacement');
         $placementNode = eZContentObjectTreeNode::fetch($defaultUserPlacement);
         if (!$placementNode instanceof eZContentObjectTreeNode) {
             return false;
         }
     }
     $contentClass = eZContentClass::fetch($siteINI->variable('UserSettings', 'UserClassID'));
     $userCreatorID = $siteINI->variable('UserSettings', 'UserCreatorID');
     $defaultSectionID = $siteINI->variable('UserSettings', 'DefaultSectionID');
     $db = eZDB::instance();
     $db->begin();
     $contentObject = $contentClass->instantiate($userCreatorID, $defaultSectionID);
     $contentObject->store();
     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => 1, 'parent_node' => $placementNode->attribute('node_id'), 'is_main' => 1));
     $nodeAssignment->store();
     $currentTimeStamp = eZDateTime::currentTimeStamp();
     /** @var eZContentObjectVersion $version */
     $version = $contentObject->currentVersion();
     $version->setAttribute('modified', $currentTimeStamp);
     $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
     $version->store();
     $dataMap = $version->dataMap();
     self::fillUserObject($version->dataMap(), $authResult);
     if (!isset($dataMap['user_account'])) {
         $db->rollback();
         return false;
     }
     $userLogin = '******' . $authResult['login_method'] . '_' . $authResult['id'];
     $userPassword = (string) rand() . 'ngconnect_' . $authResult['login_method'] . '_' . $authResult['id'] . (string) rand();
     $userExists = false;
     if (eZUser::requireUniqueEmail()) {
         $userExists = eZUser::fetchByEmail($authResult['email']) instanceof eZUser;
     }
     if (empty($authResult['email']) || $userExists) {
         $email = md5('ngconnect_' . $authResult['login_method'] . '_' . $authResult['id']) . '@localhost.local';
     } else {
         $email = $authResult['email'];
     }
     $user = new eZUser(array('contentobject_id' => $contentObject->attribute('id'), 'email' => $email, 'login' => $userLogin, 'password_hash' => md5("{$userLogin}\n{$userPassword}"), 'password_hash_type' => 1));
     $user->store();
     $userSetting = new eZUserSetting(array('is_enabled' => true, 'max_login' => 0, 'user_id' => $contentObject->attribute('id')));
     $userSetting->store();
     $dataMap['user_account']->setContent($user);
     $dataMap['user_account']->store();
     $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObject->attribute('id'), 'version' => $version->attribute('version')));
     if (array_key_exists('status', $operationResult) && $operationResult['status'] == eZModuleOperationInfo::STATUS_CONTINUE) {
         $db->commit();
         return $user;
     }
     $db->rollback();
     return false;
 }
 static function move($nodeID, $newParentNodeID)
 {
     $result = false;
     if (!is_numeric($nodeID) || !is_numeric($newParentNodeID)) {
         return false;
     }
     $node = eZContentObjectTreeNode::fetch($nodeID);
     if (!$node) {
         return false;
     }
     $object = $node->object();
     if (!$object) {
         return false;
     }
     $objectID = $object->attribute('id');
     $oldParentNode = $node->fetchParent();
     $oldParentObject = $oldParentNode->object();
     // clear user policy cache if this is a user object
     if (in_array($object->attribute('contentclass_id'), eZUser::contentClassIDs())) {
         eZUser::purgeUserCacheByUserId($object->attribute('id'));
     }
     // clear cache for old placement.
     eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     $db = eZDB::instance();
     $db->begin();
     $node->move($newParentNodeID);
     $newNode = eZContentObjectTreeNode::fetchNode($objectID, $newParentNodeID);
     if ($newNode) {
         $newNode->updateSubTreePath(true, true);
         if ($newNode->attribute('main_node_id') == $newNode->attribute('node_id')) {
             // If the main node is moved we need to check if the section ID must change
             $newParentNode = $newNode->fetchParent();
             $newParentObject = $newParentNode->object();
             if ($object->attribute('section_id') != $newParentObject->attribute('section_id')) {
                 eZContentObjectTreeNode::assignSectionToSubTree($newNode->attribute('main_node_id'), $newParentObject->attribute('section_id'), $oldParentObject->attribute('section_id'));
             }
         }
         // modify assignment
         $curVersion = $object->attribute('current_version');
         $nodeAssignment = eZNodeAssignment::fetch($objectID, $curVersion, $oldParentNode->attribute('node_id'));
         if ($nodeAssignment) {
             $nodeAssignment->setAttribute('parent_node', $newParentNodeID);
             $nodeAssignment->setAttribute('op_code', eZNodeAssignment::OP_CODE_MOVE);
             $nodeAssignment->store();
             // update search index
             $nodeIDList = array($nodeID);
             eZSearch::removeNodeAssignment($node->attribute('main_node_id'), $newNode->attribute('main_node_id'), $object->attribute('id'), $nodeIDList);
             eZSearch::addNodeAssignment($newNode->attribute('main_node_id'), $object->attribute('id'), $nodeIDList);
         }
         $result = true;
     } else {
         eZDebug::writeError("Node {$nodeID} was moved to {$newParentNodeID} but fetching the new node failed");
     }
     $db->commit();
     // clear cache for new placement.
     eZContentCacheManager::clearContentCacheIfNeeded($objectID);
     return $result;
 }
示例#4
0
文件: index.php 项目: truffo/eep
 public function create($parentNodeId, $classIdentifier, $dataSet)
 {
     $result = array("result" => false);
     $parentNode = eZContentObjectTreeNode::fetch($parentNodeId);
     if (!is_object($parentNode)) {
         throw new Exception("createObject::create(): Failed to locate parent node. id='" . $parentNodeId . "'");
     }
     $contentClass = eZContentClass::fetchByIdentifier($classIdentifier);
     if (!$contentClass) {
         throw new Exception("Failed to instantiate content class [" . $classIdentifier . "]");
     }
     // take care over clustered setups
     $db = eZDB::instance();
     $db->begin();
     $contentObject = $contentClass->instantiate(false, 0, false);
     $dataMap = $contentObject->attribute('data_map');
     foreach ($dataSet as $key => $value) {
         // attributes are lower case
         $key = strtolower($key);
         // if the field exists in the object, write to it
         if (isset($dataMap[$key])) {
             $dataMap[$key]->fromString($value);
             $dataMap[$key]->store();
         }
     }
     $contentObject->store();
     $result["objectid"] = $contentObject->attribute('id');
     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => 1, 'parent_node' => $parentNodeId, 'is_main' => 1));
     if (!$nodeAssignment) {
         throw new Exception("createObject::create(): Failed to create matching node for object of class '" . $classIdentifier . "'");
     }
     $nodeAssignment->store();
     $obj_version = $contentObject->currentVersion();
     $publish = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObject->attribute('id'), 'version' => $obj_version->attribute('version')));
     $db->commit();
     $result["publish"] = $publish;
     $result["parentnodeid"] = $parentNodeId;
     $result["mainnodeid"] = $contentObject->mainNodeID();
     $result["contentclass"] = $classIdentifier;
     $result["contentobjectid"] = $contentObject->attribute('id');
     $result["result"] = true;
     return $result;
 }
示例#5
0
文件: copy.php 项目: legende91/ez
function copyObject($Module, $object, $allVersions, $newParentNodeID)
{
    if (!$newParentNodeID) {
        return $Module->redirectToView('view', array('full', 2));
    }
    // check if we can create node under the specified parent node
    if (($newParentNode = eZContentObjectTreeNode::fetch($newParentNodeID)) === null) {
        return $Module->redirectToView('view', array('full', 2));
    }
    $classID = $object->attribute('contentclass_id');
    if (!$newParentNode->checkAccess('create', $classID)) {
        $objectID = $object->attribute('id');
        eZDebug::writeError("Cannot copy object {$objectID} to node {$newParentNodeID}, " . "the current user does not have create permission for class ID {$classID}", 'content/copy');
        return $Module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel');
    }
    $db = eZDB::instance();
    $db->begin();
    $newObject = $object->copy($allVersions);
    // We should reset section that will be updated in updateSectionID().
    // If sectionID is 0 then the object has been newly created
    $newObject->setAttribute('section_id', 0);
    $newObject->store();
    $curVersion = $newObject->attribute('current_version');
    $curVersionObject = $newObject->attribute('current');
    $newObjAssignments = $curVersionObject->attribute('node_assignments');
    unset($curVersionObject);
    // remove old node assignments
    foreach ($newObjAssignments as $assignment) {
        $assignment->purge();
    }
    // and create a new one
    $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $newObject->attribute('id'), 'contentobject_version' => $curVersion, 'parent_node' => $newParentNodeID, 'is_main' => 1));
    $nodeAssignment->store();
    // publish the newly created object
    eZOperationHandler::execute('content', 'publish', array('object_id' => $newObject->attribute('id'), 'version' => $curVersion));
    // Update "is_invisible" attribute for the newly created node.
    $newNode = $newObject->attribute('main_node');
    eZContentObjectTreeNode::updateNodeVisibility($newNode, $newParentNode);
    $db->commit();
    return $Module->redirectToView('view', array('full', $newParentNodeID));
}
 function createObject($classIdentifier, $parentNodeID, $name)
 {
     $user = eZUser::currentUser();
     $Class = eZContentClass::fetchByIdentifier($classIdentifier);
     if (!$Class) {
         eZDebug::writeError("No class with identifier {$classIdentifier}", "classCreation");
         return false;
     }
     $contentObject = $Class->instantiate($user->attribute('contentobject_id'));
     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1));
     $nodeAssignment->store();
     $version = $contentObject->version(1);
     $version->setAttribute('modified', eZDateTime::currentTimeStamp());
     $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
     $version->store();
     $contentObjectID = $contentObject->attribute('id');
     $attributes = $contentObject->attribute('contentobject_attributes');
     $attributes[0]->fromString($name);
     $attributes[0]->store();
     $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1));
     return true;
 }
示例#7
0
 $class = $object->contentClass();
 if ($module->isCurrentAction('AddAssignment')) {
     $selectedNodeIDArray = eZContentBrowse::result('AddNodeAssignment');
     if (!is_array($selectedNodeIDArray)) {
         $selectedNodeIDArray = array();
     }
     if (eZOperationHandler::operationIsAvailable('content_addlocation')) {
         $operationResult = eZOperationHandler::execute('content', 'addlocation', array('node_id' => $nodeID, 'object_id' => $objectID, 'select_node_id_array' => $selectedNodeIDArray), null, true);
     } else {
         eZContentOperationCollection::addAssignment($nodeID, $objectID, $selectedNodeIDArray);
     }
 } else {
     if ($module->isCurrentAction('SelectAssignmentLocation')) {
         $ignoreNodesSelect = array();
         $ignoreNodesClick = array();
         $assigned = eZNodeAssignment::fetchForObject($objectID, $object->attribute('current_version'), 0, false);
         $publishedAssigned = $object->assignedNodes(false);
         $isTopLevel = false;
         foreach ($publishedAssigned as $element) {
             $append = false;
             if ($element['parent_node_id'] == 1) {
                 $isTopLevel = true;
             }
             foreach ($assigned as $ass) {
                 if ($ass['parent_node'] == $element['parent_node_id']) {
                     $append = true;
                     break;
                 }
             }
             if ($append) {
                 $ignoreNodesSelect[] = $element['node_id'];
示例#8
0
function handleNodeTemplate( $module, $class, $object, $version, $contentObjectAttributes, $editVersion, $editLanguage, $tpl )
{
    // When the object has been published we will use the nodes as
    // node-assignments by faking the list, this is required since new
    // version of the object does not have node-assignments/
    // When the object is a draft we use the normal node-assignment list
    $assignedNodeArray = array();
    $versionedAssignedNodeArray = $version->attribute( 'parent_nodes' );
    $parentNodeIDMap = array();
    $nodes = $object->assignedNodes();
    $i = 0;
    foreach ( $nodes as $node )
    {
        $data = array( 'id' => null,
                       'contentobject_id' => $object->attribute( 'id' ),
                       'contentobject_version' => $version->attribute( 'version' ),
                       'parent_node' => $node->attribute( 'parent_node_id' ),
                       'sort_field' => $node->attribute( 'sort_field' ),
                       'sort_order' => $node->attribute( 'sort_order' ),
                       'is_main' => ( $node->attribute( 'main_node_id' ) == $node->attribute( 'node_id' ) ? 1 : 0 ),
                       'parent_remote_id' => $node->attribute( 'remote_id' ),
                       'op_code' => eZNodeAssignment::OP_CODE_NOP );
        $assignment = eZNodeAssignment::create( $data );
        $assignedNodeArray[$i] = $assignment;
        $parentNodeIDMap[$node->attribute( 'parent_node_id' )] = $i;
        ++$i;
    }
    foreach ( $versionedAssignedNodeArray as $nodeAssignment )
    {
        $opCode = $nodeAssignment->attribute( 'op_code' );
        if ( ( $opCode & 1 ) == eZNodeAssignment::OP_CODE_NOP ) // If the execute bit is not set it will be ignored.
        {
            continue;
        }
        // Only add assignments whose parent is not present in the published nodes.
        if ( isset( $parentNodeIDMap[$nodeAssignment->attribute( 'parent_node' )] ) )
        {
            if ( $opCode == eZNodeAssignment::OP_CODE_CREATE ) // CREATE entries are just skipped
            {
                continue;
            }
            // Or if they have an op_code (move,remove) set, in which case they overwrite the entry
            $index = $parentNodeIDMap[$nodeAssignment->attribute( 'parent_node' )];
            $assignedNodeArray[$index]->setAttribute( 'id', $nodeAssignment->attribute( 'id' ) );
            $assignedNodeArray[$index]->setAttribute( 'from_node_id', $nodeAssignment->attribute( 'from_node_id' ) );
            $assignedNodeArray[$index]->setAttribute( 'remote_id', $nodeAssignment->attribute( 'remote_id' ) );
            $assignedNodeArray[$index]->setAttribute( 'op_code', $nodeAssignment->attribute( 'op_code' ) );
            continue;
        }
        if ( $opCode == eZNodeAssignment::OP_CODE_REMOVE ||
             $opCode == eZNodeAssignment::OP_CODE_MOVE )
        {
            // The node-assignment has a remove/move operation but the node does not exist.
            // We will not show it in this case.
            continue;
        }
        $assignedNodeArray[$i] = $nodeAssignment;
        ++$i;
    }
    eZDebugSetting::writeDebug( 'kernel-content-edit', $assignedNodeArray, "assigned nodes array" );
    $remoteMap = array();

    $db = eZDB::instance();
    $db->begin();
    foreach ( $assignedNodeArray as $assignedNodeKey => $assignedNode )
    {
        $node = $assignedNode->getParentNode();
        if ( $node !== null )
        {
            $remoteID = $assignedNode->attribute( 'remote_id' );
            if ( $remoteID > 0 )
            {
                if ( isset( $remoteMap[$remoteID] ) )
                {
                    if ( is_array( $remoteMap[$remoteID] ) )
                    {
                        $remoteMap[$remoteID][] = $assignedNode;
                    }
                    else
                    {
                        $currentRemote = $remoteMap[$remoteID];
                        unset( $remoteMap[$remoteID] );
                        $remoteMap[$remoteID] = array();
                        $remoteMap[$remoteID][] = $currentRemote;
                        $remoteMap[$remoteID][] = $assignedNode;
                    }
                }
                else
                {
                    $remoteMap[$remoteID] = $assignedNode;
                }
            }
        }
        else
        {
            $assignedNode->purge();
            if( isset( $assignedNodeArray[$assignedNodeKey] ) )
                unset( $assignedNodeArray[$assignedNodeKey] );
        }
    }
    $db->commit();
    eZDebugSetting::writeDebug( 'kernel-content-edit', $assignedNodeArray, "assigned nodes array" );

    $currentVersion = $object->version( $editVersion );
    $publishedNodeArray = array();
    if ( $currentVersion )
        $publishedNodeArray = $currentVersion->attribute( 'parent_nodes' );
    $mainParentNodeID = $version->attribute( 'main_parent_node_id' );

    $tpl->setVariable( 'assigned_node_array', $assignedNodeArray );
    $tpl->setVariable( 'assigned_remote_map', $remoteMap );
    $tpl->setVariable( 'published_node_array', $publishedNodeArray );
    $tpl->setVariable( 'main_node_id', $mainParentNodeID );
}
    function setupAssignments( $parameters )
    {
        $parameters = array_merge( array( 'group-name' => false,
                                          'default-variable-name' => false,
                                          'specific-variable-name' => false,
                                          'fallback-node-id' => false,
                                          'section-id-wanted' => false ),
                                   $parameters );
        if ( !$parameters['group-name'] and
             !$parameters['default-variable-name'] and
             !$parameters['specific-variable-name'] )
             return false;
        $contentINI = eZINI::instance( 'content.ini' );
        $defaultAssignment = $contentINI->variable( $parameters['group-name'], $parameters['default-variable-name'] );
        $specificAssignments = $contentINI->variable( $parameters['group-name'], $parameters['specific-variable-name'] );
        $hasAssignment = false;
        $assignments = false;
        $sectionIDWanted = $parameters['section-id-wanted'];
        $sectionID = 0;
        $contentClass = $this->CurrentObject->attribute( 'content_class' );
        $contentClassIdentifier = $contentClass->attribute( 'identifier' );
        $contentClassID = $contentClass->attribute( 'id' );
        foreach ( $specificAssignments as $specificAssignment )
        {
            $assignmentRules = explode( ';', $specificAssignment );
            $classMatches = $assignmentRules[0];
            $assignments = $assignmentRules[1];
            $mainID = false;
            if ( isset( $assignmentRules[2] ) )
                $mainID = $assignmentRules[2];
            $classMatchArray = explode( ',', $classMatches );
            foreach ( $classMatchArray as $classMatch )
            {
                $classMatch = trim( $classMatch );
                if ( preg_match( "#^group_([0-9]+)$#", $classMatch, $matches ) )
                {
                    $classGroupID = $matches[1];
                    if ( $contentClass->inGroup( $classGroupID ) )
                    {
                        $hasAssignment = true;
                        break;
                    }
                }
                else if ( $classMatch == $contentClassIdentifier )
                {
                    $hasAssignment = true;
                    break;
                }
                else if ( $classMatch == $contentClassID )
                {
                    $hasAssignment = true;
                    break;
                }
            }
            if ( $hasAssignment )
                break;
        }
        if ( !$hasAssignment )
        {
            $assignmentRules = explode( ';', $defaultAssignment );
            $assignments = $assignmentRules[0];
            $mainID = false;
            if ( isset( $assignmentRules[1] ) )
                $mainID = $assignmentRules[1];
        }
        eZDebug::writeDebug( $assignments, 'assignments' );
        if ( $assignments )
        {
            if ( $mainID )
                $mainID = $this->nodeID( $mainID );
            $nodeList = $this->nodeIDList( $assignments );
            eZDebug::writeDebug( $nodeList, 'nodeList' );
            $assignmentCount = 0;
            eZDebug::writeDebug( $this->CurrentObject->attribute( 'id' ), 'current object' );
            eZDebug::writeDebug( $this->CurrentVersion->attribute( 'version' ), 'current version' );
            foreach ( $nodeList as $nodeID )
            {
                $node = eZContentObjectTreeNode::fetch( $nodeID );
                if ( !$node )
                    continue;
                $parentContentObject = $node->attribute( 'object' );

                eZDebug::writeDebug( "Checking for '$nodeID'" );
                if ( $parentContentObject->checkAccess( 'create',
                                                        $contentClassID,
                                                        $parentContentObject->attribute( 'contentclass_id' ) ) == '1' )
                {
                    eZDebug::writeDebug( "Adding to '$nodeID' and main = '$mainID'" );
                    if ( $mainID === false )
                    {
                        $isMain = ( $assignmentCount == 0 );
                    }
                    else
                        $isMain = ( $mainID == $nodeID );

                    /* Here we figure out the section ID in case it is needed
                     * to assign a newly created object to. */
                    if ( $sectionIDWanted and $isMain )
                    {
                        $db = eZDB::instance();
                        $query = "SELECT section_id
                                  FROM ezcontentobject c, ezcontentobject_tree t
                                  WHERE t.node_id = 109
                                      AND t.contentobject_id = c.id";
                        $result = $db->arrayQuery( $query );
                        $sectionID = $result[0]['section_id'];
                    }

                    $nodeAssignment = eZNodeAssignment::create( array( 'contentobject_id' => $this->CurrentObject->attribute( 'id' ),
                                                                       'contentobject_version' => $this->CurrentVersion->attribute( 'version' ),
                                                                       'parent_node' => $node->attribute( 'node_id' ),
                                                                       'is_main' => $isMain ) );
                    $nodeAssignment->store();
                    ++$assignmentCount;
                }
                return $sectionID;
            }

            if ( $assignmentCount == 0 &&
                 $parameters['fallback-node-id'] )
            {
                $nodeAssignment = eZNodeAssignment::create( array( 'contentobject_id' => $this->CurrentObject->attribute( 'id' ),
                                                                   'contentobject_version' => $this->CurrentVersion->attribute( 'version' ),
                                                                   'parent_node' => $parameters['fallback-node-id'],
                                                                   'is_main' => true ) );
                $nodeAssignment->store();
                ++$assignmentCount;
            }
        }
        return true;
    }
示例#10
0
 function onPublish($contentObjectAttribute, $contentObject, $publishedNodes)
 {
     $content = $contentObjectAttribute->content();
     foreach ($content['relation_list'] as $key => $relationItem) {
         if ($relationItem['is_modified']) {
             $subObjectID = $relationItem['contentobject_id'];
             $subObjectVersion = $relationItem['contentobject_version'];
             $object = eZContentObject::fetch($subObjectID);
             $time = time();
             $version = eZContentObjectVersion::fetchVersion($subObjectVersion, $subObjectID);
             $version->setAttribute('modified', $time);
             $version->store();
             if ($relationItem['parent_node_id'] > 0) {
                 // action 1: edit a normal object
                 if (!eZNodeAssignment::fetch($object->attribute('id'), $object->attribute('current_version'), $relationItem['parent_node_id'], false)) {
                     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $relationItem['parent_node_id'], 'sort_field' => eZContentObjectTreeNode::SORT_FIELD_PUBLISHED, 'sort_order' => eZContentObjectTreeNode::SORT_ORDER_DESC, 'is_main' => 1));
                     $nodeAssignment->store();
                 }
                 $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $object->attribute('id'), 'version' => $subObjectVersion));
                 $objectNodeID = $object->attribute('main_node_id');
                 $content['relation_list'][$key]['node_id'] = $objectNodeID;
             } else {
                 // action 2: edit a nodeless object (or creating a new node
                 // Make the previous version archived
                 $currentVersion = $object->currentVersion();
                 $currentVersion->setAttribute('status', eZContentObjectVersion::STATUS_ARCHIVED);
                 $currentVersion->setAttribute('modified', $time);
                 $currentVersion->store();
                 $version->setAttribute('status', eZContentObjectVersion::STATUS_PUBLISHED);
                 $version->store();
                 $object->setAttribute('status', eZContentObject::STATUS_PUBLISHED);
                 if (!$object->attribute('published')) {
                     $object->setAttribute('published', $time);
                 }
                 $object->setAttribute('modified', $time);
                 $object->setAttribute('current_version', $subObjectVersion);
                 $class = $object->contentClass();
                 $objectName = $class->contentObjectName($object, $version->attribute('version'));
                 $object->setName($objectName, $version->attribute('version'));
                 $object->store();
                 if (!eZNodeAssignment::fetch($object->attribute('id'), $object->attribute('current_version'), $contentObject->attribute('main_node_id'), false)) {
                     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $contentObject->attribute('main_node_id'), 'sort_field' => eZContentObjectTreeNode::SORT_FIELD_PUBLISHED, 'sort_order' => eZContentObjectTreeNode::SORT_ORDER_DESC, 'is_main' => 1));
                     $nodeAssignment->store();
                 }
             }
             $content['relation_list'][$key]['is_modified'] = false;
         }
     }
     $this->storeObjectAttributeContent($contentObjectAttribute, $content);
     $contentObjectAttribute->setContent($content);
     $contentObjectAttribute->store();
 }
示例#11
0
function copyPublishContentObject($sourceObject, $sourceSubtreeNodeIDList, &$syncNodeIDListSrc, &$syncNodeIDListNew, &$syncObjectIDListSrc, &$syncObjectIDListNew, $allVersions = false, $keepCreator = false, $keepTime = false)
{
    global $cli;
    $sourceObjectID = $sourceObject->attribute('id');
    $key = array_search($sourceObjectID, $syncObjectIDListSrc);
    if ($key !== false) {
        return 1;
        // object already copied
    }
    $srcNodeList = $sourceObject->attribute('assigned_nodes');
    // check if all parent nodes for given contentobject are already published:
    foreach ($srcNodeList as $srcNode) {
        $sourceParentNodeID = $srcNode->attribute('parent_node_id');
        // if parent node for this node is outside
        // of subtree being copied, then skip this node.
        $key = array_search($sourceParentNodeID, $sourceSubtreeNodeIDList);
        if ($key === false) {
            continue;
        }
        $key = array_search($sourceParentNodeID, $syncNodeIDListSrc);
        if ($key === false) {
            return 2;
            // one of parent nodes is not published yet - have to try to publish later.
        } else {
            $newParentNodeID = $syncNodeIDListNew[$key];
            if (($newParentNode = eZContentObjectTreeNode::fetch($newParentNodeID)) === null) {
                return 3;
                // cannot fetch one of parent nodes - must be error somewhere above.
            }
        }
    }
    // make copy of source object
    $newObject = $sourceObject->copy($allVersions);
    // insert source and new object's ids in $syncObjectIDList
    // We should reset section that will be updated in updateSectionID().
    // If sectionID is 0 than the object has been newly created
    $newObject->setAttribute('section_id', 0);
    $newObject->store();
    $syncObjectIDListSrc[] = $sourceObjectID;
    $syncObjectIDListNew[] = $newObject->attribute('id');
    $curVersion = $newObject->attribute('current_version');
    $curVersionObject = $newObject->attribute('current');
    $newObjAssignments = $curVersionObject->attribute('node_assignments');
    // copy nodeassigments:
    $assignmentsForRemoving = array();
    $foundMainAssignment = false;
    foreach ($newObjAssignments as $assignment) {
        $parentNodeID = $assignment->attribute('parent_node');
        // if assigment is outside of subtree being copied then do not copy this assigment
        $key = array_search($parentNodeID, $sourceSubtreeNodeIDList);
        if ($key === false) {
            $assignmentsForRemoving[] = $assignment->attribute('id');
            continue;
        }
        $key = array_search($parentNodeID, $syncNodeIDListSrc);
        if ($key === false) {
            $cli->error("Subtree Copy Error!\nOne of parent nodes for contentobject (ID = {$sourceObjectID}) is not published yet.");
            return 4;
        }
        if ($assignment->attribute('is_main')) {
            $foundMainAssignment = true;
        }
        $newParentNodeID = $syncNodeIDListNew[$key];
        $assignment->setAttribute('parent_node', $newParentNodeID);
        $assignment->store();
    }
    // remove assigments which are outside of subtree being copied:
    eZNodeAssignment::purgeByID($assignmentsForRemoving);
    // JB valid
    // if main nodeassigment was not copied then set as main first nodeassigment
    if ($foundMainAssignment == false) {
        $newObjAssignments = $curVersionObject->attribute('node_assignments');
        // JB start
        // We need to check if it has any assignments before changing the data.
        if (isset($newObjAssignments[0])) {
            $newObjAssignments[0]->setAttribute('is_main', 1);
            $newObjAssignments[0]->store();
        }
        // JB end
    }
    // publish the newly created object
    $result = eZOperationHandler::execute('content', 'publish', array('object_id' => $newObject->attribute('id'), 'version' => $curVersion));
    // JB start
    // Refetch the object data since it might change in the database.
    $newObjectID = $newObject->attribute('id');
    $newObject = eZContentObject::fetch($newObjectID);
    // JB end
    $newNodeList = $newObject->attribute('assigned_nodes');
    if (count($newNodeList) == 0) {
        $newObject->purge();
        $cli->error("Subtree Copy Error!\nCannot publish contentobject.");
        return 5;
    }
    $objAssignments = $curVersionObject->attribute('node_assignments');
    foreach ($newNodeList as $newNode) {
        $newParentNodeID = $newNode->attribute('parent_node_id');
        $keyA = array_search($newParentNodeID, $syncNodeIDListNew);
        if ($keyA === false) {
            die("Copy Subtree Error: Algoritm ERROR! Cannot find new parent node ID in new ID's list");
        }
        $srcParentNodeID = $syncNodeIDListSrc[$keyA];
        // Update attributes of node
        $bSrcParentFound = false;
        foreach ($srcNodeList as $srcNode) {
            if ($srcNode->attribute('parent_node_id') == $srcParentNodeID) {
                $newNode->setAttribute('priority', $srcNode->attribute('priority'));
                $newNode->setAttribute('is_hidden', $srcNode->attribute('is_hidden'));
                $newNode->setAttribute('is_invisible', $srcNode->attribute('is_invisible'));
                $syncNodeIDListSrc[] = $srcNode->attribute('node_id');
                $syncNodeIDListNew[] = $newNode->attribute('node_id');
                $bSrcParentFound = true;
                break;
            }
        }
        if ($bSrcParentFound == false) {
            die("Copy Subtree Error: Algoritm ERROR! Cannot find source parent node ID in source parent node ID's list of contentobject being copied.");
        }
        // Create unique remote_id
        $newRemoteID = eZRemoteIdUtility::generate('node');
        $oldRemoteID = $newNode->attribute('remote_id');
        $newNode->setAttribute('remote_id', $newRemoteID);
        // Change parent_remote_id for object assignments
        foreach ($objAssignments as $assignment) {
            if ($assignment->attribute('parent_remote_id') == $oldRemoteID) {
                $assignment->setAttribute('parent_remote_id', $newRemoteID);
                $assignment->store();
            }
        }
        $newNode->store();
    }
    // Update "is_invisible" attribute for the newly created node.
    $newNode = $newObject->attribute('main_node');
    eZContentObjectTreeNode::updateNodeVisibility($newNode, $newParentNode);
    // ??? do we need this here?
    // if $keepCreator == true then keep owner of contentobject being
    // copied and creator of its published version Unchaged
    $isModified = false;
    if ($keepTime) {
        $srcPublished = $sourceObject->attribute('published');
        $newObject->setAttribute('published', $srcPublished);
        $srcModified = $sourceObject->attribute('modified');
        $newObject->setAttribute('modified', $srcModified);
        $isModified = true;
    }
    if ($keepCreator) {
        $srcOwnerID = $sourceObject->attribute('owner_id');
        $newObject->setAttribute('owner_id', $srcOwnerID);
        $isModified = true;
    }
    if ($isModified) {
        $newObject->store();
    }
    if ($allVersions) {
        // copy time of creation and modification and creator id for
        // all versions of content object being copied.
        $srcVersionsList = $sourceObject->versions();
        foreach ($srcVersionsList as $srcVersionObject) {
            $newVersionObject = $newObject->version($srcVersionObject->attribute('version'));
            if (!is_object($newVersionObject)) {
                continue;
            }
            $isModified = false;
            if ($keepTime) {
                $srcVersionCreated = $srcVersionObject->attribute('created');
                $newVersionObject->setAttribute('created', $srcVersionCreated);
                $srcVersionModified = $srcVersionObject->attribute('modified');
                $newVersionObject->setAttribute('modified', $srcVersionModified);
                $isModified = true;
            }
            if ($keepCreator) {
                $srcVersionCreatorID = $srcVersionObject->attribute('creator_id');
                $newVersionObject->setAttribute('creator_id', $srcVersionCreatorID);
                $isModified = true;
            }
            if ($isModified) {
                $newVersionObject->store();
            }
        }
    } else {
        $srcVersionObject = $sourceObject->attribute('current');
        $newVersionObject = $newObject->attribute('current');
        $isModified = false;
        if ($keepTime) {
            $srcVersionCreated = $srcVersionObject->attribute('created');
            $newVersionObject->setAttribute('created', $srcVersionCreated);
            $srcVersionModified = $srcVersionObject->attribute('modified');
            $newVersionObject->setAttribute('modified', $srcVersionModified);
            $isModified = true;
        }
        if ($keepCreator) {
            $srcVersionCreatorID = $srcVersionObject->attribute('creator_id');
            $newVersionObject->setAttribute('creator_id', $srcVersionCreatorID);
            $isModified = true;
        }
        if ($isModified) {
            $newVersionObject->store();
        }
    }
    return 0;
    // source object was copied successfully.
}
 /**
  * Creates and publishes a new content object.
  *
  * This function takes all the variables passes in the $params
  * argument and creates a new content object out of it.
  *
  * Here is an example
  * <code>
  * <?php
  *
  * // admin user
  * $creatorID    = 14;
  *
  * // folder content class
  * $classIdentifier = 'folder';
  *
  * // root node
  * $parentNodeID = 2;
  *
  * // have a look at the folder content class' definition ;)
  * // basically the array is the following :
  * // key : attribute identifier ( not attribute ID !! )
  * // value : value for this attribute
  * //
  * // Please refer to each fromString/toString function to see
  * // how to organize your data
  *
  * $xmlDeclaration = '<?xml version="1.0" encoding="utf-8"?>
  *                    <section xmlns:image="http://ez.no/namespaces/ezpublish3/image/"
  *                             xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/"
  *                             xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/">';
  *
  * $attributeList = array( 'name'              => 'A newly created folder object',
  *                         'short_name'        => 'A new folder',
  *                         'short_description' => $xmlDeclaration .'<paragraph>This is the short description</paragraph></section>',
  *                         'description'       => $xmlDeclaration . '<section><section><header>Some header</header><paragraph>Some paragraph
  *                                                                   with a <link target="_blank" url_id="1">link</link></paragraph>
  *                                                                   </section></section></section>',
  *                         'show_children'     => true);
  *
  * // Creates the data import array
  * $params                     = array();
  * $params['creator_id']       = $creatorID;
  * $params['class_identifier'] = $classIdentifier;
  * $params['parent_node_id']   = $parentNodeID;
  * $params['attributes']       = $attributeList;
  *
  * $contentObject = eZContentFunctions::createAndPublishObject( $params );
  *
  * if( $contentObject )
  * {
  *     // do anything you want here
  * }
  *
  * ?>
  * </code>
  *
  * @param array $params An array with all the informations to store.
  *                      This array must contains a strict list of key/value pairs.
  *                      The possible keys are the following :
  *                      - 'parent_node_id'   : The parentNodeID for this new object.
  *                      - 'class_identifier' : The classIdentifier for this new object.
  *                                             using the classID is not possible.
  *                      - 'creator_id'       : The eZUser::contentObjectID to use as creator
  *                                             of this new eZContentObject, uses current user
  *                                             and stores object id in current session if not set
  *                      - 'attributes'       : The list of attributes to store, in order to now
  *                                             which values you can use for this key, you have to
  *                                             read the code of the fromString and toString functions
  *                                             of the attribute's datatype you use
  *                      - 'storage_dir'      :
  *                      - 'remote_id'        : The value for the remoteID  (optional)
  *                      - 'section_id'       : The value for the sectionID (optional)
  * @return eZContentObject|false An eZContentObject object if success, false otherwise
  */
 static function createAndPublishObject($params)
 {
     $parentNodeID = $params['parent_node_id'];
     $classIdentifier = $params['class_identifier'];
     $creatorID = isset($params['creator_id']) ? $params['creator_id'] : false;
     $attributesData = isset($params['attributes']) ? $params['attributes'] : false;
     $storageDir = isset($params['storage_dir']) ? $params['storage_dir'] : '';
     $contentObject = false;
     $parentNode = eZContentObjectTreeNode::fetch($parentNodeID, false, false);
     if (is_array($parentNode)) {
         $contentClass = eZContentClass::fetchByIdentifier($classIdentifier);
         if ($contentClass instanceof eZContentClass) {
             $db = eZDB::instance();
             $db->begin();
             $languageCode = isset($params['language']) ? $params['language'] : false;
             $sectionID = isset($params['section_id']) ? $params['section_id'] : 0;
             $contentObject = $contentClass->instantiate($creatorID, $sectionID, false, $languageCode);
             if (array_key_exists('remote_id', $params)) {
                 $contentObject->setAttribute('remote_id', $params['remote_id']);
             }
             $contentObject->store();
             $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1, 'sort_field' => $contentClass->attribute('sort_field'), 'sort_order' => $contentClass->attribute('sort_order')));
             $nodeAssignment->store();
             $version = $contentObject->version(1);
             $version->setAttribute('modified', eZDateTime::currentTimeStamp());
             $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
             $version->store();
             if (is_array($attributesData) && !empty($attributesData)) {
                 $attributes = $contentObject->attribute('contentobject_attributes');
                 foreach ($attributes as $attribute) {
                     $attributeIdentifier = $attribute->attribute('contentclass_attribute_identifier');
                     if (isset($attributesData[$attributeIdentifier])) {
                         $dataString = $attributesData[$attributeIdentifier];
                         switch ($datatypeString = $attribute->attribute('data_type_string')) {
                             case 'ezimage':
                             case 'ezbinaryfile':
                             case 'ezmedia':
                                 $dataString = $storageDir . $dataString;
                                 break;
                             default:
                         }
                         $attribute->fromString($dataString);
                         $attribute->store();
                     }
                 }
             }
             $db->commit();
             $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObject->attribute('id'), 'version' => 1));
         } else {
             eZDebug::writeError("Content class with identifier '{$classIdentifier}' doesn't exist.", __METHOD__);
         }
     } else {
         eZDebug::writeError("Node with id '{$parentNodeID}' doesn't exist.", __METHOD__);
     }
     return $contentObject;
 }
 /**
  * @param eZContentObject $object
  * @param bool $allVersions
  * @param int $newParentNodeID
  * @throws Exception
  * @return eZContentObject
  */
 public static function copyObject(eZContentObject $object, $allVersions = false, $newParentNodeID = null)
 {
     if (!$object instanceof eZContentObject) {
         throw new InvalidArgumentException('Object not found');
     }
     if (!$newParentNodeID) {
         $newParentNodeID = $object->attribute('main_parent_node_id');
     }
     // check if we can create node under the specified parent node
     if (($newParentNode = eZContentObjectTreeNode::fetch($newParentNodeID)) === null) {
         throw new InvalidArgumentException('Parent node not found');
     }
     $classID = $object->attribute('contentclass_id');
     if (!$newParentNode->checkAccess('create', $classID)) {
         $objectID = $object->attribute('id');
         eZDebug::writeError("Cannot copy object {$objectID} to node {$newParentNodeID}, " . "the current user does not have create permission for class ID {$classID}", 'content/copy');
         throw new Exception('Object not found');
     }
     $db = eZDB::instance();
     $db->begin();
     $newObject = $object->copy($allVersions);
     // We should reset section that will be updated in updateSectionID().
     // If sectionID is 0 then the object has been newly created
     $newObject->setAttribute('section_id', 0);
     $newObject->store();
     $curVersion = $newObject->attribute('current_version');
     $curVersionObject = $newObject->attribute('current');
     $newObjAssignments = $curVersionObject->attribute('node_assignments');
     unset($curVersionObject);
     // remove old node assignments
     foreach ($newObjAssignments as $assignment) {
         /** @var eZNodeAssignment $assignment */
         $assignment->purge();
     }
     // and create a new one
     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $newObject->attribute('id'), 'contentobject_version' => $curVersion, 'parent_node' => $newParentNodeID, 'is_main' => 1));
     $nodeAssignment->store();
     $db->commit();
     return $newObject;
 }
    if (!$discardConfirm) {
        $isConfirmed = true;
    }
}
if ($isConfirmed) {
    $object = eZContentObject::fetch($objectID);
    if ($object === null) {
        return $Module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel');
    }
    $versionObject = $object->version($version);
    if (is_object($versionObject) and in_array($versionObject->attribute('status'), array(eZContentObjectVersion::STATUS_DRAFT, eZContentObjectVersion::STATUS_INTERNAL_DRAFT))) {
        if (!$object->attribute('can_edit')) {
            // Check if it is a first created version of an object.
            // If so, then edit is allowed if we have an access to the 'create' function.
            if ($object->attribute('current_version') == 1 && !$object->attribute('status')) {
                $mainNode = eZNodeAssignment::fetchForObject($object->attribute('id'), 1);
                $parentObj = $mainNode[0]->attribute('parent_contentobject');
                $allowEdit = $parentObj->checkAccess('create', $object->attribute('contentclass_id'), $parentObj->attribute('contentclass_id'));
            } else {
                $allowEdit = false;
            }
            if (!$allowEdit) {
                return $Module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel', array('AccessList' => $object->accessList('edit')));
            }
        }
        $versionCount = $object->getVersionCount();
        $nodeID = $versionCount == 1 ? $versionObject->attribute('main_parent_node_id') : $object->attribute('main_node_id');
        $versionObject->removeThis();
    }
    $hasRedirected = false;
    if ($http->hasSessionVariable('RedirectIfDiscarded')) {
 /**
  * Create a copy of an object.
  *
  * The basis for this method is taken from kernel/content/copy.php
  *
  * @todo Merge this method into kernel wrapper's object class.
  *
  * @param eZContentObject $object
  * @param int $newParentNodeID
  * @return eZContentObject
  */
 public static function copyObject($object, $newParentNodeID)
 {
     $newParentNode = eZContentObjectTreeNode::fetch($newParentNodeID);
     $db = eZDB::instance();
     $db->begin();
     $newObject = $object->copy(true);
     // We should reset section that will be updated in updateSectionID().
     // If sectionID is 0 than the object has been newly created
     $newObject->setAttribute('section_id', 0);
     $newObject->store();
     $curVersion = $newObject->attribute('current_version');
     $curVersionObject = $newObject->attribute('current');
     $newObjAssignments = $curVersionObject->attribute('node_assignments');
     unset($curVersionObject);
     // remove old node assignments
     foreach ($newObjAssignments as $assignment) {
         $assignment->purge();
     }
     // and create a new one
     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $newObject->attribute('id'), 'contentobject_version' => $curVersion, 'parent_node' => $newParentNodeID, 'is_main' => 1));
     $nodeAssignment->store();
     // publish the newly created object
     eZOperationHandler::execute('content', 'publish', array('object_id' => $newObject->attribute('id'), 'version' => $curVersion));
     // Update "is_invisible" attribute for the newly created node.
     $newNode = $newObject->attribute('main_node');
     eZContentObjectTreeNode::updateNodeVisibility($newNode, $newParentNode);
     $db->commit();
     return $newObject;
 }
    function createContentObject( $objectInformation )
    {
        $db = eZDB::instance();
        $contentObjectVersion = false;
        if ( $objectInformation['ownerID'] )
        {
            $userID = $objectInformation['ownerID'];
        }
        else
        {
            $user = eZUser::currentUser();
            $userID = $user->attribute( 'contentobject_id' );
        }
        if ( $objectInformation['remoteID'] )
        {
            $contentObject = eZContentObject::fetchByRemoteId( $objectInformation['remoteID'] );
            if (  $contentObject )
            {
                $this->writeMessage( "\t[".$objectInformation['remoteID']."] Object exists: " . $contentObject->attribute("name") . ". Creating new version.", 'notice' );
                $contentObjectVersion = $contentObject->createNewVersion();
            }
        }
        elseif ( $objectInformation['objectID'] )
        {
            $contentObject = eZContentObject::fetch( $objectInformation['objectID'] );
            if (  $contentObject )
            {
                $this->writeMessage( "\t[".$objectInformation['remoteID']."] Object exists: " . $contentObject->attribute("name") . ". Creating new version.", 'notice' );
                $contentObjectVersion = $contentObject->createNewVersion();
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

                    if( $objectInformation['priority'] )
                    {
                        $this->updateNodePriority( $refArray['node_id'], $objectInformation['priority'] );
                    }
                }
            }
            unset($contentObjectVersion);
            unset($contentObject);
            return $refArray;
        }
    return false;
    }
 /**
  * Copies the specified object to the same folder, with optional $destinationName.
  *
  * @param eZContentObject $object
  * @param eZContentObject $newParentNode
  * @param string $destinationName
  * @return bool
  */
 protected function copyObjectSameDirectory($object, $newParentNode, $destinationName = null)
 {
     $object = $object->ContentObject;
     $newParentNodeID = $newParentNode->attribute('node_id');
     $classID = $object->attribute('contentclass_id');
     if (!$newParentNode->checkAccess('create', $classID)) {
         $objectID = $object->attribute('id');
         return false;
     }
     $db = eZDB::instance();
     $db->begin();
     $newObject = $object->copy(true);
     // We should reset section that will be updated in updateSectionID().
     // If sectionID is 0 than the object has been newly created
     $newObject->setAttribute('section_id', 0);
     // @as 2009-01-08 - Added check for destination name the same as the source name
     // (this was causing problems with nodes disappearing after renaming)
     $newName = $destinationName;
     if ($destinationName === null || strtolower($destinationName) === strtolower($object->attribute('name'))) {
         $newName = 'Copy of ' . $object->attribute('name');
     }
     // @todo @as avoid using [0] (could be another index in some classes)
     $contentObjectAttributes = $newObject->contentObjectAttributes();
     $contentObjectAttributes[0]->setAttribute('data_text', $newName);
     $contentObjectAttributes[0]->store();
     $newObject->store();
     $curVersion = $newObject->attribute('current_version');
     $curVersionObject = $newObject->attribute('current');
     $newObjAssignments = $curVersionObject->attribute('node_assignments');
     unset($curVersionObject);
     // remove old node assignments
     foreach ($newObjAssignments as $assignment) {
         $assignment->purge();
     }
     // and create a new one
     $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $newObject->attribute('id'), 'contentobject_version' => $curVersion, 'parent_node' => $newParentNodeID, 'is_main' => 1));
     $nodeAssignment->store();
     // publish the newly created object
     eZOperationHandler::execute('content', 'publish', array('object_id' => $newObject->attribute('id'), 'version' => $curVersion));
     // Update "is_invisible" attribute for the newly created node.
     $newNode = $newObject->attribute('main_node');
     eZContentObjectTreeNode::updateNodeVisibility($newNode, $newParentNode);
     $db->commit();
     return true;
 }
    function execute( $xmlNode )
    {
        $xmlObjectID = $xmlNode->getAttribute( 'contentObject' );
        $xmlParentNodeID = $xmlNode->getAttribute( 'addToNode' );
        $setReferenceID = $xmlNode->getAttribute( 'setReference' );
        $priority = $xmlNode->getAttribute( 'priority' );

        $objectID = $this->getReferenceID( $xmlObjectID );
        $parentNodeID = $this->getReferenceID( $xmlParentNodeID );

        if ( !$objectID )
        {
            $this->writeMessage( "\tNo object defined.", 'error' );
            return false;
        }
        if ( !$parentNodeID )
        {
            $this->writeMessage( "\tNo location defined.", 'error' );
            return false;
        }

        $object = eZContentObject::fetch( $objectID );
        if ( !$object )
        {
            $this->writeMessage( "\tObject not found.", 'error' );
            return false;
        }

        $parentNode =  eZContentObjectTreeNode::fetch( $parentNodeID );
        if ( !$parentNode )
        {
            $this->writeMessage( "\tparent node not found.", 'error' );
            return false;
        }
        $node = $object->attribute( 'main_node' );

        $nodeAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $object->attribute( 'current_version' ), 0, false );
        $assignedNodes = $object->assignedNodes();

        $parentNodeIDArray = array();
        $setMainNode = false;
        $hasMainNode = false;
        foreach ( $assignedNodes as $assignedNode )
        {
            if ( $assignedNode->attribute( 'is_main' ) )
                $hasMainNode = true;
            $append = false;
            foreach ( $nodeAssignmentList as $nodeAssignment )
            {
                if ( $nodeAssignment['parent_node'] == $assignedNode->attribute( 'parent_node_id' ) )
                {
                    $append = true;
                    break;
                }
            }
            if ( $append )
            {
                $parentNodeIDArray[] = $assignedNode->attribute( 'parent_node_id' );
            }
        }
        if ( !$hasMainNode )
            $setMainNode = true;

        $mainNodeID = $parentNode->attribute( 'main_node_id' );
        $objectName = $object->attribute( 'name' );

        $db = eZDB::instance();
        $db->begin();
        $locationAdded = false;
        $destNode = null;
        if ( !in_array( $parentNodeID, $parentNodeIDArray ) )
        {
            $parentNodeObject = $parentNode->attribute( 'object' );

            $insertedNode = $object->addLocation( $parentNodeID, true );

            // Now set is as published and fix main_node_id
            $insertedNode->setAttribute( 'contentobject_is_published', 1 );
            $insertedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) );
            $insertedNode->setAttribute( 'contentobject_version', $node->attribute( 'contentobject_version' ) );
            // Make sure the url alias is set updated.
            $insertedNode->updateSubTreePath();
            $insertedNode->sync();

            $locationAdded = true;
        }
        if ( $locationAdded )
        {
            $ini = eZINI::instance();
            $userClassID = $ini->variable( "UserSettings", "UserClassID" );
            if ( $object->attribute( 'contentclass_id' ) == $userClassID )
            {
                eZUser::cleanupCache();
            }
            $this->writeMessage( "\tAdded location of " . $object->attribute( 'name' ) . "  to Node $parentNodeID", 'notice' );

            $destNode = $insertedNode;
        }
        else
        {
            $this->writeMessage( "\tLocation of " . $object->attribute( 'name' ) . "  to Node $parentNodeID already exists.", 'notice' );

            $destNode = eZContentObjectTreeNode::fetchObject( eZContentObjectTreeNode::definition(), null, array( 'parent_node_id' => $parentNodeID, 'contentobject_id' => $objectID ) );
        }
        $db->commit();

        if( $destNode && $priority )
        {
            $destNode->setAttribute( 'priority', $priority );
            $destNode->store();
        }

        if( $destNode && $setReferenceID )
        {
            $this->addReference( array( $setReferenceID => $destNode->attribute( 'node_id' ) ) );
        }

        eZContentCacheManager::clearContentCacheIfNeeded( $objectID );
    }
 static function unserialize($contentNodeDOMNode, $contentObject, $version, $isMain, &$nodeList, &$options, $handlerType = 'ezcontentobject')
 {
     $parentNodeID = -1;
     $remoteID = $contentNodeDOMNode->getAttribute('remote-id');
     $parentNodeRemoteID = $contentNodeDOMNode->getAttribute('parent-node-remote-id');
     $node = eZContentObjectTreeNode::fetchByRemoteID($remoteID);
     if (is_object($node)) {
         $description = "Node with remote ID {$remoteID} already exists.";
         $choosenAction = eZPackageHandler::errorChoosenAction(eZContentObject::PACKAGE_ERROR_EXISTS, $options, $description, $handlerType, false);
         switch ($choosenAction) {
             // In case user have choosen "Keep existing object and create new"
             case eZContentObject::PACKAGE_NEW:
                 $newRemoteID = eZRemoteIdUtility::generate('node');
                 $node->setAttribute('remote_id', $newRemoteID);
                 $node->store();
                 $nodeInfo = array('contentobject_id' => $node->attribute('contentobject_id'), 'contentobject_version' => $node->attribute('contentobject_version'), 'parent_remote_id' => $remoteID);
                 $nodeAssignment = eZPersistentObject::fetchObject(eZNodeAssignment::definition(), null, $nodeInfo);
                 if (is_object($nodeAssignment)) {
                     $nodeAssignment->setAttribute('parent_remote_id', $newRemoteID);
                     $nodeAssignment->store();
                 }
                 break;
                 // When running non-interactively with ezpm.php
             // When running non-interactively with ezpm.php
             case eZPackage::NON_INTERACTIVE:
             case eZContentObject::PACKAGE_UPDATE:
                 // Update existing node settigns.
                 if (!$parentNodeRemoteID) {
                     // when top node of subtree export, only update node sort field and sort order
                     $node->setAttribute('sort_field', eZContentObjectTreeNode::sortFieldID($contentNodeDOMNode->getAttribute('sort-field')));
                     $node->setAttribute('sort_order', $contentNodeDOMNode->getAttribute('sort-order'));
                     $node->store();
                     return true;
                 }
                 break;
             default:
                 // This error may occur only if data integrity is broken
                 $options['error'] = array('error_code' => eZContentObject::PACKAGE_ERROR_NODE_EXISTS, 'element_id' => $remoteID, 'description' => $description);
                 return false;
                 break;
         }
     }
     if ($parentNodeRemoteID) {
         $parentNode = eZContentObjectTreeNode::fetchByRemoteID($parentNodeRemoteID);
         if ($parentNode !== null) {
             $parentNodeID = $parentNode->attribute('node_id');
         }
     } else {
         if (isset($options['top_nodes_map'][$contentNodeDOMNode->getAttribute('node-id')]['new_node_id'])) {
             $parentNodeID = $options['top_nodes_map'][$contentNodeDOMNode->getAttribute('node-id')]['new_node_id'];
         } else {
             if (isset($options['top_nodes_map']['*'])) {
                 $parentNodeID = $options['top_nodes_map']['*'];
             } else {
                 eZDebug::writeError('New parent node not set ' . $contentNodeDOMNode->getAttribute('name'), __METHOD__);
             }
         }
     }
     $isMain = $isMain && $contentNodeDOMNode->getAttribute('is-main-node');
     $nodeInfo = array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $version, 'is_main' => $isMain, 'parent_node' => $parentNodeID, 'parent_remote_id' => $remoteID, 'sort_field' => eZContentObjectTreeNode::sortFieldID($contentNodeDOMNode->getAttribute('sort-field')), 'sort_order' => $contentNodeDOMNode->getAttribute('sort-order'));
     if ($parentNodeID == -1 && $parentNodeRemoteID) {
         if (!isset($options['suspended-nodes'])) {
             $options['suspended-nodes'] = array();
         }
         $options['suspended-nodes'][$parentNodeRemoteID] = array('nodeinfo' => $nodeInfo, 'priority' => $contentNodeDOMNode->getAttribute('priority'));
         return true;
     }
     $existNodeAssignment = eZPersistentObject::fetchObject(eZNodeAssignment::definition(), null, $nodeInfo);
     $nodeInfo['priority'] = $contentNodeDOMNode->getAttribute('priority');
     if (!is_object($existNodeAssignment)) {
         $nodeAssignment = eZNodeAssignment::create($nodeInfo);
         $nodeList[] = $nodeInfo;
         $nodeAssignment->store();
     }
     return true;
 }
                            throw new Exception();
                        }
                    } catch (Exception $e) {
                        eZDebug::writeError("Invalid XML input data.", 'view_newslettertype');
                        $input = "";
                    }
                } else {
                    $input = $newsletterType->attribute($typeSource);
                }
                $attribute->setAttribute('data_text', $input);
                $attribute->store();
            }
        }
        $contentObject->store();
    }
    $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $parentNode->attribute('node_id'), 'is_main' => 1));
    $nodeAssignment->store();
    $newsletter = eZNewsletter::create('New "' . $class->attribute('name') . '" newsletter.', $userID, $newsletterType->attribute('id'));
    $newsletter->setAttribute('contentobject_id', $contentObject->attribute('id'));
    $newsletter->setAttribute('contentobject_version', $contentObject->attribute('current_version'));
    $newsletter->setAttribute('design_to_use', strtok($newsletterType->attribute('allowed_designs'), ','));
    $newsletter->store();
    $db->commit();
    return $Module->redirectTo('content/edit/' . $contentObject->attribute('id') . '/' . $contentObject->attribute('current_version'));
}
$userParameters = $Params['UserParameters'];
$offset = isset($userParameters['offset']) ? $userParameters['offset'] : 0;
$limitKey = isset($userParameters['limit']) ? $userParameters['limit'] : '1';
$limitList = array('1' => 10, '2' => 25, '3' => 50);
$limit = $limitList[(string) $limitKey];
$viewParameters = array('offset' => $offset, 'limitkey' => isset($userParameters['limitkey']) ? $userParameters['limitkey'] : 1);
    function installSuspendedNodeAssignment( &$installParameters )
    {
        if ( !isset( $installParameters['suspended-nodes'] ) )
        {
            return;
        }
        foreach ( $installParameters['suspended-nodes'] as $parentNodeRemoteID => $suspendedNodeInfo )
        {
            $parentNode = eZContentObjectTreeNode::fetchByRemoteID( $parentNodeRemoteID );
            if ( $parentNode !== null )
            {
                $nodeInfo = $suspendedNodeInfo['nodeinfo'];
                $nodeInfo['parent_node'] = $parentNode->attribute( 'node_id' );

                $existNodeAssignment = eZPersistentObject::fetchObject( eZNodeAssignment::definition(),
                                                           null,
                                                           $nodeInfo );
                $nodeInfo['priority'] = $suspendedNodeInfo['priority'];
                if( !is_object( $existNodeAssignment ) )
                {
                    $nodeAssignment = eZNodeAssignment::create( $nodeInfo );
                    $nodeAssignment->store();
                }

                $contentObject = eZContentObject::fetch( $nodeInfo['contentobject_id'] );
                if ( is_object( $contentObject ) && $contentObject->attribute( 'current_version' ) == $nodeInfo['contentobject_version'] )
                {
                   eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $nodeInfo['contentobject_id'],
                                                                              'version' =>  $nodeInfo['contentobject_version'] ) );
                }
                if ( isset( $nodeInfo['is_main'] ) && $nodeInfo['is_main'] )
                {
                    $existingMainNode = eZContentObjectTreeNode::fetchByRemoteID( $nodeInfo['parent_remote_id'], false );
                    if ( $existingMainNode )
                    {
                        eZContentObjectTreeNode::updateMainNodeID( $existingMainNode['node_id'],
                                                                   $nodeInfo['contentobject_id'],
                                                                   $nodeInfo['contentobject_version'],
                                                                   $nodeInfo['parent_node'] );
                    }
                }
            }
            else
            {
                eZDebug::writeError( 'Can not find parent node by remote-id ID = ' . $parentNodeRemoteID, __METHOD__ );
            }
            unset( $installParameters['suspended-nodes'][$parentNodeRemoteID] );
        }
    }
示例#22
0
 function createSubNode($node, $name)
 {
     $namedChildrenArray = $node->childrenByName($name);
     $subNode = false;
     //pk
     if (!$node->canCreate()) {
         $this->setError(self::ERROR_ACCESSDENIED, ezpI18n::tr('extension/ezodf/import/error', "Folder for images could not be created, access denied."));
         return false;
     }
     if (empty($namedChildrenArray)) {
         $class = eZContentClass::fetchByIdentifier("folder");
         $creatorID = $this->currentUserID;
         //$creatorID = 14; // 14 == admin
         $parentNodeID = $placeNodeID;
         $contentObject = $class->instantiate($creatorID, 1);
         $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $node->attribute('node_id'), 'is_main' => 1));
         $nodeAssignment->store();
         $version = $contentObject->version(1);
         $version->setAttribute('modified', eZDateTime::currentTimeStamp());
         $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
         $version->store();
         $contentObjectID = $contentObject->attribute('id');
         $dataMap = $contentObject->dataMap();
         $titleAttribudeIdentifier = 'name';
         $dataMap[$titleAttribudeIdentifier]->setAttribute('data_text', $name);
         $dataMap[$titleAttribudeIdentifier]->store();
         $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1));
         $subNode = $contentObject->mainNode();
     } else {
         if (count($namedChildrenArray) == 1) {
             $subNode = $namedChildrenArray[0];
         }
     }
     return $subNode;
 }
示例#23
0
        $tpl->setVariable('checkErrNodeId', $checkErrNodeId);
    }
    $userClassID = $ini->variable("UserSettings", "UserClassID");
    $class = eZContentClass::fetch($userClassID);
    $userCreatorID = $ini->variable("UserSettings", "UserCreatorID");
    $defaultSectionID = $ini->variable("UserSettings", "DefaultSectionID");
    if ($defaultSectionID == 0 && $count > 0) {
        $parentContentObject = eZContentObject::fetchByNodeID($defaultUserPlacement);
        $defaultSectionID = $parentContentObject->attribute('section_id');
    }
    $contentObject = $class->instantiate($userCreatorID, $defaultSectionID);
    $objectID = $contentObject->attribute('id');
    // Store the ID in session variable
    $http->setSessionVariable("RegisterUserID", $objectID);
    $userID = $objectID;
    $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => 1, 'parent_node' => $defaultUserPlacement, 'is_main' => 1));
    $nodeAssignment->store();
} else {
    if ($http->hasSessionVariable('StartedRegistration')) {
        eZDebug::writeWarning('Cancel module run to protect against multiple form submits', 'user/register');
        $http->removeSessionVariable("RegisterUserID");
        $http->removeSessionVariable('StartedRegistration');
        $db->commit();
        return eZModule::HOOK_STATUS_CANCEL_RUN;
    }
    $userID = $http->sessionVariable("RegisterUserID");
}
$Params['ObjectID'] = $userID;
$Module->addHook('post_publish', 'registerSearchObject', 1, false);
if (!function_exists('checkContentActions')) {
    function checkContentActions($module, $class, $object, $version, $contentObjectAttributes, $EditVersion, $EditLanguage)
示例#24
0
 static function setNewMainAssignment($objectID, $version)
 {
     $assignments = eZNodeAssignment::fetchForObject($objectID, $version);
     if (count($assignments) == 0) {
         return true;
     }
     // check: if there is already main assignment for the object then we should do nothing
     // BTW choose first nonremoving assignment as new main assignment
     $newMainAssignment = null;
     foreach ($assignments as $key => $assignment) {
         if ($assignment->attribute('op_code') != eZNodeAssignment::OP_CODE_REMOVE) {
             if ($newMainAssignment === null) {
                 $newMainAssignment = $assignment;
             }
             if ($assignment->attribute('is_main')) {
                 return false;
             }
         }
     }
     $db = eZDB::instance();
     if ($newMainAssignment === null) {
         $db->query("UPDATE eznode_assignment SET is_main=0 WHERE contentobject_id={$objectID} AND contentobject_version={$version}");
         return false;
     }
     $parentMainNodeID = $newMainAssignment->attribute('parent_node');
     $db->begin();
     $db->query("UPDATE eznode_assignment SET is_main=1 WHERE contentobject_id={$objectID} AND contentobject_version={$version} AND parent_node={$parentMainNodeID}");
     $db->query("UPDATE eznode_assignment SET is_main=0 WHERE contentobject_id={$objectID} AND contentobject_version={$version} AND parent_node<>{$parentMainNodeID}");
     $db->commit();
     return true;
 }
示例#25
0
function importRSSItem($item, $rssImport, $cli, $channel)
{
    $rssImportID = $rssImport->attribute('id');
    $rssOwnerID = $rssImport->attribute('object_owner_id');
    // Get owner user id
    $parentContentObjectTreeNode = eZContentObjectTreeNode::fetch($rssImport->attribute('destination_node_id'));
    // Get parent treenode object
    if ($parentContentObjectTreeNode == null) {
        $cli->output('RSSImport ' . $rssImport->attribute('name') . ': Destination tree node seems to be unavailable');
        return 0;
    }
    $parentContentObject = $parentContentObjectTreeNode->attribute('object');
    // Get parent content object
    $titleElement = $item->getElementsByTagName('title')->item(0);
    $title = is_object($titleElement) ? $titleElement->textContent : '';
    // Test for link or guid as unique identifier
    $link = $item->getElementsByTagName('link')->item(0);
    $guid = $item->getElementsByTagName('guid')->item(0);
    $rssId = '';
    if ($link->textContent) {
        $rssId = $link->textContent;
    } elseif ($guid->textContent) {
        $rssId = $guid->textContent;
    } else {
        $cli->output('RSSImport ' . $rssImport->attribute('name') . ': Item has no unique identifier. RSS guid or link missing.');
        return 0;
    }
    $md5Sum = md5($rssId);
    // Try to fetch RSSImport object with md5 sum matching link.
    $existingObject = eZPersistentObject::fetchObject(eZContentObject::definition(), null, array('remote_id' => 'RSSImport_' . $rssImportID . '_' . $md5Sum));
    // if object exists, continue to next import item
    if ($existingObject != null) {
        $cli->output('RSSImport ' . $rssImport->attribute('name') . ': Object ( ' . $existingObject->attribute('id') . ' ) with ID: "' . $rssId . '" already exists');
        unset($existingObject);
        // delete object to preserve memory
        return 0;
    }
    // Fetch class, and create ezcontentobject from it.
    $contentClass = eZContentClass::fetch($rssImport->attribute('class_id'));
    // Instantiate the object with user $rssOwnerID and use section id from parent. And store it.
    $contentObject = $contentClass->instantiate($rssOwnerID, $parentContentObject->attribute('section_id'));
    $db = eZDB::instance();
    $db->begin();
    $contentObject->store();
    $contentObjectID = $contentObject->attribute('id');
    // Create node assignment
    $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObjectID, 'contentobject_version' => $contentObject->attribute('current_version'), 'is_main' => 1, 'parent_node' => $parentContentObjectTreeNode->attribute('node_id')));
    $nodeAssignment->store();
    $version = $contentObject->version(1);
    $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
    $version->store();
    // Get object attributes, and set their values and store them.
    $dataMap = $contentObject->dataMap();
    $importDescription = $rssImport->importDescription();
    // Set content object attribute values.
    $classAttributeList = $contentClass->fetchAttributes();
    foreach ($classAttributeList as $classAttribute) {
        $classAttributeID = $classAttribute->attribute('id');
        if (isset($importDescription['class_attributes'][$classAttributeID])) {
            if ($importDescription['class_attributes'][$classAttributeID] == '-1') {
                continue;
            }
            $importDescriptionArray = explode(' - ', $importDescription['class_attributes'][$classAttributeID]);
            if (count($importDescriptionArray) < 1) {
                $cli->output('RSSImport ' . $rssImport->attribute('name') . ': Invalid import definition. Please redit.');
                break;
            }
            $elementType = $importDescriptionArray[0];
            array_shift($importDescriptionArray);
            switch ($elementType) {
                case 'item':
                    setObjectAttributeValue($dataMap[$classAttribute->attribute('identifier')], recursiveFindRSSElementValue($importDescriptionArray, $item));
                    break;
                case 'channel':
                    setObjectAttributeValue($dataMap[$classAttribute->attribute('identifier')], recursiveFindRSSElementValue($importDescriptionArray, $channel));
                    break;
            }
        }
    }
    $contentObject->setAttribute('remote_id', 'RSSImport_' . $rssImportID . '_' . $md5Sum);
    $contentObject->store();
    $db->commit();
    // Publish new object. The user id is sent to make sure any workflow
    // requiring the user id has access to it.
    $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObject->attribute('id'), 'version' => 1, 'user_id' => $rssOwnerID));
    if (!isset($operationResult['status']) || $operationResult['status'] != eZModuleOperationInfo::STATUS_CONTINUE) {
        if (isset($operationResult['result']) && isset($operationResult['result']['content'])) {
            $failReason = $operationResult['result']['content'];
        } else {
            $failReason = "unknown error";
        }
        $cli->error("Publishing failed: {$failReason}");
        unset($failReason);
    }
    $db->begin();
    unset($contentObject);
    unset($version);
    $contentObject = eZContentObject::fetch($contentObjectID);
    $version = $contentObject->attribute('current');
    // Set object Attributes like modified and published timestamps
    $objectAttributeDescription = $importDescription['object_attributes'];
    foreach ($objectAttributeDescription as $identifier => $objectAttributeDefinition) {
        if ($objectAttributeDefinition == '-1') {
            continue;
        }
        $importDescriptionArray = explode(' - ', $objectAttributeDefinition);
        $elementType = $importDescriptionArray[0];
        array_shift($importDescriptionArray);
        switch ($elementType) {
            default:
            case 'item':
                $domNode = $item;
                break;
            case 'channel':
                $domNode = $channel;
                break;
        }
        switch ($identifier) {
            case 'modified':
                $dateTime = recursiveFindRSSElementValue($importDescriptionArray, $domNode);
                if (!$dateTime) {
                    break;
                }
                $contentObject->setAttribute($identifier, strtotime($dateTime));
                $version->setAttribute($identifier, strtotime($dateTime));
                break;
            case 'published':
                $dateTime = recursiveFindRSSElementValue($importDescriptionArray, $domNode);
                if (!$dateTime) {
                    break;
                }
                $contentObject->setAttribute($identifier, strtotime($dateTime));
                $version->setAttribute('created', strtotime($dateTime));
                break;
        }
    }
    $version->store();
    $contentObject->store();
    $db->commit();
    $cli->output('RSSImport ' . $rssImport->attribute('name') . ': Object created; ' . $title);
    return 1;
}
 /**
  * @return get the CjwNewsletterList Object of the parent nl list node
  */
 function getParentListObject()
 {
     // in draft modus no node is available only node assignment
     $nodeAssignements = eZNodeAssignment::fetchForObject($this->attribute('contentobject_id'), $this->attribute('contentobject_attribute_version'), 1, true);
     if (isset($nodeAssignements[0]) && is_object($nodeAssignements[0])) {
         $parentListNodeId = $nodeAssignements[0]->attribute('parent_node');
         $parentListNode = eZContentObjectTreeNode::fetch($parentListNodeId);
     }
     if (is_object($parentListNode) && $parentListNode->attribute('class_identifier') == 'cjw_newsletter_list') {
         $parentListAttributeDataMap = $parentListNode->attribute('data_map');
         if (isset($parentListAttributeDataMap['newsletter_list'])) {
             $parentListAttribute = $parentListAttributeDataMap['newsletter_list'];
             if (!is_object($parentListAttribute)) {
                 return 0;
             }
             $parentListObject = $parentListAttribute->attribute('content');
             // CjwNewsletterListObject
             if (!is_object($parentListObject)) {
                 return 0;
             } else {
                 return $parentListObject;
             }
         } else {
             return 0;
         }
     } else {
         return 0;
     }
 }
 /**
  * Removes nodes
  *
  * This function does not check about permissions, this is the responsibility of the caller!
  *
  * @param array $removeNodeIdList Array of Node ID to remove
  *
  * @return array An array with operation status, always true
  */
 public static function removeNodes(array $removeNodeIdList)
 {
     $mainNodeChanged = array();
     $nodeAssignmentIdList = array();
     $objectIdList = array();
     $db = eZDB::instance();
     $db->begin();
     foreach ($removeNodeIdList as $nodeId) {
         $node = eZContentObjectTreeNode::fetch($nodeId);
         $objectId = $node->attribute('contentobject_id');
         foreach (eZNodeAssignment::fetchForObject($objectId, eZContentObject::fetch($objectId)->attribute('current_version'), 0, false) as $nodeAssignmentKey => $nodeAssignment) {
             if ($nodeAssignment['parent_node'] == $node->attribute('parent_node_id')) {
                 $nodeAssignmentIdList[$nodeAssignment['id']] = 1;
             }
         }
         if ($nodeId == $node->attribute('main_node_id')) {
             $mainNodeChanged[$objectId] = 1;
         }
         $node->removeThis();
         if (!isset($objectIdList[$objectId])) {
             $objectIdList[$objectId] = eZContentObject::fetch($objectId);
         }
     }
     eZNodeAssignment::purgeByID(array_keys($nodeAssignmentIdList));
     foreach (array_keys($mainNodeChanged) as $objectId) {
         $allNodes = $objectIdList[$objectId]->assignedNodes();
         // Registering node that will be promoted as 'main'
         $mainNodeChanged[$objectId] = $allNodes[0];
         eZContentObjectTreeNode::updateMainNodeID($allNodes[0]->attribute('node_id'), $objectId, false, $allNodes[0]->attribute('parent_node_id'));
     }
     // Give other search engines that the default one a chance to reindex
     // when removing locations.
     if (!eZSearch::getEngine() instanceof eZSearchEngine) {
         foreach (array_keys($objectIdList) as $objectId) {
             eZContentOperationCollection::registerSearchObject($objectId);
         }
     }
     $db->commit();
     //call appropriate method from search engine
     eZSearch::removeNodes($removeNodeIdList);
     $userClassIdList = eZUser::contentClassIDs();
     foreach ($objectIdList as $objectId => $object) {
         eZContentCacheManager::clearObjectViewCacheIfNeeded($objectId);
         // clear user policy cache if this was a user object
         if (in_array($object->attribute('contentclass_id'), $userClassIdList)) {
             eZUser::purgeUserCacheByUserId($object->attribute('id'));
         }
     }
     // we don't clear template block cache here since it's cleared in eZContentObjectTreeNode::removeNode()
     return array('status' => 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;
    }
function copyPublishContentObject($sourceObject, $sourceSubtreeNodeIDList, &$syncNodeIDListSrc, &$syncNodeIDListNew, &$syncObjectIDListSrc, &$syncObjectIDListNew, $objectIDBlackList, &$nodeIDBlackList, &$notifications, $allVersions = false, $keepCreator = false, $keepTime = false)
{
    $sourceObjectID = $sourceObject->attribute('id');
    $key = array_search($sourceObjectID, $syncObjectIDListSrc);
    if ($key !== false) {
        eZDebug::writeDebug("Object (ID = {$sourceObjectID}) has been already copied.", "Subtree copy: copyPublishContentObject()");
        return 1;
        // object already copied
    }
    $srcNodeList = $sourceObject->attribute('assigned_nodes');
    // if we already failed to copy that contentobject, then just skip it:
    if (in_array($sourceObjectID, $objectIDBlackList)) {
        return 0;
    }
    // if we already failed to copy that node, then just skip it:
    //if ( in_array( $sourceNodeID, $nodeIDBlackList ) )
    //    return 0;
    // if cannot read contentobject then remember it and all its nodes (nodes
    // which are inside subtree being copied) in black list, and skip current node:
    if (!$sourceObject->attribute('can_read')) {
        $objectIDBlackList[] = $sourceObjectID;
        $notifications['Warnings'][] = ezpI18n::tr('kernel/content/copysubtree', "Object (ID = %1) was not copied: you do not have permission to read the object.", null, array($sourceObjectID));
        $srcNodeList = $sourceObject->attribute('assigned_nodes');
        foreach ($srcNodeList as $srcNode) {
            $srcNodeID = $srcNode->attribute('node_id');
            $sourceParentNodeID = $srcNode->attribute('parent_node_id');
            $key = array_search($sourceParentNodeID, $sourceSubtreeNodeIDList);
            if ($key !== false) {
                $nodeIDBlackList[] = $srcNodeID;
                $notifications['Warnings'][] = ezpI18n::tr('kernel/content/copysubtree', "Node (ID = %1) was not copied: you do not have permission to read object (ID = %2).", null, array($srcNodeID, $sourceObjectID));
            }
        }
        return 0;
    }
    // check if all possible parent nodes for given contentobject are already published:
    $isReadyToPublish = false;
    foreach ($srcNodeList as $srcNode) {
        $srcNodeID = $srcNode->attribute('node_id');
        if (in_array($srcNodeID, $nodeIDBlackList)) {
            continue;
        }
        $srcParentNodeID = $srcNode->attribute('parent_node_id');
        // if parent node for this node is outside
        // of subtree being copied, then skip this node:
        $key = array_search($srcParentNodeID, $sourceSubtreeNodeIDList);
        if ($key === false) {
            continue;
        }
        // if parent node for this node wasn't copied yet and is in black list
        // then add that node in black list and just skip it:
        $key = array_search($srcParentNodeID, $nodeIDBlackList);
        if ($key !== false) {
            $nodeIDBlackList[] = $srcNodeID;
            $notifications['Warnings'][] = ezpI18n::tr('kernel/content/copysubtree', "Node (ID = %1) was not copied: parent node (ID = %2) was not copied.", null, array($srcNodeID, $srcParentNodeID));
            continue;
        }
        $key = array_search($srcParentNodeID, $syncNodeIDListSrc);
        if ($key === false) {
            // if parent node is not copied yet and not in black list,
            // then just skip sourceObject from copying for next time
            eZDebug::writeDebug("Parent node (ID = {$srcParentNodeID}) for contentobject (ID = {$sourceObjectID}) is not published yet.", "Subtree copy: copyPublishContentObject()");
            return 2;
        } else {
            $newParentNodeID = $syncNodeIDListNew[$key];
            $newParentNode = eZContentObjectTreeNode::fetch($newParentNodeID);
            if ($newParentNode === null) {
                eZDebug::writeError("Cannot fetch one of parent nodes. Error are somewhere above", "Subtree copy error: copyPublishContentObject()");
                return 3;
            }
            if ($newParentNode->checkAccess('create', $sourceObject->attribute('contentclass_id')) != 1) {
                $nodeIDBlackList[] = $srcNodeID;
                $notifications['Warnings'][] = ezpI18n::tr('kernel/content/copysubtree', "Node (ID = %1) was not copied: you do not have permission to create.", null, array($srcNodeID));
                continue;
            } else {
                $isReadyToPublish = true;
            }
        }
    }
    // if all nodes of sourceObject were skiped as black list entry or
    // as outside of subtree being copied, then sourceObject cannot be
    // copied and published in any new location. So insert sourceObject
    // in a black list and skip it.
    if ($isReadyToPublish == false) {
        $objectIDBlackList[] = $sourceObjectID;
        $notifications['Warnings'][] = ezpI18n::tr('kernel/content/copysubtree', "Object (ID = %1) was not copied: no one nodes of object was not copied.", null, array($sourceObjectID));
        return 0;
    }
    // make copy of source object
    $newObject = $sourceObject->copy($allVersions);
    // insert source and new object's ids in $syncObjectIDList
    // We should reset section that will be updated in updateSectionID().
    // If sectionID is 0 than the object has been newly created
    $newObject->setAttribute('section_id', 0);
    $newObject->store();
    $syncObjectIDListSrc[] = $sourceObjectID;
    $curVersion = $newObject->attribute('current_version');
    $curVersionObject = $newObject->attribute('current');
    $newObjAssignments = $curVersionObject->attribute('node_assignments');
    // copy nodeassigments:
    $assignmentsForRemoving = array();
    $foundMainAssignment = false;
    foreach ($newObjAssignments as $assignment) {
        $parentNodeID = $assignment->attribute('parent_node');
        // if assigment is outside of subtree being copied then do not copy this assigment
        $key1 = array_search($parentNodeID, $sourceSubtreeNodeIDList);
        $key2 = array_search($parentNodeID, $nodeIDBlackList);
        if ($key1 === false or $key2 !== false) {
            $assignmentsForRemoving[] = $assignment->attribute('id');
            continue;
        }
        $key = array_search($parentNodeID, $syncNodeIDListSrc);
        if ($key === false) {
            eZDebug::writeError("Cannot publish contentobject (ID={$sourceObjectID}). Parent is not published yet.", "Subtree Copy error: copyPublishContentObject()");
            return 4;
        }
        if ($assignment->attribute('is_main')) {
            $foundMainAssignment = true;
        }
        $newParentNodeID = $syncNodeIDListNew[$key];
        $assignment->setAttribute('parent_node', $newParentNodeID);
        $assignment->store();
    }
    // remove assigments which are outside of subtree being copied:
    eZNodeAssignment::purgeByID($assignmentsForRemoving);
    // if main nodeassigment was not copied then set as main first nodeassigment
    if ($foundMainAssignment == false) {
        $newObjAssignments = $curVersionObject->attribute('node_assignments');
        // We need to check if it has any assignments before changing the data.
        if (isset($newObjAssignments[0])) {
            $newObjAssignments[0]->setAttribute('is_main', 1);
            $newObjAssignments[0]->store();
        }
    }
    // publish the newly created object
    $result = eZOperationHandler::execute('content', 'publish', array('object_id' => $newObject->attribute('id'), 'version' => $curVersion));
    // Refetch the object data since it might change in the database.
    $newObjectID = $newObject->attribute('id');
    $newObject = eZContentObject::fetch($newObjectID);
    $newNodeList = $newObject->attribute('assigned_nodes');
    if (count($newNodeList) == 0) {
        $newObject->purge();
        eZDebug::writeError("Cannot publish contentobject.", "Subtree Copy Error!");
        $sourceObjectName = $srcNode->getName();
        $notifications['Warnings'][] = ezpI18n::tr('kernel/content/copysubtree', "Cannot publish object (Name: %1, ID: %2).", null, array($sourceObjectName, $sourceObjectID));
        return -1;
    }
    // Only if the object has been published successfully, the object id can be added into $syncObjectIDListNew
    $syncObjectIDListNew[] = $newObject->attribute('id');
    $objAssignments = $curVersionObject->attribute('node_assignments');
    foreach ($newNodeList as $newNode) {
        $newParentNode = $newNode->fetchParent();
        $newParentNodeID = $newParentNode->attribute('node_id');
        $keyA = array_search($newParentNodeID, $syncNodeIDListNew);
        if ($keyA === false) {
            eZDebug::writeError("Algoritm ERROR! Cannot find new parent node ID in new ID's list", "Subtree Copy Error!");
            return -2;
        }
        $srcParentNodeID = $syncNodeIDListSrc[$keyA];
        // Update attributes of node
        $bSrcParentFound = false;
        foreach ($srcNodeList as $srcNode) {
            if ($srcNode->attribute('parent_node_id') == $srcParentNodeID) {
                $newNode->setAttribute('priority', $srcNode->attribute('priority'));
                $newNode->setAttribute('is_hidden', $srcNode->attribute('is_hidden'));
                // Update node visibility
                if ($newParentNode->attribute('is_invisible') or $newParentNode->attribute('is_hidden')) {
                    $newNode->setAttribute('is_invisible', 1);
                } else {
                    $newNode->setAttribute('is_invisible', $srcNode->attribute('is_invisible'));
                }
                $syncNodeIDListSrc[] = $srcNode->attribute('node_id');
                $syncNodeIDListNew[] = $newNode->attribute('node_id');
                $bSrcParentFound = true;
                break;
            }
        }
        if ($bSrcParentFound == false) {
            eZDebug::writeError("Cannot find source parent node in list of nodes already copied.", "Subtree Copy Error!");
        }
        // Create unique remote_id
        $newRemoteID = eZRemoteIdUtility::generate('node');
        $oldRemoteID = $newNode->attribute('remote_id');
        $newNode->setAttribute('remote_id', $newRemoteID);
        // Change parent_remote_id for object assignments
        foreach ($objAssignments as $assignment) {
            if ($assignment->attribute('parent_remote_id') == $oldRemoteID) {
                $assignment->setAttribute('parent_remote_id', $newRemoteID);
                $assignment->store();
            }
        }
        $newNode->store();
    }
    // if $keepCreator == true then keep owner of contentobject being
    // copied and creator of its published version Unchaged
    $isModified = false;
    if ($keepTime) {
        $srcPublished = $sourceObject->attribute('published');
        $newObject->setAttribute('published', $srcPublished);
        $srcModified = $sourceObject->attribute('modified');
        $newObject->setAttribute('modified', $srcModified);
        $isModified = true;
    }
    if ($keepCreator) {
        $srcOwnerID = $sourceObject->attribute('owner_id');
        $newObject->setAttribute('owner_id', $srcOwnerID);
        $isModified = true;
    }
    if ($isModified) {
        $newObject->store();
    }
    if ($allVersions) {
        // copy time of creation and midification and creator id for
        // all versions of content object being copied.
        $srcVersionsList = $sourceObject->versions();
        foreach ($srcVersionsList as $srcVersionObject) {
            $newVersionObject = $newObject->version($srcVersionObject->attribute('version'));
            if (!is_object($newVersionObject)) {
                continue;
            }
            $isModified = false;
            if ($keepTime) {
                $srcVersionCreated = $srcVersionObject->attribute('created');
                $newVersionObject->setAttribute('created', $srcVersionCreated);
                $srcVersionModified = $srcVersionObject->attribute('modified');
                $newVersionObject->setAttribute('modified', $srcVersionModified);
                $isModified = true;
            }
            if ($keepCreator) {
                $srcVersionCreatorID = $srcVersionObject->attribute('creator_id');
                $newVersionObject->setAttribute('creator_id', $srcVersionCreatorID);
                $isModified = true;
            }
            if ($isModified) {
                $newVersionObject->store();
            }
        }
    } else {
        $srcVersionObject = $sourceObject->attribute('current');
        $newVersionObject = $newObject->attribute('current');
        $isModified = false;
        if ($keepTime) {
            $srcVersionCreated = $srcVersionObject->attribute('created');
            $newVersionObject->setAttribute('created', $srcVersionCreated);
            $srcVersionModified = $srcVersionObject->attribute('modified');
            $newVersionObject->setAttribute('modified', $srcVersionModified);
            $isModified = true;
        }
        if ($keepCreator) {
            $srcVersionCreatorID = $srcVersionObject->attribute('creator_id');
            $newVersionObject->setAttribute('creator_id', $srcVersionCreatorID);
            $isModified = true;
        }
        if ($isModified) {
            $newVersionObject->store();
        }
    }
    return 0;
    // source object was copied successfully.
}
 static function loginUser($login, $password, $authenticationMatch = false)
 {
     $http = eZHTTPTool::instance();
     $db = eZDB::instance();
     if ($authenticationMatch === false) {
         $authenticationMatch = eZUser::authenticationMatch();
     }
     $loginEscaped = $db->escapeString($login);
     $passwordEscaped = $db->escapeString($password);
     $loginArray = array();
     if ($authenticationMatch & eZUser::AUTHENTICATE_LOGIN) {
         $loginArray[] = "login='******'";
     }
     if ($authenticationMatch & eZUser::AUTHENTICATE_EMAIL) {
         $loginArray[] = "email='{$loginEscaped}'";
     }
     if (count($loginArray) == 0) {
         $loginArray[] = "login='******'";
     }
     $loginText = implode(' OR ', $loginArray);
     $contentObjectStatus = eZContentObject::STATUS_PUBLISHED;
     $ini = eZINI::instance();
     $textFileIni = eZINI::instance('textfile.ini');
     $databaseName = $db->databaseName();
     // if mysql
     if ($databaseName === 'mysql') {
         $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login\n                      FROM ezuser, ezcontentobject\n                      WHERE ( {$loginText} ) AND\n                        ezcontentobject.status='{$contentObjectStatus}' AND\n                        ( ezcontentobject.id=contentobject_id OR ( password_hash_type=4 AND ( {$loginText} ) AND password_hash=PASSWORD('{$passwordEscaped}') ) )";
     } else {
         $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login\n                      FROM ezuser, ezcontentobject\n                      WHERE ( {$loginText} ) AND\n                            ezcontentobject.status='{$contentObjectStatus}' AND\n                            ezcontentobject.id=contentobject_id";
     }
     $users = $db->arrayQuery($query);
     $exists = false;
     if (count($users) >= 1) {
         foreach ($users as $userRow) {
             $userID = $userRow['contentobject_id'];
             $hashType = $userRow['password_hash_type'];
             $hash = $userRow['password_hash'];
             $exists = eZUser::authenticateHash($userRow['login'], $password, eZUser::site(), $hashType, $hash);
             // If hash type is MySql
             if ($hashType == eZUser::PASSWORD_HASH_MYSQL and $databaseName === 'mysql') {
                 $queryMysqlUser = "******";
                 $mysqlUsers = $db->arrayQuery($queryMysqlUser);
                 if (count($mysqlUsers) >= 1) {
                     $exists = true;
                 }
             }
             eZDebugSetting::writeDebug('kernel-user', eZUser::createHash($userRow['login'], $password, eZUser::site(), $hashType), "check hash");
             eZDebugSetting::writeDebug('kernel-user', $hash, "stored hash");
             // If current user has been disabled after a few failed login attempts.
             $canLogin = eZUser::isEnabledAfterFailedLogin($userID);
             if ($exists) {
                 // We should store userID for warning message.
                 $GLOBALS['eZFailedLoginAttemptUserID'] = $userID;
                 $userSetting = eZUserSetting::fetch($userID);
                 $isEnabled = $userSetting->attribute("is_enabled");
                 if ($hashType != eZUser::hashType() and strtolower($ini->variable('UserSettings', 'UpdateHash')) == 'true') {
                     $hashType = eZUser::hashType();
                     $hash = eZUser::createHash($login, $password, eZUser::site(), $hashType);
                     $db->query("UPDATE ezuser SET password_hash='{$hash}', password_hash_type='{$hashType}' WHERE contentobject_id='{$userID}'");
                 }
                 break;
             }
         }
     }
     if ($exists and $isEnabled and $canLogin) {
         eZDebugSetting::writeDebug('kernel-user', $userRow, 'user row');
         $user = new eZUser($userRow);
         eZDebugSetting::writeDebug('kernel-user', $user, 'user');
         $userID = $user->attribute('contentobject_id');
         eZUser::updateLastVisit($userID);
         eZUser::setCurrentlyLoggedInUser($user, $userID);
         // Reset number of failed login attempts
         eZUser::setFailedLoginAttempts($userID, 0);
         return $user;
     } else {
         if ($textFileIni->variable('TextFileSettings', 'TextFileEnabled') == "true") {
             $fileName = $textFileIni->variable('TextFileSettings', 'FileName');
             $filePath = $textFileIni->variable('TextFileSettings', 'FilePath');
             $defaultUserPlacement = $ini->variable("UserSettings", "DefaultUserPlacement");
             $separator = $textFileIni->variable("TextFileSettings", "FileFieldSeparator");
             $loginColumnNr = $textFileIni->variable("TextFileSettings", "LoginAttribute");
             $passwordColumnNr = $textFileIni->variable("TextFileSettings", "PasswordAttribute");
             $emailColumnNr = $textFileIni->variable("TextFileSettings", "EmailAttribute");
             $lastNameColumnNr = $textFileIni->variable("TextFileSettings", "LastNameAttribute");
             $firstNameColumnNr = $textFileIni->variable("TextFileSettings", "FirstNameAttribute");
             if ($textFileIni->hasVariable('TextFileSettings', 'DefaultUserGroupType')) {
                 $UserGroupType = $textFileIni->variable('TextFileSettings', 'DefaultUserGroupType');
                 $UserGroup = $textFileIni->variable('TextFileSettings', 'DefaultUserGroup');
             }
             if ($UserGroupType != null) {
                 if ($UserGroupType == "name") {
                     $groupName = $UserGroup;
                     $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                       FROM ezcontentobject, ezcontentobject_tree\n                                       WHERE ezcontentobject.name='{$groupName}'\n                                       AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                     $groupObject = $db->arrayQuery($groupQuery);
                     if (count($groupObject) > 0) {
                         $defaultUserPlacement = $groupObject[0]['node_id'];
                     }
                 } else {
                     if ($UserGroupType == "id") {
                         $groupID = $UserGroup;
                         $groupQuery = "SELECT ezcontentobject_tree.node_id\n                                           FROM ezcontentobject, ezcontentobject_tree\n                                           WHERE ezcontentobject.id='{$groupID}'\n                                           AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                         $groupObject = $db->arrayQuery($groupQuery);
                         if (count($groupObject) > 0) {
                             $defaultUserPlacement = $groupObject[0]['node_id'];
                         }
                     }
                 }
             }
             if ($filePath != "root" and $filePath != null) {
                 $fileName = $filePath . "/" . $fileName;
             }
             if (file_exists($fileName)) {
                 $handle = fopen($fileName, "r");
             } else {
                 // Increase number of failed login attempts.
                 if (isset($userID)) {
                     eZUser::setFailedLoginAttempts($userID);
                 }
                 return false;
             }
             while (!feof($handle)) {
                 $line = trim(fgets($handle, 4096));
                 if ($line === '') {
                     continue;
                 }
                 if ($separator == "tab") {
                     $userArray = explode("\t", $line);
                 } else {
                     $userArray = explode($separator, $line);
                 }
                 $uid = $userArray[$loginColumnNr - 1];
                 $email = $userArray[$emailColumnNr - 1];
                 $pass = $userArray[$passwordColumnNr - 1];
                 $firstName = $userArray[$firstNameColumnNr - 1];
                 $lastName = $userArray[$lastNameColumnNr - 1];
                 if ($login == $uid) {
                     if (trim($pass) == $password) {
                         $createNewUser = true;
                         $existUser = eZUser::fetchByName($login);
                         if ($existUser != null) {
                             $createNewUser = false;
                         }
                         if ($createNewUser) {
                             $userClassID = $ini->variable("UserSettings", "UserClassID");
                             $userCreatorID = $ini->variable("UserSettings", "UserCreatorID");
                             $defaultSectionID = $ini->variable("UserSettings", "DefaultSectionID");
                             $remoteID = "TextFile_" . $login;
                             $db->begin();
                             // The content object may already exist if this process has failed once before, before the eZUser object was created.
                             // Therefore we try to fetch the eZContentObject before instantiating it.
                             $contentObject = eZContentObject::fetchByRemoteID($remoteID);
                             if (!is_object($contentObject)) {
                                 $class = eZContentClass::fetch($userClassID);
                                 $contentObject = $class->instantiate($userCreatorID, $defaultSectionID);
                             }
                             $contentObject->setAttribute('remote_id', $remoteID);
                             $contentObject->store();
                             $contentObjectID = $contentObject->attribute('id');
                             $userID = $contentObjectID;
                             $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObjectID, 'contentobject_version' => 1, 'parent_node' => $defaultUserPlacement, 'is_main' => 1));
                             $nodeAssignment->store();
                             $version = $contentObject->version(1);
                             $version->setAttribute('modified', time());
                             $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
                             $version->store();
                             $contentObjectID = $contentObject->attribute('id');
                             $contentObjectAttributes = $version->contentObjectAttributes();
                             $contentObjectAttributes[0]->setAttribute('data_text', $firstName);
                             $contentObjectAttributes[0]->store();
                             $contentObjectAttributes[1]->setAttribute('data_text', $lastName);
                             $contentObjectAttributes[1]->store();
                             $user = eZUser::create($userID);
                             $user->setAttribute('login', $login);
                             $user->setAttribute('email', $email);
                             $user->setAttribute('password_hash', "");
                             $user->setAttribute('password_hash_type', 0);
                             $user->store();
                             eZUser::updateLastVisit($userID);
                             eZUser::setCurrentlyLoggedInUser($user, $userID);
                             // Reset number of failed login attempts
                             eZUser::setFailedLoginAttempts($userID, 0);
                             $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1));
                             $db->commit();
                             return $user;
                         } else {
                             $db->begin();
                             // Update user information
                             $userID = $existUser->attribute('contentobject_id');
                             $contentObject = eZContentObject::fetch($userID);
                             $parentNodeID = $contentObject->attribute('main_parent_node_id');
                             $currentVersion = $contentObject->attribute('current_version');
                             $version = $contentObject->attribute('current');
                             $contentObjectAttributes = $version->contentObjectAttributes();
                             $contentObjectAttributes[0]->setAttribute('data_text', $firstName);
                             $contentObjectAttributes[0]->store();
                             $contentObjectAttributes[1]->setAttribute('data_text', $lastName);
                             $contentObjectAttributes[1]->store();
                             $existUser = eZUser::fetch($userID);
                             $existUser->setAttribute('email', $email);
                             $existUser->setAttribute('password_hash', "");
                             $existUser->setAttribute('password_hash_type', 0);
                             $existUser->store();
                             if ($defaultUserPlacement != $parentNodeID) {
                                 $newVersion = $contentObject->createNewVersion();
                                 $newVersion->assignToNode($defaultUserPlacement, 1);
                                 $newVersion->removeAssignment($parentNodeID);
                                 $newVersionNr = $newVersion->attribute('version');
                                 $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $userID, 'version' => $newVersionNr));
                             }
                             eZUser::updateLastVisit($userID);
                             eZUser::setCurrentlyLoggedInUser($existUser, $userID);
                             // Reset number of failed login attempts
                             eZUser::setFailedLoginAttempts($userID, 0);
                             $db->commit();
                             return $existUser;
                         }
                     } else {
                         // Increase number of failed login attempts.
                         if (isset($userID)) {
                             eZUser::setFailedLoginAttempts($userID);
                         }
                         return false;
                     }
                 }
             }
             fclose($handle);
         }
     }
     // Increase number of failed login attempts.
     if (isset($userID)) {
         eZUser::setFailedLoginAttempts($userID);
     }
     return false;
 }