Share » Learn » eZ Publish » Fetching User Objects with PHP - part 2

Fetching User Objects with PHP - part 2

Monday 18 October 2010 1:38:28 am

  • Currently 3 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Putting it all together

Let's put all of what we have covered together and create a full cronjob script for exporting user information that can be run on a monthly basis. We will export all new users created by the system each month and store it in a tab delimited text file (we will not use a CSV as there is a good chance that if you are storing user address fields that they will contain commas). We will also send an email confirmation that the file has been created which will include stats on the number of new site users, the total number of active site users and the number of users who wish to be emailed.

Before we begin we need to make sure a directory exists to store our exports. Create a directory in your var folder called "user_exports" (also make sure eZ Publish can write to the directory).

 

Formatting the user data

To make our code more legible we will move the code we created in part one of this tutorial to display user details into a separate function. We will also modify the information so it is shown in a format suitable for a tab delimited file. We will be using the eZContentObjectTreeNode::subTreeByNodeID() function to extract users. Due to this we will be dealing with eZContentObjectTreeNodes and so the code in the function will reflect this:

function show_user( $userNode )
{
    // first add the id for reference:

    $return_string = $userNode->attribute( 'node_id' );
    
    // now extract the fields:
    
    $userObj  = $userNode->attribute( 'object' ); //we will handle pulling the information out of these later.
    $dataMap = $userObj->attribute( 'data_map' );
    
    //print each in turn:
    foreach( $dataMap as $key => $value )
    {
        $type = $value->dataType();
        switch( $type->DataTypeString )
        {
            case 'ezuser':
                $user_account = $dataMap['user_account']->attribute( 'content' );
                $return_string .= "\t{$user_account->attribute( 'login' )}\t{$user_account->attribute( 'email' )}";
                break;
            case 'ezstring': //for basic text & ints
            case 'eztext':
            case 'ezint':
            case 'ezfloat':
            $return_string .= $value->toString();
                break;
            case 'ezimage':
                $content = $value->attribute( 'content' );
                $displayText = $content->displayText();
                $imageAlias = $content->imageAlias( 'original' );
                $imagePath = $imageAlias['url'];
                $return_string .= "\t$displayText ($imagePath)";
                break;
        }
    }
    $return_string .= "\n";
    return $return_string;
}
 

We also need to create a header row for our data export. To make things easy for us, let's modify the code we have just created and display the key for each field instead of the field value itself:

function show_header($userNode)
{
    $return_string = "Node ID";
    
    $userObj  = $userNode->attribute( 'object' ); //we will handle pulling the information out of these later.
    $dataMap = $userObj->attribute( 'data_map' );
    
    foreach( array_keys( $dataMap ) as $key )
    {
        $return_string .= "\t$key";
    }
    $return_string .= "\n";
    return $return_string;

}
 

Fetching the user information

Now that we have the functions created to show a header and to show a user, let's put them into use and store details of all new users into a variable:

$includeClasses = array( 'user' );
$sortBy = array( "name", true ); //let's sort by name

//working out the month start and end dates for the previous month, compatible with all versions of PHP 5:
$first_of_month = strtotime( date( "Y-m-1" ) ); //this is our endtime, midnight on the first of the current month
$first_of_last_month = strtotime( '-1 month' , $first_of_month ); //our start time is one month before then.

$attributeFilter  = array( array( 'published', 'between', array( $first_of_last_month,$first_of_month ) ) );

$params = array( 'SortBy' => $sortBy,
                'ClassFilterType' => 'include',
                'ClassFilterArray' => $includeClasses,
                'AttributeFilter' => $attributeFilter);


//getting the ID of where the users sit in the cms (limiting the area eZ has to search for the objects):
$parent_node = eZContentObjectTreeNode::fetchByURLPath( 'users/members' ); //note the lowercase. Use underscores rather than hyphens if spaces are included in the path
$parent_node_id = $parent_node->attribute( 'node_id' );

$new_users = eZContentObjectTreeNode::subTreeByNodeID( $params, $parent_node_id );
$monthly_new_user_count = eZContentObjectTreeNode::subTreeCountByNodeID( $params,$parent_node_id );

/*print header info:*/
$file_content = show_header( $new_users[0] );

foreach( $new_users as $user )
{
  $file_content .= show_user( $user );
}
 

We can pull out the total number of users who have modified their details and the number of users who wish to be emailed using the code we have already looked at. I will omit repeating the code here so we can move on to the other functionality required (the full source code is available at the end of the tutorial).

 

Storing the content to file

The first bit of additional functionality we need is to store our variable to a file. We’ll do this with some standard PHP code:

//creating the file (filename based on start and end dates of the data):
$file_name = date( 'd-m-Y', $first_of_last_month ) . '_' . date( 'd-m-Y', strtotime( '-1 day' , $first_of_month )) . ".txt";
$var_path = $_SERVER['PWD'] . '/var/user_export/';
$file_path = $var_path.$file_name;

// creating the file and storing our content:
$file_pointer = fopen( $file_path, 'x' );
fwrite( $file_pointer, $file_content);
 

Sending a notification email

We now need to notify someone that the file has been stored. You will be aware that the site admin’s email is available to us through the site.ini file. Since we can extract it from here, let’s use this as our email address:

// pulling out the site admin's email address for sending the email:
$site_ini = eZIni::instance( "site.ini" );
$admin_email =$site_ini->BlockValues['MailSettings']['AdminEmail'];
 

Now we have the admin's email, let's create our email message and sent it to them. Let’s include the stats so they have details of the latest export:

//sending the email containing user stats:
$email_subject = "Users report for" . Date( 'd-m-Y', $first_of_last_month ) . ' to ' . date( 'd-m-Y', strtotime( '-1 day' , $first_of_month ) );
$email_content = 'The New Users Report from the start of  ' . date( 'd-m-Y', $first_of_last_month ) . ' to the end of ' . date( 'd-m-Y', strtotime( '-1 day' , $first_of_month ) ) . ' has been created at: ' . $file_path;
$email_content .= "\n\nHere is a summary of the user stats:\n\n";
$email_content .= 'New Users: ' . $monthly_new_user_count . "\n";
$email_content .= 'Modified Users: ' . $monthly_modified_user_count . "\n";
$email_content .= 'Users who wish to be emailed: ' . $users_to_email_count . "\n";
//sending our email with a link to our file to the site admin:
mail( $admin_email, $email_subject, $email_content ); //we don't need any real styling so let’s just use the standard php email function
 
36 542 Users on board!

Tutorial menu

Printable

Printer Friendly version of the full article on one page with plain styles

Author(s)