How to create a new user via the API (PHP)?

Author Message

Rainer Krauss

Thursday 02 July 2009 2:02:01 am

Dear all,
have been looking at source code from project extensions for some time now, and apparently I'm not getting it right..

Please, what is the source code I need to use (in ezp 4.1) to:
- create a new user, given account details such as first and last name, email and password
- assign them to a specified user group
- assign them to a specified section
?

Thanks in advance for your reply.

Best wishes,
Rainer

Xavier Langlois

Thursday 02 July 2009 9:49:11 am

Hello, here's what you're looking for
(tested on ez4.1)

function createUser($parentNodeId, $userClassId, $sectionId, $login, $email, $password, $dataTextAttributeList)
{
	$class = eZContentClass::fetch( $userClassId );
	$contentObject = $class->instantiate( 1, 1 );
	$contentObjectId = $contentObject->attribute( 'id' );
	//$contentObject->setAttribute( 'name', $login);
	$dataMap = $contentObject->dataMap();	
	foreach($dataTextAttributeList as $identifier=>$value)
	{
		$attribute = $dataMap[$identifier];
		$attribute->setAttribute( 'data_text', $value);
		$attribute->sync();
	}
	
	$nodeAssignment = eZNodeAssignment::create( array(
		'contentobject_id' => $contentObjectId,
		'contentobject_version' => $contentObject->attribute( 'current_version' ),
		'parent_node' => $parentNodeId,
		'sort_field' => 2,
		'sort_order' => 0,
		'is_main' => 1));
	$nodeAssignment->store();
	
	$version = $contentObject->version( 1 );
	$version->setAttribute( 'status', 'EZ_VERSION_STATUS_DRAFT' );
	$version->store();
		
	$user = new eZUser( $contentObject->attribute( 'id' ) );
	$user->setAttribute('login', $login );
	$user->setAttribute('email', $email );
	$hashType = eZUser::hashType() . "";
	$newHash = $user->createHash( $login, $password, eZUser::site(), $hashType );
	$user->setAttribute( "password_hash_type", $hashType );
	$user->setAttribute( "password_hash", $newHash );
	$user->store();
	
	$operationResult = eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $contentObjectId, 'version' => 1 ) );
	
	//assign section ... maybe there is a shorter way
	$object = eZContentObject::fetch( $contentObjectId, true);
	eZContentObjectTreeNode::assignSectionToSubTree( $contentObject->attribute( 'main_node_id' ), $sectionId );
	return $user;
}

//eg:  create a new user under user group "Users" (node_id=5)
$dataTextAttributeList = array('first_name'=>'Toto', 'last_name'=>'De La Motte');
$oUser = createUser( 5, 4, 2, "toto", "toto@nospam.com", 'pass', $dataTextAttributeList );

Bye

--
There were these two cows, chatting over the fence between their fields.
The first cow said, "I tell you, this mad-cow-disease is really pretty scary. Don't you think ?"
The other cow replies, "Hell, I ain't worried, I'm a duck !"

Powered by eZ Publish™ CMS Open Source Web Content Management. Copyright © 1999-2014 eZ Systems AS (except where otherwise noted). All rights reserved.