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>
|
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 licence@visionwt.com 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 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.
|
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
|