Importing: Update entry if it already exists

Author Message

Alex Jones

Tuesday 27 January 2004 9:39:20 am

I am moving along on my import script, but am trying to set up a check to see if an entry already exists within the database. I have figured out how to check whether or not an entry exists by comparing against a unique field (product number) in the database. The problem I am running into occurs when I try to set up my script to update an existing entry. Below is the code that I have so far, the first part of the IF statement works properly, the second is where I am confused. How do I instantiate the existing content object with the object ID? For that matter, do I need to instantiate it, or is there something else? I have pulled this code, in-part from a couple of import scripts, but I am still stumped.

$productNumberExistsArray = $db->arrayQuery( "SELECT  * 
  FROM  ezcontentobject_attribute 
  WHERE contentclassattribute_id = '$productNumberField' 
  AND data_text = '$productNumber'" 
  );

  if ( $productNumberExistsArray == null )
  {
    // Create an empty content object.
    $contentObject =& $class->instantiate( $userID, $sectionID );

    // Inform the tree of the new content object.      
    $nodeAssignment =& eZNodeAssignment::create( array(
      'contentobject_id' => $contentObject->attribute( 'id' ),
      'contentobject_version' => $contentObject->attribute( 'current_version' ),
      'parent_node' => $parentNode->attribute( 'node_id' ),
      'sort_field' => 2,
      'sort_order' => 0,
      'is_main' => 1
      )
    );

    // Store the node assignment
    $nodeAssignment->store();
  }
  else // Where I am having problems
  {
    // Retrieve the proper content object id and update the existing product entry.
    $contentObjectID = $productNumberExistsArray[0]['id'];
    $contentObject =& eZContentObject::fetch( $contentObjectID );
    $nodeAssignment =& eZNodeAssignment::create( array(
      'contentobject_id' => $contentObject->attribute( 'id' ),
      'contentobject_version' => $contentObject->attribute( 'current_version' ),
      'parent_node' => $parentNode->attribute( 'node_id' ),
      'sort_field' => 2,
      'sort_order' => 0,
      'is_main' => 1
      )
    );
  }

Any help would be greatly appreciated!

Alex

Alex
[ bald_technologist on the IRC channel (irc.freenode.net): #eZpublish ]

<i>When in doubt, clear the cache.</i>

Paul Forsyth

Wednesday 28 January 2004 7:11:21 am

if i read you right you want to update the content of an attribute with a new value.

once you have the object (fetched with its id) you just need to pull out the attribute you want, modify its content, and store that attribute. since the object referes to that attribute it is by default, updated.

paul

Alex Jones

Thursday 29 January 2004 7:49:46 am

Paul, thank you for the reply. I guess the area that I find confusing is how to do the fetch. Specifically, what should the code look like to fetch the proper data? The ID you speak of is the Object ID, right?

Thanks for the help!

Alex

Alex
[ bald_technologist on the IRC channel (irc.freenode.net): #eZpublish ]

<i>When in doubt, clear the cache.</i>

Paul Forsyth

Thursday 29 January 2004 8:40:12 am

Hmm, im wondering if we are speaking about the same thing here. I know you have this code...

Ok, once you have your object:

$contentObject =& eZContentObject::fetch( $contentObjectID );

Get the current version. This gives you access to the latest versions of each attribute:

$contentObjectVersion =& $contentObject->version( $contentObject->attribute( 'current_version' ) );

Then take the attributes from that version:

$contentObjectAttributes =& $contentObjectVersion->contentObjectAttributes();

Then search for the attribute you wish to change. You may know the id, if not find it by name:

foreach (array_keys($contentObjectAttributes) as $key)
{
    $contentObjectAttribute =& $contentObjectAttributes[$key];
    $contentClassAttribute =& $contentObjectAttribute->contentClassAttribute();

    // Each attribute has an attribute called 'name' that identifies it.
    if ($contentClassAttribute->attribute("name") == "Attribute to change")
    {
        $contentObjectAttribute->setAttribute("data_text", "My new piece of information");
        $contentObjectAttribute->store();
    }
}

Hope this helps!

paul

Paul Forsyth

Thursday 29 January 2004 8:40:45 am

Wow, huge text everywhere! Does it appear like this on IE?

paul

Alex Jones

Thursday 29 January 2004 11:20:29 am

Thanks for the info Paul! I think this will help me knock out the problem. :)

As for the text, it isn't quite as big in IE as it is on a Moz browser, but it is noticably bigger than the standard text size. This is due to the same issue that your brought up aobut the font size in Bug reports: invalid nesting of pre tags.

Alex

Alex
[ bald_technologist on the IRC channel (irc.freenode.net): #eZpublish ]

<i>When in doubt, clear the cache.</i>

Seth Cooper

Friday 30 January 2004 11:39:50 am

Alex, I'm worknig on a similar project. Would you mind posting your complete script?

Thanks.

Alex Jones

Monday 02 February 2004 8:22:28 am

Seth, below is the script that I have. It runs well from what I have been able to test, but please note a few things:
1. This will not import every type of content yet. I still need to work out how to import images, and I haven't bothered with enums, related objects and the like.
2. This is cobbled together from several sources, foremost among these is an import script that Paul F. was kind enough to send me. The license at the top of this script is the same as the one that applies to his original script. I need to do a bit more research to find the authors of the other scripts that I used, so they may be given credit where it is due. The version info and the author data on this script have not been modified from Paul's original script.
3. Because this script was pulled from several spots, the code is less than beautiful, and in some areas downright ugly. I plan to clean it up down the road, but I am posting it now so it might help others. If someone else cleans it up and/or finds a better way to accomplish some of these tasks, please be kind to post those changes to this thread.
4. This is a command-line script, meant to reside in the main eZ publish directory.
5. Make sure to change the name of the imported file on line 291, or name your file import.csv and place it in the same directory.
6. I have only tested this with a small amount of imported items (less than 25) - I have no idea how well it will work on large imports.

#!/usr/bin/php
<?php

//
// Sample import file
//
// Copyright (C) 1999-2003 Vision with Technology, All rights reserved.
//
// This file may be distributed and/or modified under the terms of the
// "GNU General Public License" version 2 as published by the Free
// Software Foundation 
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
// THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE.
//
// The "GNU General Public License" (GPL) is available at
// http://www.gnu.org/copyleft/gpl.html.
//
// Contact [email protected] if any conditions of this licencing isn't clear to
// you.
//
// Author:        Paul Forsyth
// Version:      $Id: import.php,v 1.1 2003/12/24 16:42:20 paulf Exp $

// Make sure PHP does not timeout. This value overrides the php.ini timeout value.
set_time_limit( 0 );

// Include required files
include_once( "lib/ezutils/classes/ezextension.php" );
include_once( "lib/ezutils/classes/ezmodule.php" );
include_once( 'lib/ezutils/classes/ezcli.php' );
include_once( 'kernel/classes/ezscript.php' );
include_once( 'lib/ezutils/classes/ezexecution.php' );
include_once( 'kernel/classes/ezcontentobjecttreenode.php' );
include_once( 'kernel/classes/eznodeassignment.php' );

include_once( "lib/ezxml/classes/ezxml.php" );
include_once( "lib/ezxml/classes/ezdomdocument.php" );
include_once( "lib/ezxml/classes/ezdomnode.php" );
include_once( "kernel/classes/datatypes/ezxmltext/ezxmltexttype.php");
include_once( "kernel/classes/datatypes/ezxmltext/ezxmltext.php");

// Set up the command line interface.
//
// This allows eZ to set up the PHP session correctly.

$cli =& eZCLI::instance();

// Set up the script environment.
$script =& eZScript::instance( array( 'debug-message' => '',
                                      'use-session' => false,
                                      'use-modules' => true,
                                      'use-extensions' => true ) );

$script->startup();

$endl = $cli->endlineString();
$webOutput = $cli->isWebOutput();

$script->setUseDebugOutput( false );
$script->setAllowedDebugLevels( false );
$script->setUseDebugAccumulators( false );
$script->setUseDebugTimingPoints( false );
$script->setUseIncludeFiles( false );

if ( $webOutput )
    $useColors = true;

$cli->setUseStyles( false );
$script->setDebugMessage( "\n\n" . str_repeat( '#', 36 ) . $cli->style( 'emphasize' ) . 
                        " DEBUG " . $cli->style( 'emphasize-end' )  . str_repeat( '#', 36 ) . "\n" );

$script->setUseSiteAccess( false );

$script->initialize();

$cli->output( "Running " . $cli->stylize( 'emphasize', 'import.php' ) );

// Prepare the database instance.
//
// This allows eZ to access the correct database.

$db =& eZDB::instance();
$db->setIsSQLOutputEnabled( false );

// Add a new object to the root folder
//
// The following code adds a new Folder object to the root folder.

// Use the Cutting Edge Product class
$contentClassID=14;

// Locate the new article at the default location, the root
$parentNodeID=186;

// Set the administrator as the creator of this node
$userID=218;

// Fetch the parent node
$parentNode =& eZContentObjectTreeNode::fetch( $parentNodeID );
$parentContentObject =& $parentNode->attribute( 'object' );
$sectionID = $parentContentObject->attribute( 'section_id' );

// Find the class from the id.
$class =& eZContentClass::fetch( $contentClassID );

/* -------------------- [ AJ: Begin XML Text Import ] -------------------- */

include_once( 'kernel/classes/datatypes/ezxmltext/handlers/input/ezsimplifiedxmlinput.php' );

class text2xml extends eZSimplifiedXMLInput
{
    function text2xml( &$xmlData, $contentObjectAttribute )
    {
        $this->eZSimplifiedXMLInput( $xmlData, 0, $contentObjectAttribute );
    }

  function &validateText( &$data, &$contentObjectAttribute )
    {
        $contentObjectAttributeID = $contentObjectAttribute->attribute( "id" );
        // Below is same as in the function validateInput(...) in class eZSimplifiedXMLInput
        eZDebug::writeDebug($data, "input data");
        // Set original input to a global variable
        $originalInput = "originalInput_" . $contentObjectAttributeID;
        $GLOBALS[$originalInput] = $data;

        // Set input valid true to a global variable
        $isInputValid = "isInputValid_" . $contentObjectAttributeID;
        $GLOBALS[$isInputValid] = true;
        $inputData = "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' 
                                xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/' >";
        $inputData .= "<paragraph>";
        $inputData .= $data;
        $inputData .= "</paragraph>";
        $inputData .= "</section>";

        $data =& $this->convertInput( $inputData );
        $message = $data[1];
        if ( $this->IsInputValid == false )
        {
            $GLOBALS[$isInputValid] = false;
            $errorMessage = null;
            foreach ( $message as $line )
            {
                $errorMessage .= $line .";";
            }
            $contentObjectAttribute->setValidationError( ezi18n( 'kernel/classes/datatypes',
                                                                 $errorMessage,
                                                                 'ezXMLTextType' ) );
            return EZ_INPUT_VALIDATOR_STATE_INVALID;
        }
        else
        {
            $dom = $data[0];
            $objects =& $dom->elementsByName( 'object' );
            if ( $objects !== null )
            {
                foreach ( array_keys( $objects ) as $objectKey )
                {
                    $object =& $objects[$objectKey];
                    $objectID = $object->attributeValue( 'id' );
                    $currentObject =& eZContentObject::fetch( $objectID );
                    $editVersion = $contentObjectAttribute->attribute('version');
                    $editObjectID = $contentObjectAttribute->attribute('contentobject_id');
                    $editObject =& eZContentObject::fetch( $editObjectID );
                    if ( $currentObject == null )
                    {
                        $GLOBALS[$isInputValid] = false;
                        $contentObjectAttribute->setValidationError( ezi18n( 'kernel/classes/datatypes',
                                'Object '. $objectID .' does not exist.', 'ezXMLTextType' ) );
                        return EZ_INPUT_VALIDATOR_STATE_INVALID;
                    }
                    else
                    {
                        $relatedObjects =& $editObject->relatedContentObjectArray( $editVersion );
                        $relatedObjectIDArray = array();
                        foreach ( $relatedObjects as $relatedObject )
                        {
                            $relatedObjectID = $relatedObject->attribute( 'id' );
                            $relatedObjectIDArray[] = $relatedObjectID;
                        }
                        if ( !in_array( $objectID, $relatedObjectIDArray ) )
                        {
                            $editObject->addContentObjectRelation( $objectID, $editVersion );
                        }
                    }

                    // If there are any image object with links.
                    $href = $object->attributeValueNS( 'ezurl_href',
                                'http://ez.no/namespaces/ezpublish3/image/' );
                    $urlID = $object->attributeValueNS( 'ezurl_id', 
                                'http://ez.no/namespaces/ezpublish3/image/' );

                    if ( $href != null )
                    {
                        $linkID =& eZURL::registerURL( $href );
                        $object->appendAttribute( $dom->createAttributeNodeNS(
                                'http://ez.no/namespaces/ezpublish3/image/', 'image:ezurl_id', $linkID ) );
                        $object->removeNamedAttribute( 'ezurl_href' );
                    }

                    if ( $urlID != null )
                    {
                        $url =& eZURL::url( $urlID );
                        if ( $url == null )
                        {
                            $GLOBALS[$isInputValid] = false;
                            $contentObjectAttribute->setValidationError( ezi18n( 'kernel/classes/datatypes',
                                    'Link '. $urlID .' does not exist.', 'ezXMLTextType' ) );
                            return EZ_INPUT_VALIDATOR_STATE_INVALID;
                        }
                    }
                }
            }
            $links =& $dom->elementsByName( 'link' );

            if ( $links !== null )
            {
                foreach ( array_keys( $links ) as $linkKey )
                {
                    $link =& $links[$linkKey];
                    if ( $link->attributeValue( 'id' ) != null )
                    {
                        $linkID = $link->attributeValue( 'id' );
                        $url =& eZURL::url( $linkID );
                        if ( $url == null )
                        {
                            $GLOBALS[$isInputValid] = false;
                            $contentObjectAttribute->setValidationError( ezi18n( 'kernel/classes/datatypes',
                                    'Link '. $linkID .' does not exist.', 'ezXMLTextType' ) );
                            return EZ_INPUT_VALIDATOR_STATE_INVALID;
                        }
                    }
                    if ( $link->attributeValue( 'href' ) != null )
                    {
                        $url = $link->attributeValue( 'href' );
                        $linkID =& eZURL::registerURL( $url );
                        $link->appendAttribute( $dom->createAttributeNode( 'id', $linkID ) );
                        $link->removeNamedAttribute( 'href' );
                    }
                }
            }

            $domString = $dom->toString();

   eZDebug::writeDebug($domString, "unprocessed xml");
   $domString = preg_replace( "#<paragraph> </paragraph>#", "<paragraph> </paragraph>", $domString );
   $domString = str_replace ( "<paragraph />" , "", $domString );
   $domString = str_replace ( "<line />" , "", $domString );
   $domString = str_replace ( "<paragraph></paragraph>" , "", $domString );
   //$domString = preg_replace( "#>[W]+<#", "><", $domString );
   $domString = preg_replace( "#<paragraph> </paragraph>#", "<paragraph />", $domString );
   $domString = preg_replace( "#<paragraph></paragraph>#", "", $domString );

   $domString = preg_replace( "#[\n]+#", "", $domString );
   $domString = preg_replace( "#</LINE>#", "\n", $domString );
   $domString = preg_replace( "#<PARAGRAPH>#", "\n\n", $domString );
   eZDebug::writeDebug($domString, "domstring");
            $xml = new eZXML();
            $tmpDom =& $xml->domTree( $domString, array( 'CharsetConversion' => false ) );
//                 $domString = $tmpDom->toString();
            $domString = eZXMLTextType::domString( $tmpDom );

            eZDebug::writeDebug($domString, "stored xml");
            $contentObjectAttribute->setAttribute( "data_text", $domString );
            $contentObjectAttribute->setValidationLog( $message );

            $paragraphs = $tmpDom->elementsByName( 'paragraph' );

            $classAttribute =& $contentObjectAttribute->contentClassAttribute();
            if ( $classAttribute->attribute( "is_required" ) == true )
            {
                if ( count( $paragraphs ) == 0 )
                    return EZ_INPUT_VALIDATOR_STATE_INVALID;
                else
                    return EZ_INPUT_VALIDATOR_STATE_ACCEPTED;
            }
            else
                return EZ_INPUT_VALIDATOR_STATE_ACCEPTED;
        }
        return EZ_INPUT_VALIDATOR_STATE_INVALID;
    }    
}

/* -------------------- [ AJ: End  XML Text Import ] -------------------- */

/* -------------------- [ AJ: Begin Code to import tab delimited list ] -------------------- */

$ImportRow = 1;
// AJ: Change import.csv to the name/path of the file to be imported.
$ImportHandle = fopen("import.csv", "r");
	while ($ImportData = fgetcsv($ImportHandle, 1000, "	")) {
   $ImportNum = count($ImportData);
   $ImportRow++;


/* -------------------- [ AJ: Begin Object Existence Check ] --------------------
   Check to detect whether or not the imported item already exists by comparing the 
   item number against the product number field.
   If the item number exists, retrieve and assign its object id to the imported entry
   If it does not exist, assign a new object id to the imported entry
------------------------------------------------------------------------------ */


    // The Product Number Field Number
    $productNumberField = '153' ;
	// The Product Number to Compare
	$productNumber = $ImportData[1];
	$cli->output( '$ImportData[1] = ' . $ImportData[1] );
	
    // Check if the item has been imported.
	$productNumberExistsArray = $db->arrayQuery( "SELECT  * 
                                                      FROM  ezcontentobject_attribute 
                                                      WHERE contentclassattribute_id = '$productNumberField' 
                                                      AND data_text = '$productNumber'" );

	if ( $productNumberExistsArray == null )
    {
			$cli->output( ' 
------------------------------------------------------------------
			 ');
		// Create a new content object
		$cli->output( $productNumber . ' is not in the system. Add it.' );

		// Create an empty content object.
		$contentObject =& $class->instantiate( $userID, $sectionID );

		// Inform the tree of the new content object.      
		$nodeAssignment =& eZNodeAssignment::create( array(
			'contentobject_id' => $contentObject->attribute( 'id' ),
			'contentobject_version' => $contentObject->attribute( 'current_version' ),
			'parent_node' => $parentNode->attribute( 'node_id' ),
			'sort_field' => 2,
			'sort_order' => 0,
			'is_main' => 1
			)
		);

		// Store the node assignment
		$nodeAssignment->store();

	// Now fetch the latest version of the object.
	$contentObjectVersion =& $contentObject->version( $contentObject->attribute( 'current_version' ) );
	$contentObjectVersion->setAttribute( 'status', EZ_VERSION_STATUS_DRAFT );
	$contentObjectVersion->store();

	// Get the attributes
	$contentObjectAttributes =& $contentObjectVersion->contentObjectAttributes();

	// AJ: Output the Object's ID to the screen 
	$cli->output( "Object ID: " . $contentObject->attribute( 'id' ) );
		}
		else 
		{
			// Retrieve the proper content object id and update the existing product entry.
			
			$cli->output( ' 
------------------------------------------------------------------
			 ');
			$cli->output( $productNumber . ' is in the system. Update it. ' );
    	    $contentObjectID = $productNumberExistsArray[0]['contentobject_id'];
	        $contentObject =& eZContentObject::fetch( $contentObjectID );
			$contentObjectVersion =& $contentObject->version( $contentObject->attribute( 'current_version' ) );
			$contentObjectAttributes =& $contentObjectVersion->contentObjectAttributes();
			
				$cli->output( ' ---------------------------------------------- ');
				$cli->output( '  $contentObjectID = ' . $contentObjectID );
				$cli->output( '  $contentObject = ' . $contentObject );
				$cli->output( '  $contentObjectVersion = ' . $contentObjectVersion );
				$cli->output( '  $contentObjectAttributes = ' . $contentObjectAttributes );
				$cli->output( ' ---------------------------------------------- ');
	        
		}

/* -------------------- [ AJ: End Object Existence Check ] -------------------- */

	// Set specific content attribute information from the version parameters. 
	foreach (array_keys($contentObjectAttributes) as $key)
	{
		$contentObjectAttribute =& $contentObjectAttributes[$key];
		$contentClassAttribute =& $contentObjectAttribute->contentClassAttribute();

		// Each attribute has an attribute called 'name' that identifies it.    
	    if ($contentClassAttribute->attribute("name") == "Name")
	    {
    		$contentObjectAttribute->setAttribute("data_text", "$ImportData[0]");
    		$contentObjectAttribute->store();
    		$cli->output( '  $contentObjectAttribute->setAttribute("data_text", "' . $ImportData[0] . '");' );
    	}
	    if ($contentClassAttribute->attribute("name") == "Description")
    	{
    		$contentObjectAttribute->setAttribute("data_text", "$ImportData[2]");
	    	$contentObjectAttribute->store();
    		$cli->output( '  $contentObjectAttribute->setAttribute("data_text", "' . $ImportData[2] . '");' );
	    }
    	if ($contentClassAttribute->attribute("name") == "Product nr.")
	    {
    		$contentObjectAttribute->setAttribute("data_text", "$ImportData[1]");
    		$contentObjectAttribute->store();
    		$cli->output( '  $contentObjectAttribute->setAttribute("data_text", "' . $ImportData[1] . '");' );
    	}
	    if ($contentClassAttribute->attribute("name") == "Price")
    	{
	    	$contentObjectAttribute->setAttribute("data_float", "$ImportData[3]");
    		$contentObjectAttribute->store();
    		$cli->output( '  $contentObjectAttribute->setAttribute("data_float", "' . $ImportData[3] . '");' );
	    }
	    if ($contentClassAttribute->attribute("name") == "Information")
    	{
            $dummy = "";
			$data = $ImportData[4];
            $converter = new text2xml( $dummy, 0, $contentObjectAttribute );
            $converter->validateText( $data, $contentObjectAttribute );
            $contentObjectAttribute->SetAttribute( 'data_int', EZ_XMLTEXT_VERSION_TIMESTAMP );
            $contentObjectAttribute->store();
	    $cli->output( 'Data:' . $data);
		}
	}

	// Publish the object.
	include_once( 'lib/ezutils/classes/ezoperationhandler.php' );
	$operationResult = eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $contentObject->attribute( 'id' ),
                                   'version' => $contentObject->attribute( 'current_version' ) ) );
	}
	fclose($ImportHandle);

/* -------------------- [ AJ: End Code to import CSV ] -------------------- */

// Clean up the script environment.
$script->shutdown();
?> 

 

Alex
[ bald_technologist on the IRC channel (irc.freenode.net): #eZpublish ]

<i>When in doubt, clear the cache.</i>

Hardy Pottinger

Wednesday 28 April 2004 12:36:59 pm

Thank you very much for posting this code, it's proving to be very helpful. I'm running into a snag, though, because I can only run this script in a web context, and I'd really like to be able to use the command-line for this kind of thing. The problem stems from the fact that I can't figure out how to tell the script what database to use. I believe I need to do something with this line:

$script->setUseSiteAccess( false );

but, I've tried both just a site name:

$script->setUseSiteAccess( "name_of_my_site" );

as well as a path:

$script->setUseSiteAccess( "settings/siteaccess/name_of_my_site/site.ini.append" );

No luck yet. Am I barking up the right tree here? Am I missing something really obvious?

Alex Jones

Wednesday 28 April 2004 1:17:26 pm

Hrrrm, well, I'm not sure. I only had to worry about one database with my set up so I didn't have to deal with choosing between different databases. The only other thing I could think of might be:

$script->setUseSiteAccess( 'siteaccess' );

Alex

Alex
[ bald_technologist on the IRC channel (irc.freenode.net): #eZpublish ]

<i>When in doubt, clear the cache.</i>

Hardy Pottinger

Wednesday 28 April 2004 1:54:39 pm

I tried, no joy. From reading the script class code, it looks like this method sets the SiteAccess value, which I think would need to be the path to the siteaccess.

I've just tried setting the main settings/site.ini file to reference the database, still no luck. Here's the error message I see when I run from a command line:

X-Powered-By: PHP/4.1.2
Content-type: text/html

Running broken_import_script.php

Fatal error: eZ publish did not finish it's request
The execution of eZ publish was abruptly ended, the debug output is present below.

[no debug output]

If I hit this script from the web, it runs perfectly...

FWIW, I'm using a name-based vhost for this site. I've always installed eZPublish 3 via the install wizard, so in theory this is all standard stuff... there ought to be a way to get the script object to know what site I'm talking about.

Paul Forsyth

Wednesday 28 April 2004 2:34:20 pm

Have you tried:

$script->setUseSiteAccess( 'user' );

paul

--
http://www.visionwt.com

Hardy Pottinger

Wednesday 28 April 2004 2:44:34 pm

nope, 'user' produces the same output on the command line...

X-Powered-By: PHP/4.1.2
Content-type: text/html

Running broken_import_script.php

Fatal error: eZ publish did not finish it's request
The execution of eZ publish was abruptly ended, the debug output is present below.

Paul Forsyth

Wednesday 28 April 2004 3:28:59 pm

Another way may be to run one of the ez scripts, but modify it to print out the value of $siteaccess. This might help to show what range of values the system expects.

paul

--
http://www.visionwt.com

Hardy Pottinger

Wednesday 28 April 2004 11:19:49 pm

Thanks for the suggestion, but no luck. I've been all over the kernel/lib code tonight, and it looks like my understanding of

$script->setUseSiteAccess( 'name_of_site_e.g._intranet' );

is correct. If you look at the access.php file in the root of ezpublish, you'll see the code that's being called (look at function changeAccess( $access ), which is called by kernel/classes/ezscript.php ). It's definitely supposed to provide the connection information, so that later calls to ezdb will work.

I've tried passing database parameters directly to ezdb like this:

// this shouldn't be necessary, but I'm grasping at straws here:
$defaultDatabaseParameters = array( 'server' => 'localhost',
                                    'user' => 'my_user_name',
                                    'password' => 'my_password',
                                    'database' => 'my_database'
                                  );

$cli->output( 'getting ready to access the DB ' );
$db =& eZDB::instance(false, $defaultDatabaseParameters );
$db->setIsSQLOutputEnabled( false );
$cli->output( 'I\'ve got the DB! ' );

but this is the output I see on the command line:

X-Powered-By: PHP/4.1.2
Content-type: text/html

Running broken_import_script.php
getting ready to access the DB

Fatal error: eZ publish did not finish it's request
The execution of eZ publish was abruptly ended, the debug output is present below.

So, the issue is that I can't seem to get ezdb to crack open a database when run from the command line.

Would there be any other reason why running a script from the command line would fail to connect to a DB, while hitting it from the web works just fine?

(as an aside, the fact that there's no debug output for database connectivity problems like this is worrisome)

I can live with hitting these scripts from the web, but it will bother me every time I have to do it. And it's one more thing I have to worry about securing.

steve walker

Monday 13 September 2004 5:22:16 am

Alex,

I want to try to use this script import product information that would be a csv file exported from xl.

Would there be any chance of some pointers in terms of setting up this script to do that, and possibly a demo csv file so I can get some idea of whats involved in the implementation.

Also, what was the end result of this script? Have you got it working as you wanted in a lived environment?

Regards, Steve.

http://www.oneworldmarket.co.uk

Siniša Šehović

Tuesday 05 October 2004 1:13:24 am

Hi ppl :-)

I have figured out how to import CSV file into eZP and it works great.
Now I'm stuck with something.
<b>Please help!</b>

Don't know how to update user account information in user class?!?
I want to import login, email and generic password but don't know how to do it with SetAttribute?

Best regards,
Sinisa

---
If at first you don't succeed, look in the trash for the instructions.

Paul Forsyth

Tuesday 05 October 2004 2:09:34 am

Heres a code snippet for creating/importing a user:

$ini =& eZINI::instance();

$userClassID = $ini->variable( "UserSettings", "UserClassID" );
$class =& eZContentClass::fetch( $userClassID );

$userCreatorID = $ini->variable( "UserSettings", "UserCreatorID" );
$defaultSectionID = $ini->variable( "UserSettings", "DefaultSectionID" );
$defaultUserPlacement = $ini->variable( "UserSettings", "DefaultUserPlacement" );

$contentObject =& $class->instantiate( $userCreatorID, $defaultSectionID, false);

$nodeAssignment =& eZNodeAssignment::create( array(
                                                   'contentobject_id' => $contentObject->attribute( 'id' ),
                                                   'contentobject_version' => 1,
                                                   'parent_node' => $defaultUserPlacement,
                                                   'is_main' => 1
                                                  )
                                           );
$nodeAssignment->store();
    
// Set a status for the content object version
$contentObjectVersion =& $contentObject->version($contentObject->attribute( 'current_version' ) );
$contentObjectVersion->setAttribute( 'status', EZ_VERSION_STATUS_DRAFT);
$contentObjectVersion->store();

// Set the members attributes
$contentObjectAttributes =& $contentObject->attribute('data_map');

$firstNameAttribute = $contentObjectAttributes['first_name'];
$lastNameAttribute = $contentObjectAttributes['last_name'];
$userAccountAttribute = $contentObjectAttributes['user_account']->content();

// Now set the details
$firstNameAttribute->setAttribute("data_text", "Enter first name");
$firstNameAttribute->store();
    
$lastNameAttribute->setAttribute("data_text", "Enter second name");
$lastNameAttribute->store();
    
$userAccountAttribute->setAttribute("login", "Choose login");
$userAccountAttribute->setAttribute("email", "Choose email");

// Entered md5 sum of 'publish'. Replace with hash of your own. Make sure the hash type matches.
$userAccountAttribute->setAttribute("password_hash", "9b6d0bb3102b87fae57bc4a39149518e");
    
// Keep the password type as 2. This is the default for eZ publish but look in ezuser.php for more options.
$userAccountAttribute->setAttribute("password_hash_type", 2);
$userAccountAttribute->store();

// Now publish the object.
$operationResult = eZOperationHandler::execute( 'content', 
                                                'publish',
                                                array( 'object_id' => $contentObject->attribute( 'id' ),
                                                       'version' => $contentObject->attribute('current_version' ) ) );

paul

Siniša Šehović

Tuesday 05 October 2004 11:47:17 pm

Hi Paul

Thanx for your reply.
That works great with some modification!

Thanx again!!!

Best regards,
Sinisa

---
If at first you don't succeed, look in the trash for the instructions.

Siniša Šehović

Thursday 07 October 2004 12:40:17 am

Hi Paul,

I have one problem now after importing data into eZp.
Can't login. Getting error about wrong login or password but right hash is in table (seen by phpmyadmin).

$userAccountAttribute->setAttribute("password_hash", "83c0009fdf92e9bbbde59df5488ff315");

Do I have to import hash into check password field too?(or that check field is only for comparison in user class)

Best regards,
Sinisa

---
If at first you don't succeed, look in the trash for the instructions.

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