Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions core/Api/UserApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -258,4 +258,52 @@ public function account_list($user_id, $query = array())
$filter['created_by'] = $user_id;
return Account::search($filter);
}

/**
* Import new users from into DB
*
* @url GET /users/csv

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it not supposed to be a POST API?
@url POST /users/csv

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update on latest commit.

*/
public function import_csv($data = array(), $mime = 'text/csv')
{
$this->_authorize('user_create');
$csv_data = explode(PHP_EOL, $data);
$temp = array_pop($csv_data);

// skip header row
$header_csv = str_getcsv($csv_data[0], ",");
foreach(array_slice($csv_data, 1) as $row) {
$row_csv = str_getcsv($row, ",");
$user_data = array_combine($header_csv, $row_csv);

$oUser = new User();
$this->set($oUser, $user_data);
$oUser->__set('active', intval($user_data['active']));
if (!$oUser->save()) {
throw new CoreException(417, 'Could not save User');
}
}

/**
* Export all users form DB
*
* @url POST /users/csv

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it not supposed to be a GET API?
@url GET /users/csv

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update on latest commit.

*/
public function export_csv()
{
$fields = array('username', 'passwd', 'first_name', 'last_name', 'email', 'address', 'company', 'active');
$query = 'SELECT ' . implode(", ", $fields) . ' FROM usr';
$result = DB::query('usr', $query);
$filepath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'users.csv';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use random file name, tempname function ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure what you mean by this. Could you please elaborate? thanks

$handle = fopen($filepath, 'w');
$head = implode(",", $fields) . "\n";
fwrite($handle, $head);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$csv = implode(",",$row) . "\n";
fwrite($handle, $csv);
}
fclose($handle);
return new SplFileInfo($filepath);
}
}
}