User Importer

Erstellt am: Tuesday 31 January 2017  |  Letzte Änderung am: Saturday 11 August 2018

This article is a part of the Working with ItemManager series.

This script allows you to import users from an uploaded CSV file to ItemManger's Users category. It will add users with very basic information – you can extend this script as you please.

Note that for this tutorial the Users category must already be created. How that can be done is explained at the beginning of this article Creating user management.

You can generate CSV file with all users inside it, using a standard spreadsheet software like: Microsoft Excel, LibreOffice Calc, Numbers, OpenOffice Calc or Gnumeric. You have to create the file filled with data (or take it from a database using phpMyAdmin), you will only have to choose CSV file when you Save as... the file. As example, a CSV file can also be downloaded from here users.csv

As you see, some the fields of the Users category are reflected in our CSV file columns. Some column names like name, active, are reserved for the attributes, so they are not field names.

Note line 4 from the top, there I have installed an incomplete data set specially for testing. Since I have defined column # 2 as a required (see script $reqCol variable), this record will be skipped when writing.

Before you can run the script, you may define some parameters:

/**
 * Define the script parameters
 */

// Relative path to the CSV file with data to import
$csv_path = '/import/users.csv';

// Skip table headers?
$skipHeaders = true;

// If the field names are the same as the table headers, this can be empty.
$fieldNames = array();

// Define the target IM's category
$category = 'Users';

// Define required columns (not listed here can be left blank)
$reqCol = array(0, 1, 2);

You can run this script as a plugin or paste it into your theme file. Remember to modify the path and other params in the script, according to the location you saved the CSV file.

/**
 * Define the script parameters
 */

// Relative path to the CSV file with data to import
$csv_path = '/import/users.csv';

// Skip table headers?
$skipHeaders = true;

// If the field names are the same as the table headers, this can be empty.
$fieldNames = array();

// Define the target IM's category
$category = 'Users';

// Define required columns (not listed here can be left blank)
$reqCol = array(0, 1, 2);

$full_path = __DIR__.$csv_path;
if(!file_exists($full_path)) {
	exit("File <mark>$full_path</mark> does not exists");
}

// Get IM class instances
$imanager = imanager();
$itemMapper = $imanager->getItemMapper();
$tple = $imanager->getTemplateEngine();
$curCategory = $imanager->getCategory("name=$category");
if(!$curCategory) {
	exit("Category <mark>{$imanager->sanitizer->text($category)}</mark> does not exists");
}
$itemMapper->alloc($curCategory->id);

// Define output templates
$table     = "<table width='100%' cellspacing='2' cellpadding='0' border='0' align='center' >[[content]]</table>\r\n";
$tableRow  = "<tr>\r\n[[content]]</tr>\r\n";
$tableHCol = "<th style='text-align: left; padding: 8px 12px; border-bottom: 2px solid #c5ccd6;'>[[content]]</th>\r\n";
$tableCol  = "<td[[prop]] style='text-align: left; padding: 8px 12px; border-bottom: 1px solid #c5ccd6;'>[[content]]</td>\r\n";
$tabBuffer = '';

// Open the CSV file for reading
$handle = fopen($full_path, 'r');
$emptyNames = empty($fieldNames) ? true : false;
$i = 0;
$row = array();
while(($row = fgetcsv($handle, 1000, ';')) !== false)
{
	$rowBuffer = '';
	$colBuffer = '';

	if($i == 0 && $skipHeaders) {
		$colBuffer .= $tple->render($tableHCol, array('content' => 'Row'));
		foreach($row as $key => $col) {
			$colBuffer .= $tple->render($tableHCol, array('content' => $col));
			if($emptyNames) $fieldNames[$key] = $col;
		}
		$tabBuffer .= $tple->render($tableRow, array('content' => $colBuffer));

		$i++;
		continue;
	}

	if($reqCol) {
		foreach($reqCol as $col) {
			if(empty($row[$col])) {
				$colBuffer .= $tple->render($tableCol, array('prop' => '', 'content' => $i));
				$colBuffer .= $tple->render($tableCol, array('prop' => ' colspan="'.count($row).'"',
					'content' => '<strong>Error:</strong> Required value empty, data record is not written.'));
				$tabBuffer .= $tple->render($tableRow, array('content' => $colBuffer));
				$i++;
				continue 2;
			}
		}
	}

	$colBuffer .= $tple->render($tableCol, array('prop' => '', 'content' => $i));
	// Create new item
	$newItem = new \Item($curCategory->id);
	foreach($row as $key => $col) {
		// Its an attribute not a field?
		$name = mb_strtolower($fieldNames[$key]);
		if($name == 'name' || $name == 'active' || $name == 'label' || $name == 'position') {
			$newItem->$name = $col;
		} else {
			$newItem->setFieldValue($name, $col);
		}
		$colBuffer .= $tple->render($tableCol, array('prop' => '', 'content' => $col));
	}
	// Save Item & SimpleItem
	if($newItem->save()) {
		$itemMapper->simplify($newItem);
		$itemMapper->save();
	}

	$tabBuffer .= $tple->render($tableRow, array('content' => $colBuffer));

	$i++;
}
fclose($handle);

$output = '<h3>Import Log</h3>';
$output .= $tple->render($table, array('content' => $tabBuffer));

echo $output;

Now you can see the list of imported users when everything ran properly:

Autor: Bigin  |  Tags:  FrameworkPHPGetSimpleDevelopmentItemManager