3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright Tech To The People http:tttp.eu (c) 2008 |
7 +--------------------------------------------------------------------+
9 | CiviCRM is free software; you can copy, modify, and distribute it |
10 | under the terms of the GNU Affero General Public License |
11 | Version 3, 19 November 2007. |
13 | CiviCRM is distributed in the hope that it will be useful, but |
14 | WITHOUT ANY WARRANTY; without even the implied warranty of |
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
16 | See the GNU Affero General Public License for more details. |
18 | You should have received a copy of the GNU Affero General Public |
19 | License along with this program; if not, contact CiviCRM LLC |
20 | at info[AT]civicrm[DOT]org. If you have questions about the |
21 | GNU Affero General Public License or the licensing of CiviCRM, |
22 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
23 +--------------------------------------------------------------------+
27 * This files provides several classes for doing command line work with
28 * CiviCRM. civicrm_cli is the base class. It's used by cli.php.
30 * In addition, there are several additional classes that inherit
31 * civicrm_cli to do more precise functions.
36 * base class for doing all command line operations via civicrm
41 // required values that must be passed
42 // via the command line
43 var $_required_arguments = array('action', 'entity');
44 var $_additional_arguments = array();
52 var $_site = 'localhost';
54 var $_password = NULL;
56 // all other arguments populate the parameters
57 // array that is passed to civicrm_api
58 var $_params = array('version' => 3);
60 var $_errors = array();
65 public function initialize() {
66 if (!$this->_accessing_from_cli()) {
69 if (!$this->_parseOptions()) {
72 if (!$this->_bootstrap()) {
75 if (!$this->_validateOptions()) {
81 public function _accessing_from_cli() {
82 if (PHP_SAPI
=== 'cli') {
86 trigger_error("cli.php can only be run from command line.", E_USER_ERROR
);
93 public function callApi() {
94 require_once 'api/api.php';
96 // CRM-9822 -'execute' action always goes thru Job api and always writes to log
97 if ($this->_action
!= 'execute' && $this->_joblog
) {
98 require_once 'CRM/Core/JobManager.php';
99 $facility = new CRM_Core_JobManager();
100 $facility->setSingleRunParams($this->_entity
, $this->_action
, $this->_params
, 'From Cli.php');
101 $facility->executeJobByAction($this->_entity
, $this->_action
);
104 // CRM-9822 cli.php calls don't require site-key, so bypass site-key authentication
105 $this->_params
['auth'] = FALSE;
106 $result = civicrm_api($this->_entity
, $this->_action
, $this->_params
);
109 if ($result['is_error'] != 0) {
110 $this->_log($result['error_message']);
113 elseif ($this->_output
) {
114 print_r($result['values']);
122 private function _parseOptions() {
123 $args = $_SERVER['argv'];
124 // remove the first argument, which is the name
128 while (list($k, $arg) = each($args)) {
129 // sanitize all user input
130 $arg = $this->_sanitize($arg);
132 // if we're not parsing an option signifier
133 // continue to the next one
134 if (!preg_match('/^-/', $arg)) {
138 // find the value of this arg
139 if (preg_match('/=/', $arg)) {
140 $parts = explode('=', $arg);
145 if (isset($args[$k +
1])) {
146 $next_arg = $this->_sanitize($args[$k +
1]);
147 // if the next argument is not another option
148 // it's the value for this argument
149 if (!preg_match('/^-/', $next_arg)) {
155 // parse the special args first
156 if ($arg == '-e' ||
$arg == '--entity') {
157 $this->_entity
= $value;
159 elseif ($arg == '-a' ||
$arg == '--action') {
160 $this->_action
= $value;
162 elseif ($arg == '-s' ||
$arg == '--site') {
163 $this->_site
= $value;
165 elseif ($arg == '-u' ||
$arg == '--user') {
166 $this->_user
= $value;
168 elseif ($arg == '-p' ||
$arg == '--password') {
169 $this->_password
= $value;
171 elseif ($arg == '-o' ||
$arg == '--output') {
172 $this->_output
= TRUE;
174 elseif ($arg == '-j' ||
$arg == '--joblog') {
175 $this->_joblog
= TRUE;
178 while(list($short, $long) = each ($this->_additional_arguments
)) {
179 if ($arg == '-' . $short ||
$arg == '--' . $long) {
180 $property = '_' . $long;
181 $this->$property = $value;
185 // all other arguments are parameters
186 $key = ltrim($arg, '--');
187 $this->_params
[$key] = isset($value) ?
$value : NULL;
196 private function _bootstrap() {
197 // so the configuration works with php-cli
198 $_SERVER['PHP_SELF'] = "/index.php";
199 $_SERVER['HTTP_HOST'] = $this->_site
;
200 $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
201 $_SERVER['SERVER_SOFTWARE'] = NULL;
202 $_SERVER['REQUEST_METHOD'] = 'GET';
204 // SCRIPT_FILENAME needed by CRM_Utils_System::cmsRootPath
205 $_SERVER['SCRIPT_FILENAME'] = __FILE__
;
207 // CRM-8917 - check if script name starts with /, if not - prepend it.
208 if (ord($_SERVER['SCRIPT_NAME']) != 47) {
209 $_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
212 $civicrm_root = dirname(__DIR__
);
213 chdir($civicrm_root);
214 require_once ('civicrm.config.php');
216 if ( !class_exists('CRM_Core_ClassLoader') ) {
217 require_once $civicrm_root . '/CRM/Core/ClassLoader.php';
219 CRM_Core_ClassLoader
::singleton()->register();
221 $this->_config
= CRM_Core_Config
::singleton();
223 // HTTP_HOST will be 'localhost' unless overwritten with the -s argument.
224 // Now we have a Config object, we can set it from the Base URL.
225 if ($_SERVER['HTTP_HOST'] == 'localhost') {
226 $_SERVER['HTTP_HOST'] = preg_replace(
227 '!^https?://([^/]+)/$!i',
229 $this->_config
->userFrameworkBaseURL
);
232 $class = 'CRM_Utils_System_' . $this->_config
->userFramework
;
235 if (!CRM_Utils_System
::loadBootstrap(array(), FALSE, FALSE, $civicrm_root)) {
236 $this->_log(ts("Failed to bootstrap CMS"));
240 if (strtolower($this->_entity
) == 'job') {
242 $this->_log(ts("Jobs called from cli.php require valid user as parameter"));
247 if (!empty($this->_user
)) {
248 if(!CRM_Utils_System
::authenticateScript(TRUE, $this->_user
, $this->_password
, TRUE, FALSE, FALSE)) {
249 $this->_log(ts("Failed to login as %1. Wrong username or password.", array('1' => $this->_user
)));
252 if (!$cms->loadUser($this->_user
)) {
253 $this->_log(ts("Failed to login as %1", array('1' => $this->_user
)));
264 private function _validateOptions() {
265 $required = $this->_required_arguments
;
266 while (list(, $var) = each($required)) {
268 if (empty($this->$index)) {
269 $missing_arg = '--' . $var;
270 $this->_log(ts("The %1 argument is required", array(1 => $missing_arg)));
271 $this->_log($this->_getUsage());
283 private function _sanitize($value) {
284 // restrict user input - we should not be needing anything
285 // other than normal alpha numeric plus - and _.
286 return trim(preg_replace('#^[^a-zA-Z0-9\-_=/]$#', '', $value));
292 private function _getUsage() {
293 $out = "Usage: cli.php -e entity -a action [-u user] [-s site] [--output] [PARAMS]\n";
294 $out .= " entity is the name of the entity, e.g. Contact, Event, etc.\n";
295 $out .= " action is the name of the action e.g. Get, Create, etc.\n";
296 $out .= " user is an optional username to run the script as\n";
297 $out .= " site is the domain name of the web site (for Drupal multi site installs)\n";
298 $out .= " --output will print the result from the api call\n";
299 $out .= " PARAMS is one or more --param=value combinations to pass to the api\n";
306 private function _log($error) {
307 // fixme, this should call some CRM_Core_Error:: function
308 // that properly logs
314 * class used by csv/export.php to export records from
315 * the database in a csv file format.
318 class civicrm_cli_csv_exporter
extends civicrm_cli
{
319 var $separator = ',';
324 function __construct() {
325 $this->_required_arguments
= array('entity');
326 parent
::initialize();
330 $out = fopen("php://output", 'w');
331 fputcsv($out, $this->columns
, $this->separator
, '"');
334 $result = civicrm_api($this->_entity
, 'Get', $this->_params
);
336 foreach ($result['values'] as $row) {
338 $columns = array_keys($row);
339 fputcsv($out, $columns, $this->separator
, '"');
342 //handle values returned as arrays (i.e. custom fields that allow multiple selections) by inserting a control character
343 foreach ($row as &$field) {
344 if(is_array($field)) {
346 $field = implode($field,CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
349 fputcsv($out, $row, $this->separator
, '"');
357 * base class used by both civicrm_cli_csv_import
358 * and civicrm_cli_csv_deleter to add or delete
359 * records based on those found in a csv file
360 * passed to the script.
363 class civicrm_cli_csv_file
extends civicrm_cli
{
365 var $separator = ',';
370 function __construct() {
371 $this->_required_arguments
= array('entity','file');
372 $this->_additional_arguments
= array('f' => 'file');
373 parent
::initialize();
378 $handle = fopen($this->_file
, "r");
381 die("Could not open file: " . $this->_file
. ". Please provide an absolute path.\n");
385 $header = fgetcsv($handle, 0, $this->separator
);
386 // In case fgetcsv couldn't parse the header and dumped the whole line in 1 array element
387 // Try a different separator char
388 if (count($header) == 1) {
389 $this->separator
= ";";
391 $header = fgetcsv($handle, 0, $this->separator
);
392 if (count($header) == 1) {
393 die("Invalid file format for " . $this->_file
. ". It must be a valid csv with separator ',' or ';'\n");
397 $this->header
= $header;
398 while (($data = fgetcsv($handle, 0, $this->separator
)) !== FALSE) {
400 if(count($data) == 1 && is_null($data[0])) continue;
402 $params = $this->convertLine($data);
403 $this->processLine($params);
409 /* return a params as expected */
415 function convertLine($data) {
417 foreach ($this->header
as $i => $field) {
418 //split any multiselect data, denoted with CRM_Core_DAO::VALUE_SEPARATOR
419 if (strpos($data[$i], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
420 $data[$i] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,$data[$i]);
421 $data[$i] = array_combine($data[$i], $data[$i]);
423 $params[$field] = $data[$i];
425 $params['version'] = 3;
431 * class for processing records to add
432 * used by csv/import.php
436 class civicrm_cli_csv_importer
extends civicrm_cli_csv_file
{
440 function processline($params) {
441 $result = civicrm_api($this->_entity
, 'Create', $params);
442 if ($result['is_error']) {
443 echo "\nERROR line " . $this->row
. ": " . $result['error_message'] . "\n";
446 echo "\nline " . $this->row
. ": created " . $this->_entity
. " id: " . $result['id'] . "\n";
452 * class for processing records to delete
453 * used by csv/delete.php
457 class civicrm_cli_csv_deleter
extends civicrm_cli_csv_file
{
461 function processline($params) {
462 $result = civicrm_api($this->_entity
, 'Delete', $params);
463 if ($result['is_error']) {
464 echo "\nERROR line " . $this->row
. ": " . $result['error_message'] . "\n";
466 echo "\nline " . $this->row
. ": deleted\n";