/** * 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; }
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; }
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; }
function onPublish($contentObjectAttribute, $contentObject, $publishedNodes) { $content = $contentObjectAttribute->content(); foreach ($content['relation_browse'] as $key => $relationItem) { if ($relationItem['is_modified']) { $subObjectID = $relationItem['contentobject_id']; $subObjectVersion = $relationItem['contentobject_version']; $object = eZContentObject::fetch($subObjectID); if ($object) { $class = $object->contentClass(); $time = time(); // Make the previous version archived $currentVersion = $object->currentVersion(); $currentVersion->setAttribute('status', eZContentObjectVersion::STATUS_ARCHIVED); $currentVersion->setAttribute('modified', $time); $currentVersion->store(); $version = eZContentObjectVersion::fetchVersion($subObjectVersion, $subObjectID); $version->setAttribute('modified', $time); $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', $version->attribute('version')); $object->setAttribute('is_published', true); $objectName = $class->contentObjectName($object, $version->attribute('version')); $object->setName($objectName, $version->attribute('version')); $object->store(); } if ($relationItem['parent_node_id'] > 0) { 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' => 2, 'sort_order' => 0, 'is_main' => 1)); $nodeAssignment->store(); } $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $object->attribute('id'), 'version' => $object->attribute('current_version'))); $objectNodeID = $object->attribute('main_node_id'); $content['relation_browse'][$key]['node_id'] = $objectNodeID; } else { 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' => 2, 'sort_order' => 0, 'is_main' => 1)); $nodeAssignment->store(); } } $content['relation_browse'][$key]['is_modified'] = false; } } eZObjectRelationBrowseType::storeObjectAttributeContent($contentObjectAttribute, $content); $contentObjectAttribute->setContent($content); $contentObjectAttribute->store(); }
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; }
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(); }
/** * 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; }
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; }
function cloneNodeAssignment($nextVersionNumber = 1, $contentObjectID = false) { $assignmentRow = array('contentobject_id' => $this->attribute('contentobject_id'), 'contentobject_version' => $nextVersionNumber, 'remote_id' => $this->attribute('remote_id'), 'parent_node' => $this->attribute('parent_node'), 'sort_field' => $this->attribute('sort_field'), 'sort_order' => $this->attribute('sort_order'), 'is_main' => $this->attribute('is_main'), 'parent_remote_id' => $this->attribute('parent_remote_id')); if ($contentObjectID !== false) { $assignmentRow['contentobject_id'] = $contentObjectID; } return eZNodeAssignment::create($assignmentRow); }
/** * Creates a copy of $sourceObject * @param eZContentObject $sourceObject * @return eZContentObject */ protected function createCopy(eZContentObject $sourceObject) { $db = eZDB::instance(); $db->begin(); $newObject = $sourceObject->copy(); $newObject->setAttribute('section_id', 0); $newObject->store(); $curVersion = $newObject->attribute('current_version'); $curVersionObject = $newObject->attribute('current'); $newObjAssignments = $curVersionObject->attribute('node_assignments'); // 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' => 2, 'is_main' => 1)); $nodeAssignment->store(); // publish the newly created object eZOperationHandler::execute('content', 'publish', array('object_id' => $newObject->attribute('id'), 'version' => $curVersion)); $db->commit(); return $this->forceFetchContentObject($newObject->attribute('id')); }
static function &loginUser($login, $password, $authenticationMatch = false) { #read configuration $SERVERS = array(); $ini =& eZINI::instance('imapuser.ini'); $blocks = $ini->groups(); foreach ($blocks as $key => $variables) { if (preg_match('/SERVER:(?P<server>.*)/', $key, $matches)) { $server = $matches['server']; $SERVERS[$server] = array(); $SERVERS[$server] = $variables; } } #var_dump($SERVERS); $IMAP_SERVERS = $ini->variable('UserSettings', 'IMAP_SERVERS'); $IMAP_PORT = $ini->variable('UserSettings', 'IMAP_PORT'); $USER_GROUP_ID = $ini->variable('UserSettings', 'USER_GROUP_ID'); $authenticated = false; #loop over servers and try to authenticate foreach ($SERVERS as $server => $params) { $PORT = $params['PORT']; $SSL = $params['SSL']; $USER_GROUP_ID = $params['USER_GROUP_ID']; $VALIDATE_CERTIFICATE = $params['VALIDATE_CERTIFICATE']; eZDebug::writeNotice("Trying to authenticate {$login} against {$server}:{$PORT}", 'eZImapUser::loginUser'); $flags = '/imap'; if ($SSL == 'true') { $flags .= '/ssl'; } if ($VALIDATE_CERTIFICATE == 'false') { $flags .= '/novalidate-cert'; } $identifier = '{' . $server . ':' . $PORT . $flags . '}'; #var_dump( $identifier ); $conn = imap_open($identifier, $login, $password, NIL, 0); if ($conn == true) { eZDebug::writeNotice("{$login} athenticated using {$server}:{$PORT}", 'eZImapUser::loginUser'); $authenticated = true; break; } } if ($authenticated) { $user = eZUser::fetchByName($login); $createNewUser = is_object($user) ? false : true; if ($createNewUser) { #create user $ini = eZINI::instance(); $userClassID = $ini->variable("UserSettings", "UserClassID"); $userCreatorID = $ini->variable("UserSettings", "UserCreatorID"); $defaultSectionID = $ini->variable("UserSettings", "DefaultSectionID"); $class = eZContentClass::fetch($userClassID); $contentObject = $class->instantiate($userCreatorID, $defaultSectionID); $contentObject->store(); $userID = $contentObjectID = $contentObject->attribute('id'); $version = $contentObject->version(1); $version->setAttribute('modified', time()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); $user = eZImapUser::create($userID); $user->setAttribute('login', $login); $user->setAttribute('email', $login . '@' . $server); #set unusable password $user->setAttribute('password_hash', ""); $user->setAttribute('password_hash_type', 0); $user->store(); #set group $newNodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObjectID, 'contentobject_version' => 1, 'parent_node' => $USER_GROUP_ID, 'is_main' => 1)); $newNodeAssignment->store(); $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1)); #overwrite default name, which is generated based on first name and second name which we don't have here $contentObject->setName($login); $contentObject->setAttribute('published', time()); $contentObject->setAttribute('modified', time()); $contentObject->store(); } eZUser::setCurrentlyLoggedInUser($user, $user->attribute('contentobject_id')); return $user; } else { return false; } }
$user = eZUser::currentUser(); $userID = $user->attribute('contentobject_id'); $sectionID = $parentContentObject->attribute('section_id'); $db = eZDB::instance(); $db->begin(); $object = $class->instantiate($userID, $sectionID); $ObjectID = $object->attribute('id'); $version = $object->currentVersion(); $EditVersion = $version->attribute('version'); $EditLanguage = false; $time = time(); $version->setAttribute('created', $time); $version->setAttribute('modified', $time); $object->setAttribute('modified', $time); $dataMap = $version->dataMap(); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $node->attribute('node_id'), 'sort_field' => $class->attribute('sort_field'), 'sort_order' => $class->attribute('sort_order'), 'is_main' => 1)); if ($http->hasPostVariable('AssignmentRemoteID')) { $nodeAssignment->setAttribute('remote_id', $http->postVariable('AssignmentRemoteID')); } $nodeAssignment->store(); /* handle attribute values conversion scheme: powercontent_[attributeidentifier]_[normalpostvariablename] where the attribute id in normalpostvariablename has been replaced with 'pcattributeid' */ $postVariables = $_POST; $usedAttributes = array(); foreach ($postVariables as $postName => $postValue) {
/** * Updates content object * * @param $params array( * 'object' => eZContentObject Content object * 'attributes' => array( Content object`s attributes * string identifier => string stringValue * ), * 'parentNode' => eZContentObjectTreeNode Parent node object, not necessary * 'parentNodeID' => int Content object`s parent node ID, not necessary * 'additionalParentNodeIDs' => array additionalParentNodeIDs, Additional parent node ids * 'visibility' => bool Nodes visibility * ) * @return bool true if object was updated, otherwise false */ public function updateObject($params) { $this->db->begin(); $object = $params['object']; if ($object instanceof eZContentObject === false) { $this->error('Content object is empty'); $this->db->rollback(); return false; } $this->debug('Starting update "' . $object->attribute('name') . '" object (class: ' . $object->attribute('class_name') . ') with remote ID ' . $object->attribute('remote_id')); $visibility = isset($params['visibility']) ? (bool) $params['visibility'] : true; $parentNode = false; if (isset($params['parentNode'])) { $parentNode = $params['parentNode']; } elseif (isset($params['parentNodeID'])) { $parentNode = eZContentObjectTreeNode::fetch($params['parentNodeID']); } if ($parentNode instanceof eZContentObjectTreeNode && $object->attribute('main_node') instanceof eZContentObjectTreeNode) { if ($parentNode->attribute('node_id') != $object->attribute('main_node')->attribute('parent_node_id')) { eZContentOperationCollection::moveNode($object->attribute('main_node_id'), $object->attribute('id'), $parentNode->attribute('node_id')); } } $additionalParentNodeIDs = isset($params['additionalParentNodeIDs']) ? (array) $params['additionalParentNodeIDs'] : array(); $additionalParentNodes = array(); foreach ($additionalParentNodeIDs as $nodeID) { $additionalParentNode = eZContentObjectTreeNode::fetch($nodeID); if ($additionalParentNode instanceof eZContentObjectTreeNode) { if ($parentNode instanceof eZContentObjectTreeNode && $nodeID != $parentNode->attribute('node_id')) { $additionalParentNodes[] = $additionalParentNode; } } else { $this->error('Can`t fetch additional parent node by ID: ' . $nodeID); } } if (count($additionalParentNodes) > 0) { $nodeAssigments = eZPersistentObject::fetchObjectList(eZNodeAssignment::definition(), null, array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'is_main' => 0), null, null, true); $removeNodeIDs = array(); foreach ($nodeAssigments as $assigment) { $node = $assigment->attribute('node'); if ($node instanceof eZContentObjectTreeNode) { if (in_array($node->attribute('parent_node_id'), $additionalParentNodeIDs) === false) { $removeNodeIDs[] = $node->attribute('node_id'); $assigment->purge(); } } } if (count($removeNodeIDs) > 0) { $info = eZContentObjectTreeNode::subtreeRemovalInformation($removeNodeIDs); foreach ($info['delete_list'] as $deleteItem) { $node = $deleteItem['node']; if ($node === null) { continue; } if ($deleteItem['can_remove']) { eZContentObjectTreeNode::removeSubtrees(array($node->attribute('node_id')), false); $this->debug('[Removed additional location] "' . $node->attribute('name') . '"', array('red')); } } } foreach ($additionalParentNodes as $node) { $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $node->attribute('node_id'), 'is_main' => 0)); $nodeAssignment->store(); } } $this->setObjectAttributes($object, $params['attributes']); $object->commitInputRelations($object->attribute('current_version')); $object->resetInputRelationList(); eZOperationHandler::execute('content', 'publish', array('object_id' => $object->attribute('id'), 'version' => $object->attribute('current_version'))); $this->db->commit(); $this->updateVisibility($object, $visibility); $this->debug('[Updated] "' . $object->attribute('name') . '"', array('yellow')); 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 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; }
/** * @param int $nodeID * @param int $main * @param int $fromNodeID * @param null|int $sortField * @param null|int $sortOrder * @param int|string $remoteID remote id of the node assignment * @param null|string $parentRemoteId remote id of the assigned tree node (not the parent tree node!) * * @return eZNodeAssignment|null */ function assignToNode( $nodeID, $main = 0, $fromNodeID = 0, $sortField = null, $sortOrder = null, $remoteID = 0, $parentRemoteId = null ) { if ( $fromNodeID == 0 && ( $this->attribute( 'status' ) == eZContentObjectVersion::STATUS_DRAFT || $this->attribute( 'status' ) == eZContentObjectVersion::STATUS_INTERNAL_DRAFT ) ) $fromNodeID = -1; $nodeRow = array( 'contentobject_id' => $this->attribute( 'contentobject_id' ), 'contentobject_version' => $this->attribute( 'version' ), 'parent_node' => $nodeID, 'is_main' => $main, 'remote_id' => $remoteID, 'parent_remote_id' => $parentRemoteId, 'from_node_id' => $fromNodeID ); if ( $sortField !== null ) $nodeRow['sort_field'] = $sortField; if ( $sortOrder !== null ) $nodeRow['sort_order'] = ( $sortOrder ? eZContentObjectTreeNode::SORT_ORDER_ASC : eZContentObjectTreeNode::SORT_ORDER_DESC ); $nodeAssignment = eZNodeAssignment::create( $nodeRow ); $nodeAssignment->store(); return $nodeAssignment; }
/** * Creates and returns a new node assignment that will place the object as child of node $nodeID. * * The returned assignment will already be stored in the database * * 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 int $parentNodeID The node ID of the parent node * @param bool $isMain True if the created node is the main node of the object * @param string|bool $remoteID A string denoting the unique remote ID of the assignment or \c false for no remote id. * @param int $sortField * @param int $sortOrder * @return eZNodeAssignment|null */ function createNodeAssignment( $parentNodeID, $isMain, $remoteID = false, $sortField = eZContentObjectTreeNode::SORT_FIELD_PUBLISHED, $sortOrder = eZContentObjectTreeNode::SORT_ORDER_DESC ) { $nodeAssignment = eZNodeAssignment::create( array( 'contentobject_id' => $this->attribute( 'id' ), 'contentobject_version' => $this->attribute( 'current_version' ), 'parent_node' => $parentNodeID, 'is_main' => ( $isMain ? 1 : 0 ), 'sort_field' => $sortField, 'sort_order' => $sortOrder ) ); if ( $remoteID !== false ) { $nodeAssignment->setAttribute( 'remote_id', $remoteID ); } $nodeAssignment->store(); return $nodeAssignment; }
/** * Creates initial node assignment for new content * @param SQLIContent $content * @param int $parentNodeID * @param bool $isMain * @return eZNodeAssignment * @internal */ protected function createNodeAssignmentForContent(SQLIContent $content, $parentNodeID, $isMain = false) { $contentObject = $content->getRawContentObject(); $contentClass = $contentObject->contentClass(); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObject->attribute('id'), 'contentobject_version' => $contentObject->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => $isMain ? 1 : 0, 'sort_field' => $contentClass->attribute('sort_field'), 'sort_order' => $contentClass->attribute('sort_order'))); $nodeAssignment->store(); return $nodeAssignment; }
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; }
static function publishNewUserGroup($parentNodeIDs, $newGroupAttributes, $isUtf8Encoding = false) { $newNodeIDs = array(); if (!is_array($newGroupAttributes) or !isset($newGroupAttributes['name']) or empty($newGroupAttributes['name'])) { eZDebug::writeWarning('Cannot create user group with empty name.', __METHOD__); return $newNodeIDs; } if (!is_array($parentNodeIDs) or count($parentNodeIDs) < 1) { eZDebug::writeWarning('No one parent node IDs was passed for publishing new group (group name = "' . $newGroupAttributes['name'] . '")', __METHOD__); return $newNodeIDs; } $ini = eZINI::instance(); $userGroupClassID = $ini->variable("UserSettings", "UserGroupClassID"); $userCreatorID = $ini->variable("UserSettings", "UserCreatorID"); $defaultSectionID = $ini->variable("UserSettings", "DefaultSectionID"); $userGroupClass = eZContentClass::fetch($userGroupClassID); $contentObject = $userGroupClass->instantiate($userCreatorID, $defaultSectionID); $contentObject->store(); $contentObjectID = $contentObject->attribute('id'); reset($parentNodeIDs); $defaultPlacement = current($parentNodeIDs); array_shift($parentNodeIDs); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObjectID, 'contentobject_version' => 1, 'parent_node' => $defaultPlacement, 'parent_remote_id' => uniqid('LDAP_'), 'is_main' => 1)); $nodeAssignment->store(); foreach ($parentNodeIDs as $parentNodeID) { $newNodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $contentObjectID, 'contentobject_version' => 1, 'parent_node' => $parentNodeID, 'parent_remote_id' => uniqid('LDAP_'), 'is_main' => 0)); $newNodeAssignment->store(); } $version = $contentObject->version(1); $version->setAttribute('modified', time()); $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT); $version->store(); $contentObjectAttributes = $version->contentObjectAttributes(); // find ant set 'name' and 'description' attributes (as standard user group class) $nameIdentifier = 'name'; $descIdentifier = 'description'; $nameContentAttribute = null; $descContentAttribute = null; foreach ($contentObjectAttributes as $attribute) { if ($attribute->attribute('contentclass_attribute_identifier') == $nameIdentifier) { $nameContentAttribute = $attribute; } else { if ($attribute->attribute('contentclass_attribute_identifier') == $descIdentifier) { $descContentAttribute = $attribute; } } } if ($nameContentAttribute) { if ($isUtf8Encoding) { $newGroupAttributes['name'] = utf8_decode($newGroupAttributes['name']); } $nameContentAttribute->setAttribute('data_text', $newGroupAttributes['name']); $nameContentAttribute->store(); } if ($descContentAttribute and isset($newGroupAttributes['description'])) { if ($isUtf8Encoding) { $newGroupAttributes['description'] = utf8_decode($newGroupAttributes['description']); } $descContentAttribute->setAttribute('data_text', $newGroupAttributes['description']); $descContentAttribute->store(); } $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => 1)); $newNodes = eZContentObjectTreeNode::fetchByContentObjectID($contentObjectID, true, 1); foreach ($newNodes as $newNode) { $newNodeIDs[] = $newNode->attribute('node_id'); } return $newNodeIDs; }
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; }
/** * 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 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] ); } }
/** * @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; }
$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)
/** * 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; }
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; }
static function process($module) { $http = eZHTTPTool::instance(); // you need the NodeID (parent node) if (!$http->hasPostVariable('NodeID')) { eZDebug::writeError('Missing mandatory parameter NodeID (the parent nodeid) so I know where to create it', 'powercontent/action.php'); return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel'); } $nodeID = $http->postVariable('NodeID'); if ($nodeID === 'UserNode') { // special mode: the content is put under the user's node $user = eZUser::currentUser(); $owner = eZContentObject::fetch($user->attribute('contentobject_id')); $nodeID = $owner->attribute('main_node_id'); } $node = eZContentObjectTreeNode::fetch($nodeID); if (is_object($node)) { $contentClassID = false; $contentClassIdentifier = false; $class = false; if ($http->hasPostVariable('ClassID')) { $contentClassID = $http->postVariable('ClassID'); $class = eZContentClass::fetch($contentClassID); } else { if ($http->hasPostVariable('ClassIdentifier')) { $contentClassIdentifier = $http->postVariable('ClassIdentifier'); $class = eZContentClass::fetchByIdentifier($contentClassIdentifier); } } if (is_object($class)) { $contentClassID = $class->attribute('id'); $parentContentObject = $node->attribute('object'); if ($parentContentObject->checkAccess('create', $contentClassID, $parentContentObject->attribute('contentclass_id')) == '1') { $user = eZUser::currentUser(); $userID = $user->attribute('contentobject_id'); $sectionID = $parentContentObject->attribute('section_id'); $db = eZDB::instance(); $db->begin(); $object = $class->instantiate($userID, $sectionID); $ObjectID = $object->attribute('id'); $version = $object->currentVersion(); $EditVersion = $version->attribute('version'); $EditLanguage = false; $time = time(); $version->setAttribute('created', $time); $version->setAttribute('modified', $time); $object->setAttribute('modified', $time); $dataMap = $version->dataMap(); $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $node->attribute('node_id'), 'sort_field' => $class->attribute('sort_field'), 'sort_order' => $class->attribute('sort_order'), 'is_main' => 1)); if ($http->hasPostVariable('AssignmentRemoteID')) { $nodeAssignment->setAttribute('remote_id', $http->postVariable('AssignmentRemoteID')); } $nodeAssignment->store(); /* handle attribute values conversion scheme: powercontent_[attributeidentifier]_[normalpostvariablename] where the attribute id in normalpostvariablename has been replaced with 'pcattributeid' */ $postVariables = $_POST; $usedAttributes = array(); foreach ($postVariables as $postName => $postValue) { $newPostVariable = false; $nameParts = explode('_', $postName); if (count($nameParts) > 2) { $firstNamePart = array_shift($nameParts); eZDebug::writeNotice($firstNamePart); if ($firstNamePart != 'powercontent') { continue; } $possibleAttributeIdentifier = ''; while (true) { $part = array_shift($nameParts); if (is_null($part)) { eZDebug::writeWarning('not found matching attribute: ' . $possibleAttributeIdentifier, 'defaultvalues/action.php'); break; } $possibleAttributeIdentifier = $possibleAttributeIdentifier . $part; if (array_key_exists($possibleAttributeIdentifier, $dataMap)) { eZDebug::writeNotice('found matching attribute: ' . $possibleAttributeIdentifier, 'defaultvalues/action.php'); $usedAttributes[] = $dataMap[$possibleAttributeIdentifier]; $attribID = $dataMap[$possibleAttributeIdentifier]->attribute('id'); $newPostVariable = implode('_', $nameParts); $newPostVariable = str_replace('pcattributeid', $attribID, $newPostVariable); $http->setPostVariable($newPostVariable, $postValue); break; } $possibleAttributeIdentifier = $possibleAttributeIdentifier . '_'; } } } $fileVariables = $_FILES; foreach ($fileVariables as $fileName => $fileValue) { $newFileVariable = false; $nameParts = explode('_', $fileName); if (count($nameParts) > 2) { $firstNamePart = array_shift($nameParts); eZDebug::writeNotice($firstNamePart); if ($firstNamePart != 'powercontent') { continue; } $possibleAttributeIdentifier = ''; while (true) { $part = array_shift($nameParts); if (is_null($part)) { break; } $possibleAttributeIdentifier = $possibleAttributeIdentifier . $part; if (array_key_exists($possibleAttributeIdentifier, $dataMap)) { eZDebug::writeNotice('found matching file attribute: ' . $possibleAttributeIdentifier, 'defaultvalues/action.php'); $usedAttributes[] = $dataMap[$possibleAttributeIdentifier]; $attribID = $dataMap[$possibleAttributeIdentifier]->attribute('id'); $newFileVariable = implode('_', $nameParts); $newFileVariable = str_replace('pcattributeid', $attribID, $newFileVariable); $_FILES[$newFileVariable] = $fileValue; break; } $possibleAttributeIdentifier = $possibleAttributeIdentifier . '_'; } } } if (count($usedAttributes) > 0) { $http->setPostVariable('DontNotify', 'InputStored'); if ($http->hasPostVariable('DoPublish')) { $http->setPostVariable('PublishButton', 'Publish'); } else { $http->setPostVariable('StoreButton', 'Store'); } } $db->commit(); if ($http->hasPostVariable('RedirectToMainNodeAfterPublish')) { $accessResult = $user->hasAccessTo('redirect', 'mainnode'); if ($accessResult['accessWord'] != 'no') { $http->setSessionVariable('RedirectURIAfterPublish', '/redirect/mainnode/' . $ObjectID); } } // let edit module run in the same HTTP request (no redirect!!) // I don't think this has any consequences for custom actions // which will use the content browser etc. $Result = array(); $Result['rerun_uri'] = $module->redirectionURI('content', 'edit', array($ObjectID, $EditVersion, $EditLanguage)); $module->setExitStatus(eZModule::STATUS_RERUN); return $Result; } else { return $module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel'); } } else { return $module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel'); } } else { eZDebug::writeError("Invalid node id: {$nodeID}", 'powercontent/action.php'); return $module->handleError(eZError::KERNEL_NOT_AVAILABLE, 'kernel'); } return $module->handleError(eZError::KERNEL_ACCESS_DENIED, 'kernel'); }