Technology | Web

Manipulating ez publish content in PHP

One of the most common tasks when developing an eZ Publish extension is creating, editing and removing content objects in PHP. eZ Publish’s standard features has the ability to accomplish this:

However, the above functionality does not always meet all the requirements.

eZContentFunctions

Using eZContentFunctions::createAndPublishObject, you can easly create an object:

Source code    
  1. <?php
  2. $xmlDeclaration = '<?xml version="1.0" encoding="utf-8"?>
  3.     <section xmlns:image="http://ez.no/namespaces/ezpublish3/image/"
  4.         xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/"
  5.         xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/">';
  6.  
  7. $params = array(
  8.     'creator_id'       => 14,
  9.     'class_identifier' => 'article',
  10.     'parent_node_id'   => 317,
  11.     'attributes'       => array(
  12.         'title'             => 'Test article',
  13.         'short_description' => 'Some short description',
  14.         'body'              => $xmlDeclaration . '<paragraph>This is the body</paragraph></section>',
  15.         'image'             => 'path_to_file/image.jpg'
  16.     )
  17. );
  18. $contentObject = eZContentFunctions::createAndPublishObject( $params );
  19. ?>

Using eZContentFunctions::updateAndPublishObject, any content object can be easly updated:

Source code    
  1. <?php
  2. $xmlDeclaration = '<?xml version="1.0" encoding="utf-8"?>
  3.     <section xmlns:image="http://ez.no/namespaces/ezpublish3/image/"
  4.         xmlns:xhtml="http://ez.no/namespaces/ezpublish3/xhtml/"
  5.         xmlns:custom="http://ez.no/namespaces/ezpublish3/custom/">';
  6.  
  7. $object = eZContentObject::fetch( 1207 );
  8. $params = array(
  9.     'remote_id'  => md5( microtime( true ) ),
  10.     'language'   => 'ger-DE',
  11.     'attributes' => array(
  12.         'title' => 'New title',
  13.         'body'  => $xmlDeclaration . '<paragraph>New article body</paragraph></section>',
  14.         'image' => 'path_to_file/new_image.jpg'
  15.     )
  16. );
  17. eZContentFunctions::updateAndPublishObject( $contentObject, $params );
  18. ?>

As you can see, the standard object manipulation functions have their drawbacks:

  • Inability to set language when the object is created
  • Inconvenience in working with ezxmltext attributes (it is not possible to specify html)
  • Inability to work only with locally uploaded files (ezimage, ezbinaryfile, ezmedia datatypes)
  • Inability to set additional location when creating or updating an object
  • Inability to change node location when updating an object
  • Lack of a debug functionality. If you are using this function in command line scripts, you’ll need to write additonal code to debug creating or updating flows
  • Each time an object is updated, a new version is created. When a content object is updated, it is often better to work with the current version versus creating new ones.

nxc_powercontent

nxc_powercontent extension aims to remove all of the above disadvantages. It provides nxcPowerContent PHP class. This class brings extended functionallity to create/update/remove eZ Publish content. The key features are:

  • Ability to download files from external resources when creating or updating objects
  • Ability to specify HTML for ezxmltext attributes
  • Ability to set/change locations (main and additional)
  • A debug functionality is built in – it’s convenient to use in the command line scripts
  • When an object is updated no new version is created

 Usage examples

Source code    
  1. <?php
  2. // Login as admin user
  3. $ini           = eZINI::instance();
  4. $userCreatorID = $ini->variable( 'UserSettings', 'UserCreatorID' );
  5. $user          = eZUser::fetch( $userCreatorID );
  6. if( ( $user instanceof eZUser ) === false ) {
  7. 	$cli->error( 'Cannot get user object by userID = "' . $userCreatorID . '". ( See site.ini [UserSettings].UserCreatorID )' );
  8. 	$script->shutdown( 1 );
  9. }
  10. eZUser::setCurrentlyLoggedInUser( $user, $userCreatorID );
  11.  
  12. /**
  13.  * Creating new nPower Content,  cli variable should be skipped if this code is not
  14.  * executed as command line script:
  15.  * $pc  = new nxcPowerContent();
  16.  **/
  17. $cli = eZCLI::instance();
  18. $pc  = new nxcPowerContent( $cli );
  19. $separator = str_pad( '', 80, '-' );
  20.  
  21. /**
  22.  * Publishing new article in node 156 with remote id "pc_test_article". Published article
  23.  * will have additional locations in the nodes 157 and 158.
  24.  **/
  25. $params = array(
  26. 	'classIdentifier'         => 'article',
  27. 	'remoteID'                => 'pc_test_article',
  28. 	'parentNodeID'            => 156,
  29. 	'additionalParentNodeIDs' => array( 157, 158 ),
  30. 	'attributes'              => array(
  31. 		'title' => 'Test Article',
  32. 		'intro' => '<h1>Header</h1><p>short description</p>',
  33. 		'body'  => '<p>Body</p><ul><li>list item</li><li>list item</li></ul>',
  34. 		'image' => 'http://blog.softheme.com/wp-content/uploads/2012/07/olympic_games_2012.png'
  35. 	)
  36. );
  37. $object = $pc->createObject( $params );
  38. $cli->output( $separator );
  39.  
  40. /**
  41.  * Publishing new folder in node 156 in English (American) language with remote id
  42.  * "pc_test_folder". It also will have additional location in the node 158. All
  43.  * assigned nodes will be hidden.
  44.  **/
  45. $params = array(
  46. 	'classIdentifier' => 'folder',
  47. 	'remoteID'        => 'pc_test_folder',
  48. 	'parentNodeID'    => 156,
  49. 	'additionalParentNodeIDs' => array( 158 ),
  50. 	'languageLocal'   => 'eng-US',
  51. 	'attributes'      => array(
  52. 		'name' => 'Test folder'
  53. 	),
  54. 	'visibility'      => false
  55. );
  56. $object = $pc->createObject( $params );
  57. $cli->output( $separator );
  58.  
  59. /**
  60.  * Trying to publish object of not existing content class.
  61.  **/
  62. $params = array(
  63. 	'classIdentifier' => 'not_exisitng_class',
  64. 	'parentNodeID'    => 156,
  65. 	'attributes'      => array(
  66. 		'name' => 'Test'
  67. 	)
  68. );
  69. $object = $pc->createObject( $params );
  70. $cli->output( $separator );
  71.  
  72. /**
  73.  * Trying to publish object under not existing node.
  74.  **/
  75. $params = array(
  76. 	'classIdentifier' => 'folder',
  77. 	'parentNodeID'    => 99999,
  78. 	'attributes'      => array(
  79. 		'name' => 'Test'
  80. 	)
  81. );
  82. $object = $pc->createObject( $params );
  83. $cli->output( $separator );
  84.  
  85. /**
  86.  * Trying to publish object with exisiting remote id.
  87.  **/
  88. $params = array(
  89. 	'classIdentifier' => 'folder',
  90. 	'remoteID'        => 'pc_test_folder',
  91. 	'parentNodeID'    => 156,
  92. 	'attributes'      => array(
  93. 		'name' => 'Test'
  94. 	)
  95. );
  96. $object = $pc->createObject( $params );
  97. $cli->output( $separator );
  98.  
  99. /**
  100.  * Moving article to 231 node (preivous it`s main location was 156) and leave
  101.  * only 158 additional location. It also changes it`s image attribute.
  102.  **/
  103. $object = eZContentObject::fetchByRemoteID( 'pc_test_article' );
  104. $params = array(
  105. 	'object'                  => $object,
  106. 	'parentNodeID'            => 231,
  107. 	'additionalParentNodeIDs' => array( 158 ),
  108. 	'attributes'              => array(
  109. 		'image' => 'http://discovery-intour.com.ua/images/tours_excur.1310461569.1.b.jpg'
  110. 	)
  111. );
  112. $pc->updateObject( $params );
  113. $cli->output( $separator );
  114.  
  115. /**
  116.  * Updating folder`s short_description attribute and unhide all assigned to it nodes.
  117.  **/
  118. $object = eZContentObject::fetchByRemoteID( 'pc_test_folder' );
  119. $params = array(
  120. 	'object'     => $object,
  121. 	'attributes' => array(
  122. 		'short_description' => '<p>Some short description</p>'
  123. 	)
  124. );
  125. $pc->updateObject( $params );
  126. $cli->output( $separator );
  127.  
  128. /**
  129.  * Removing objects with all its locations.
  130.  **/
  131. $object = eZContentObject::fetchByRemoteID( 'pc_test_folder' );
  132. $pc->removeObject( $object );
  133. $cli->output( $separator );
  134. $object = eZContentObject::fetchByRemoteID( 'pc_test_article' );
  135. $pc->removeObject( $object );
  136. $cli->output( $separator );
  137. ?>

If the following script is ran from the command line, you will receive the following output:

Source code    
  1. $ php ./bin/php/ezexec.php powercontent_usage_examples.php
  2. Starting create object (class: Article) with remote ID pc_test_article in main node: 156
  3. [Created] "Test Article" (Node ID: 252)
  4. --------------------------------------------------------------------------------
  5. Starting create object (class: Folder) with remote ID pc_test_folder in main node: 156
  6. [Created] "Test folder" (Node ID: 255)
  7. --------------------------------------------------------------------------------
  8. Can`t fetch class by Identifier: not_exisitng_class
  9. --------------------------------------------------------------------------------
  10. Can`t fetch parent node by ID: 99999
  11. --------------------------------------------------------------------------------
  12. Object "Test folder" (class: Folder) with remote ID pc_test_folder allready exist.
  13. --------------------------------------------------------------------------------
  14. Starting update "Test Article" object (class: Article) with remote ID pc_test_article
  15. [Removed additional location] "Test Article"
  16. [Updated] "Test Article"
  17. --------------------------------------------------------------------------------
  18. Starting update "Test folder" object (class: Folder) with remote ID pc_test_folder
  19. [Updated] "Test folder"
  20. --------------------------------------------------------------------------------
  21. Removing "Test folder" object (class: Folder) with remote ID pc_test_folder
  22. [Removed] "Test folder", Node ID: 255
  23. [Removed] "Test folder", Node ID: 256
  24. --------------------------------------------------------------------------------
  25. Removing "Test Article" object (class: Article) with remote ID pc_test_article
  26. [Removed] "Test Article", Node ID: 252
  27. [Removed] "Test Article", Node ID: 254
  28. --------------------------------------------------------------------------------

  We hope the nxc_powercontent extension will make life a little easier for developers. Comments and suggestions are welcome.

Print this post

8 Responses to "Manipulating ez publish content in PHP"

  1. Nicolas   on Thursday, August 16

    Thanks for sharing Serhey !

    (reply)
  2. Bruno CHIREZ   on Friday, August 31

    You should use the dedicated eZ Publish class to convert your html to ezxml.

    $XMLContent = ‘Body content';
    $parser = new eZSimplifiedXMLInputParser();
    $parser->setParseLineBreaks(true);
    $document = $parser->process($XMLContent);
    $xmlString = eZXMLTextType::domString($document);

    (reply)
  3. max   on Thursday, September 6

    Thanks for extension)

    (reply)
  4. David Hohl   on Friday, October 5

    Great job!
    thank you

    (reply)
  5. Jérôme Vieilledent   on Friday, October 5

    You can also use SQLIImport and its simplified content API : https://github.com/lolautruche/SQLIImport/tree/master/doc

    (reply)
  6. Hang Vo   on Wednesday, March 27

    Thank for sharing!!!

    (reply)
  7. Anele Ivanova   on Tuesday, April 16

    Hi,

    Recently I came across some great articles on your site.
    The other day, I was discussing (http://blog.nxcgroup.com/2012/manipulating-ez-publish-content-in-php/#.UW0iJKKBk7)with my colleagues and they suggested I submit an article of my own. Your site is just perfect for what I have written!
    Would it be ok to submit the article? It is free of charge, of course!

    Let me know what you think
    Contact me at anelieivanova@gmail.com

    Regards
    Anele Ivanova

    (reply)
  8. Radek   on Wednesday, September 11

    ‘Using eZContentFunctions::createAndPublishObject, you can easly create an object: ‘

    Your code is amatore code
    You should write somthing like that:

    $text = $http->variable(‘input_name’);

    $parser = new eZOEInputParser();
    $document = $parser->process( $text );

    // Remove last empty paragraph (added in the output part)
    $parent = $document->documentElement;
    $lastChild = $parent->lastChild;
    while( $lastChild && $lastChild->nodeName !== ‘paragraph’ )
    {
    $parent = $lastChild;
    $lastChild = $parent->lastChild;
    }

    if ( $lastChild && $lastChild->nodeName === ‘paragraph’ )
    {
    $textChild = $lastChild->lastChild;
    // $textChild->textContent == ” ” : string(2) whitespace in Opera
    if ( !$textChild ||
    ( $lastChild->childNodes->length == 1 &&
    $textChild->nodeType == XML_TEXT_NODE &&
    ( $textChild->textContent == ” ” || $textChild->textContent == ‘ ‘ || $textChild->textContent == ” || $textChild->textContent == ‘ ‘ ) ) )
    {
    $parent->removeChild( $lastChild );
    }

    $xmltext = eZXMLTextType::domString( $document );

    after this code write
    $params = …
    and create an object
    eZContentFunctions::createAndPublishObject( $params );

    (reply)

Reply to Radek

Get latest news