style warning fix
[civicrm-core.git] / bin / cli.class.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
81621fee 4 | CiviCRM version 4.7 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright Tech To The People http:tttp.eu (c) 2008 |
7 +--------------------------------------------------------------------+
8 | |
9 | CiviCRM is free software; you can copy, modify, and distribute it |
10 | under the terms of the GNU Affero General Public License |
c73475ea 11 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
6a488035
TO
12 | |
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. |
17 | |
18 | You should have received a copy of the GNU Affero General Public |
c73475ea
WA
19 | License and the CiviCRM Licensing Exception along |
20 | with this program; if not, contact CiviCRM LLC |
6a488035
TO
21 | at info[AT]civicrm[DOT]org. If you have questions about the |
22 | GNU Affero General Public License or the licensing of CiviCRM, |
23 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
24 +--------------------------------------------------------------------+
d25dd0ee 25 */
6a488035
TO
26
27/**
28 * This files provides several classes for doing command line work with
29 * CiviCRM. civicrm_cli is the base class. It's used by cli.php.
30 *
31 * In addition, there are several additional classes that inherit
32 * civicrm_cli to do more precise functions.
33 *
5396af74 34 */
6a488035
TO
35
36/**
37 * base class for doing all command line operations via civicrm
38 * used by cli.php
5396af74 39 */
6a488035
TO
40class civicrm_cli {
41 // required values that must be passed
42 // via the command line
43 var $_required_arguments = array('action', 'entity');
44 var $_additional_arguments = array();
45 var $_entity = NULL;
46 var $_action = NULL;
47 var $_output = FALSE;
48 var $_joblog = FALSE;
4dbe0684 49 var $_semicolon = FALSE;
6a488035
TO
50 var $_config;
51
52 // optional arguments
53 var $_site = 'localhost';
54 var $_user = NULL;
2d8f9c75 55 var $_password = NULL;
6a488035
TO
56
57 // all other arguments populate the parameters
58 // array that is passed to civicrm_api
59 var $_params = array('version' => 3);
60
61 var $_errors = array();
62
4e87860d
EM
63 /**
64 * @return bool
65 */
6a488035
TO
66 public function initialize() {
67 if (!$this->_accessing_from_cli()) {
68 return FALSE;
69 }
70 if (!$this->_parseOptions()) {
71 return FALSE;
72 }
73 if (!$this->_bootstrap()) {
74 return FALSE;
75 }
76 if (!$this->_validateOptions()) {
77 return FALSE;
78 }
79 return TRUE;
80 }
81
cd5823ae
EM
82 /**
83 * Ensure function is being run from the cli.
84 *
85 * @return bool
86 */
6a488035
TO
87 public function _accessing_from_cli() {
88 if (PHP_SAPI === 'cli') {
89 return TRUE;
90 }
91 else {
9c8d6e29 92 die("cli.php can only be run from command line.");
6a488035
TO
93 }
94 }
95
4e87860d
EM
96 /**
97 * @return bool
98 */
6a488035
TO
99 public function callApi() {
100 require_once 'api/api.php';
101
102 // CRM-9822 -'execute' action always goes thru Job api and always writes to log
103 if ($this->_action != 'execute' && $this->_joblog) {
104 require_once 'CRM/Core/JobManager.php';
105 $facility = new CRM_Core_JobManager();
106 $facility->setSingleRunParams($this->_entity, $this->_action, $this->_params, 'From Cli.php');
107 $facility->executeJobByAction($this->_entity, $this->_action);
108 }
109 else {
110 // CRM-9822 cli.php calls don't require site-key, so bypass site-key authentication
111 $this->_params['auth'] = FALSE;
112 $result = civicrm_api($this->_entity, $this->_action, $this->_params);
113 }
114
ab874c22 115 if (!empty($result['is_error'])) {
6a488035
TO
116 $this->_log($result['error_message']);
117 return FALSE;
118 }
15fe6ffd
TO
119 elseif ($this->_output === 'json') {
120 echo json_encode($result, defined('JSON_PRETTY_PRINT') ? JSON_PRETTY_PRINT : 0);
121 }
6a488035
TO
122 elseif ($this->_output) {
123 print_r($result['values']);
124 }
125 return TRUE;
126 }
127
4e87860d
EM
128 /**
129 * @return bool
130 */
6a488035
TO
131 private function _parseOptions() {
132 $args = $_SERVER['argv'];
133 // remove the first argument, which is the name
134 // of this script
135 array_shift($args);
136
137 while (list($k, $arg) = each($args)) {
138 // sanitize all user input
139 $arg = $this->_sanitize($arg);
140
141 // if we're not parsing an option signifier
142 // continue to the next one
143 if (!preg_match('/^-/', $arg)) {
144 continue;
145 }
146
147 // find the value of this arg
148 if (preg_match('/=/', $arg)) {
149 $parts = explode('=', $arg);
56fdfc52 150 $arg = $parts[0];
6a488035
TO
151 $value = $parts[1];
152 }
153 else {
154 if (isset($args[$k + 1])) {
155 $next_arg = $this->_sanitize($args[$k + 1]);
156 // if the next argument is not another option
157 // it's the value for this argument
158 if (!preg_match('/^-/', $next_arg)) {
159 $value = $next_arg;
160 }
161 }
162 }
163
164 // parse the special args first
165 if ($arg == '-e' || $arg == '--entity') {
166 $this->_entity = $value;
167 }
168 elseif ($arg == '-a' || $arg == '--action') {
169 $this->_action = $value;
170 }
171 elseif ($arg == '-s' || $arg == '--site') {
172 $this->_site = $value;
173 }
174 elseif ($arg == '-u' || $arg == '--user') {
175 $this->_user = $value;
176 }
177 elseif ($arg == '-p' || $arg == '--password') {
178 $this->_password = $value;
179 }
180 elseif ($arg == '-o' || $arg == '--output') {
181 $this->_output = TRUE;
182 }
26604a65 183 elseif ($arg == '-J' || $arg == '--json') {
15fe6ffd
TO
184 $this->_output = 'json';
185 }
6a488035
TO
186 elseif ($arg == '-j' || $arg == '--joblog') {
187 $this->_joblog = TRUE;
188 }
4dbe0684
T
189 elseif ($arg == '-sem' || $arg == '--semicolon') {
190 $this->_semicolon = TRUE;
191 }
6a488035 192 else {
c8c10d52 193 foreach ($this->_additional_arguments as $short => $long) {
6a488035
TO
194 if ($arg == '-' . $short || $arg == '--' . $long) {
195 $property = '_' . $long;
196 $this->$property = $value;
197 continue;
198 }
199 }
200 // all other arguments are parameters
201 $key = ltrim($arg, '--');
202 $this->_params[$key] = isset($value) ? $value : NULL;
203 }
204 }
205 return TRUE;
206 }
207
4e87860d
EM
208 /**
209 * @return bool
210 */
6a488035
TO
211 private function _bootstrap() {
212 // so the configuration works with php-cli
213 $_SERVER['PHP_SELF'] = "/index.php";
214 $_SERVER['HTTP_HOST'] = $this->_site;
215 $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
ddd885e6 216 $_SERVER['SERVER_SOFTWARE'] = NULL;
56fdfc52 217 $_SERVER['REQUEST_METHOD'] = 'GET';
ddd885e6 218
6a488035
TO
219 // SCRIPT_FILENAME needed by CRM_Utils_System::cmsRootPath
220 $_SERVER['SCRIPT_FILENAME'] = __FILE__;
ddd885e6 221
6a488035
TO
222 // CRM-8917 - check if script name starts with /, if not - prepend it.
223 if (ord($_SERVER['SCRIPT_NAME']) != 47) {
224 $_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
225 }
226
227 $civicrm_root = dirname(__DIR__);
228 chdir($civicrm_root);
dc1e9be8
TO
229 if (getenv('CIVICRM_SETTINGS')) {
230 require_once getenv('CIVICRM_SETTINGS');
231 }
232 else {
233 require_once 'civicrm.config.php';
234 }
6a488035 235 // autoload
481a74f4 236 if (!class_exists('CRM_Core_ClassLoader')) {
c1f3c6da
BS
237 require_once $civicrm_root . '/CRM/Core/ClassLoader.php';
238 }
6a488035
TO
239 CRM_Core_ClassLoader::singleton()->register();
240
241 $this->_config = CRM_Core_Config::singleton();
4e87860d 242
84f65b2e
KW
243 // HTTP_HOST will be 'localhost' unless overwritten with the -s argument.
244 // Now we have a Config object, we can set it from the Base URL.
245 if ($_SERVER['HTTP_HOST'] == 'localhost') {
a9e80afc 246 $_SERVER['HTTP_HOST'] = preg_replace(
56fdfc52
TO
247 '!^https?://([^/]+)/$!i',
248 '$1',
249 $this->_config->userFrameworkBaseURL);
84f65b2e 250 }
6a488035
TO
251
252 $class = 'CRM_Utils_System_' . $this->_config->userFramework;
253
254 $cms = new $class();
323696fa 255 if (!CRM_Utils_System::loadBootstrap(array(), FALSE, FALSE, $civicrm_root)) {
6a488035
TO
256 $this->_log(ts("Failed to bootstrap CMS"));
257 return FALSE;
258 }
259
260 if (strtolower($this->_entity) == 'job') {
261 if (!$this->_user) {
262 $this->_log(ts("Jobs called from cli.php require valid user as parameter"));
263 return FALSE;
264 }
265 }
266
267 if (!empty($this->_user)) {
22e263ad 268 if (!CRM_Utils_System::authenticateScript(TRUE, $this->_user, $this->_password, TRUE, FALSE, FALSE)) {
bec3fc7c
BS
269 $this->_log(ts("Failed to login as %1. Wrong username or password.", array('1' => $this->_user)));
270 return FALSE;
271 }
b596c3e9 272 if (($this->_config->userFramework == 'Joomla' && !$cms->loadUser($this->_user, $this->_password)) || !$cms->loadUser($this->_user)) {
6a488035
TO
273 $this->_log(ts("Failed to login as %1", array('1' => $this->_user)));
274 return FALSE;
275 }
276 }
277
278 return TRUE;
279 }
280
4e87860d
EM
281 /**
282 * @return bool
283 */
6a488035
TO
284 private function _validateOptions() {
285 $required = $this->_required_arguments;
286 while (list(, $var) = each($required)) {
287 $index = '_' . $var;
288 if (empty($this->$index)) {
289 $missing_arg = '--' . $var;
290 $this->_log(ts("The %1 argument is required", array(1 => $missing_arg)));
291 $this->_log($this->_getUsage());
292 return FALSE;
293 }
294 }
295 return TRUE;
296 }
297
4e87860d
EM
298 /**
299 * @param $value
300 *
301 * @return string
302 */
6a488035
TO
303 private function _sanitize($value) {
304 // restrict user input - we should not be needing anything
305 // other than normal alpha numeric plus - and _.
306 return trim(preg_replace('#^[^a-zA-Z0-9\-_=/]$#', '', $value));
307 }
308
4e87860d
EM
309 /**
310 * @return string
311 */
6a488035 312 private function _getUsage() {
15fe6ffd 313 $out = "Usage: cli.php -e entity -a action [-u user] [-s site] [--output|--json] [PARAMS]\n";
6a488035
TO
314 $out .= " entity is the name of the entity, e.g. Contact, Event, etc.\n";
315 $out .= " action is the name of the action e.g. Get, Create, etc.\n";
316 $out .= " user is an optional username to run the script as\n";
317 $out .= " site is the domain name of the web site (for Drupal multi site installs)\n";
15fe6ffd
TO
318 $out .= " --output will pretty print the result from the api call\n";
319 $out .= " --json will print the result from the api call as JSON\n";
6a488035
TO
320 $out .= " PARAMS is one or more --param=value combinations to pass to the api\n";
321 return ts($out);
322 }
323
4e87860d
EM
324 /**
325 * @param $error
326 */
6a488035
TO
327 private function _log($error) {
328 // fixme, this should call some CRM_Core_Error:: function
329 // that properly logs
330 print "$error\n";
331 }
96025800 332
6a488035
TO
333}
334
335/**
336 * class used by csv/export.php to export records from
337 * the database in a csv file format.
5396af74 338 */
6a488035
TO
339class civicrm_cli_csv_exporter extends civicrm_cli {
340 var $separator = ',';
341
4e87860d 342 /**
4e87860d 343 */
5396af74 344 public function __construct() {
6a488035
TO
345 $this->_required_arguments = array('entity');
346 parent::initialize();
347 }
348
4dbe0684
T
349 /**
350 * Run the script.
351 */
5396af74 352 public function run() {
4dbe0684
T
353 if ($this->_semicolon) {
354 $this->separator = ';';
355 }
356
6a488035
TO
357 $out = fopen("php://output", 'w');
358 fputcsv($out, $this->columns, $this->separator, '"');
359
360 $this->row = 1;
361 $result = civicrm_api($this->_entity, 'Get', $this->_params);
a9e80afc 362 $first = TRUE;
6a488035 363 foreach ($result['values'] as $row) {
22e263ad 364 if ($first) {
6a488035
TO
365 $columns = array_keys($row);
366 fputcsv($out, $columns, $this->separator, '"');
a9e80afc 367 $first = FALSE;
6a488035 368 }
0d5a3f9d
JL
369 //handle values returned as arrays (i.e. custom fields that allow multiple selections) by inserting a control character
370 foreach ($row as &$field) {
22e263ad 371 if (is_array($field)) {
0d5a3f9d 372 //convert to string
a9e80afc 373 $field = implode($field, CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
0d5a3f9d
JL
374 }
375 }
6a488035
TO
376 fputcsv($out, $row, $this->separator, '"');
377 }
378 fclose($out);
379 echo "\n";
380 }
96025800 381
6a488035
TO
382}
383
384/**
385 * base class used by both civicrm_cli_csv_import
386 * and civicrm_cli_csv_deleter to add or delete
387 * records based on those found in a csv file
388 * passed to the script.
5396af74 389 */
6a488035
TO
390class civicrm_cli_csv_file extends civicrm_cli {
391 var $header;
392 var $separator = ',';
393
4e87860d 394 /**
4e87860d 395 */
5396af74 396 public function __construct() {
a9e80afc 397 $this->_required_arguments = array('entity', 'file');
6a488035
TO
398 $this->_additional_arguments = array('f' => 'file');
399 parent::initialize();
400 }
401
cd5823ae
EM
402 /**
403 * Run CLI function.
404 */
5396af74 405 public function run() {
6a488035
TO
406 $this->row = 1;
407 $handle = fopen($this->_file, "r");
408
409 if (!$handle) {
410 die("Could not open file: " . $this->_file . ". Please provide an absolute path.\n");
411 }
412
413 //header
414 $header = fgetcsv($handle, 0, $this->separator);
415 // In case fgetcsv couldn't parse the header and dumped the whole line in 1 array element
416 // Try a different separator char
417 if (count($header) == 1) {
418 $this->separator = ";";
419 rewind($handle);
420 $header = fgetcsv($handle, 0, $this->separator);
6a488035
TO
421 }
422
423 $this->header = $header;
424 while (($data = fgetcsv($handle, 0, $this->separator)) !== FALSE) {
425 // skip blank lines
4f99ca55
TO
426 if (count($data) == 1 && is_null($data[0])) {
427 continue;
a9e80afc 428 }
6a488035 429 $this->row++;
6c07d162
J
430 if ($this->row % 1000 == 0) {
431 // Reset PEAR_DB_DATAOBJECT cache to prevent memory leak
39a545dc 432 CRM_Core_DAO::freeResult();
6c07d162 433 }
6a488035
TO
434 $params = $this->convertLine($data);
435 $this->processLine($params);
436 }
437 fclose($handle);
6a488035
TO
438 }
439
440 /* return a params as expected */
4e87860d
EM
441 /**
442 * @param $data
443 *
444 * @return array
445 */
5396af74 446 public function convertLine($data) {
6a488035
TO
447 $params = array();
448 foreach ($this->header as $i => $field) {
2d8f9c75 449 //split any multiselect data, denoted with CRM_Core_DAO::VALUE_SEPARATOR
0d5a3f9d 450 if (strpos($data[$i], CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
a9e80afc 451 $data[$i] = explode(CRM_Core_DAO::VALUE_SEPARATOR, $data[$i]);
0d5a3f9d
JL
452 $data[$i] = array_combine($data[$i], $data[$i]);
453 }
6a488035
TO
454 $params[$field] = $data[$i];
455 }
456 $params['version'] = 3;
457 return $params;
458 }
96025800 459
6a488035
TO
460}
461
462/**
463 * class for processing records to add
464 * used by csv/import.php
465 *
5396af74 466 */
6a488035 467class civicrm_cli_csv_importer extends civicrm_cli_csv_file {
4e87860d 468 /**
c490a46a 469 * @param array $params
4e87860d 470 */
5396af74 471 public function processline($params) {
6a488035
TO
472 $result = civicrm_api($this->_entity, 'Create', $params);
473 if ($result['is_error']) {
474 echo "\nERROR line " . $this->row . ": " . $result['error_message'] . "\n";
475 }
476 else {
477 echo "\nline " . $this->row . ": created " . $this->_entity . " id: " . $result['id'] . "\n";
478 }
479 }
96025800 480
6a488035
TO
481}
482
483/**
484 * class for processing records to delete
485 * used by csv/delete.php
486 *
5396af74 487 */
6a488035 488class civicrm_cli_csv_deleter extends civicrm_cli_csv_file {
4e87860d 489 /**
c490a46a 490 * @param array $params
4e87860d 491 */
5396af74 492 public function processline($params) {
6a488035
TO
493 $result = civicrm_api($this->_entity, 'Delete', $params);
494 if ($result['is_error']) {
495 echo "\nERROR line " . $this->row . ": " . $result['error_message'] . "\n";
0db6c3e1
TO
496 }
497 else {
6a488035
TO
498 echo "\nline " . $this->row . ": deleted\n";
499 }
500 }
96025800 501
6a488035 502}