<?php
set_time_limit ( 0 ); //ensure the script does not time out

require 'autoload.php';//make sure relevant eZ Classes can be loaded

$cli = eZCLI::instance();//provides interface with CLI

//Setting up the script object itself:
$script = eZScript::instance( array( 'description' =>  "eZ Publish user export.\n\n" .
	                                                   "Methods of exporting user information from eZ Publish \n" .
	                                                   "\n",
	                                 'use-session' => false,
	                                 'use-modules' => true,
	                                 'use-extensions' => true,
									 'debug-output' => true,
									 'debug-message' =>true

	                                     ) );

$script->startup();
$script->initialize();

// let's pull out the user fields from a user object, since we will have a lot of them anyway:
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;
}


function show_user( $userNode )
{
	//first echo 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':
				$return_string .= "\t{$value->attribute( 'data_text' )}";
				break;
			case 'ezint':
				$return_string .= "\t{$value->attribute( 'data_int' )}";
				break;
			case 'ezfloat':
				$return_string.="\t{$value->attribute( 'data_float' )}";
				break;
			case 'ezimage':
				$content = $value->attribute( 'content' );
				$displayText = $content->displayText();
				$imageAlias = $content->imageAlias('original');
				$imagePath = $imageAlias['url'];
				$return_string.="$displayText ($imagePath)";

				//print_r($value->content());
				break;
		}
	}
	$return_string.="\n";
	return $return_string;

}

/* ensuring the current user has the rights to the user information: */
$user = eZUser::fetchByName( 'admin' );
eZUser::setCurrentlyLoggedInUser( $user, $user->attribute( 'contentobject_id' ) );

/* Users created last month */
$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: */
if ( $monthly_new_user_count )
{
	$file_content = show_header( $new_users[0] );

	foreach( $new_users as $user ) //add each user to our variable:
	{
	   $file_content .= show_user( $user );
	}
}

/* Extracting other required stats: */
/* firstly, modified users */
$attributeFilter  = array( array( 'modified', 'between', array( $first_of_last_month, $first_of_month ) ),
						   array( 'published', 'not_between', array( $first_of_last_month, $first_of_month ) ) );
$params = array( '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' );

$monthly_modified_user_count = eZContentObjectTreeNode::subTreeCountByNodeID( $params, $parent_node_id );


/* Now our contactable users */
$attributeFilter  = array( array( 'user/contact_by_email', '=', 1 ) );
$params = array( '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' );
$users_to_email_count = eZContentObjectTreeNode::subTreeCountByNodeID( $params, $parent_node_id );


/* Writing stats to file if required and emailing to the site admin: */
// creating the file (filename based on start and end dates of the data):
if ( $monthly_new_user_count )
{
	$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 the email containing user stats:
// 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'];

$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 ) );
if ( $monthly_new_user_count )
	$email_content .= ' has been created at: ' . $file_path;
else
	$email_content .= ' was not created (no new users)';
$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 .= 'Total users who wish to be emailed: ' . $users_to_email_count . "\n";
echo $email_content;
//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 just use the standard php email function

$script->shutdown(); //stop the script
?>