Merge remote-tracking branch 'upstream/4.3' into 4.3-master-2013-08-14-04-44-13
[civicrm-core.git] / bin / cli.class.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 |
11 | Version 3, 19 November 2007. |
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 |
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 +--------------------------------------------------------------------+
24 */
25
26 /**
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.
29 *
30 * In addition, there are several additional classes that inherit
31 * civicrm_cli to do more precise functions.
32 *
33 **/
34
35 /**
36 * base class for doing all command line operations via civicrm
37 * used by cli.php
38 **/
39
40 class 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;
49 var $_config;
50
51 // optional arguments
52 var $_site = 'localhost';
53 var $_user = NULL;
54
55 // all other arguments populate the parameters
56 // array that is passed to civicrm_api
57 var $_params = array('version' => 3);
58
59 var $_errors = array();
60
61 public function initialize() {
62 if (!$this->_accessing_from_cli()) {
63 return FALSE;
64 }
65 if (!$this->_parseOptions()) {
66 return FALSE;
67 }
68 if (!$this->_bootstrap()) {
69 return FALSE;
70 }
71 if (!$this->_validateOptions()) {
72 return FALSE;
73 }
74 return TRUE;
75 }
76
77 public function _accessing_from_cli() {
78 if (PHP_SAPI === 'cli') {
79 return TRUE;
80 }
81 else {
82 trigger_error("cli.php can only be run from command line.", E_USER_ERROR);
83 }
84 }
85
86 public function callApi() {
87 require_once 'api/api.php';
88
89 // CRM-9822 -'execute' action always goes thru Job api and always writes to log
90 if ($this->_action != 'execute' && $this->_joblog) {
91 require_once 'CRM/Core/JobManager.php';
92 $facility = new CRM_Core_JobManager();
93 $facility->setSingleRunParams($this->_entity, $this->_action, $this->_params, 'From Cli.php');
94 $facility->executeJobByAction($this->_entity, $this->_action);
95 }
96 else {
97 // CRM-9822 cli.php calls don't require site-key, so bypass site-key authentication
98 $this->_params['auth'] = FALSE;
99 $result = civicrm_api($this->_entity, $this->_action, $this->_params);
100 }
101
102 if ($result['is_error'] != 0) {
103 $this->_log($result['error_message']);
104 return FALSE;
105 }
106 elseif ($this->_output) {
107 print_r($result['values']);
108 }
109 return TRUE;
110 }
111
112 private function _parseOptions() {
113 $args = $_SERVER['argv'];
114 // remove the first argument, which is the name
115 // of this script
116 array_shift($args);
117
118 while (list($k, $arg) = each($args)) {
119 // sanitize all user input
120 $arg = $this->_sanitize($arg);
121
122 // if we're not parsing an option signifier
123 // continue to the next one
124 if (!preg_match('/^-/', $arg)) {
125 continue;
126 }
127
128 // find the value of this arg
129 if (preg_match('/=/', $arg)) {
130 $parts = explode('=', $arg);
131 $arg = $parts[0];
132 $value = $parts[1];
133 }
134 else {
135 if (isset($args[$k + 1])) {
136 $next_arg = $this->_sanitize($args[$k + 1]);
137 // if the next argument is not another option
138 // it's the value for this argument
139 if (!preg_match('/^-/', $next_arg)) {
140 $value = $next_arg;
141 }
142 }
143 }
144
145 // parse the special args first
146 if ($arg == '-e' || $arg == '--entity') {
147 $this->_entity = $value;
148 }
149 elseif ($arg == '-a' || $arg == '--action') {
150 $this->_action = $value;
151 }
152 elseif ($arg == '-s' || $arg == '--site') {
153 $this->_site = $value;
154 }
155 elseif ($arg == '-u' || $arg == '--user') {
156 $this->_user = $value;
157 }
158 elseif ($arg == '-p' || $arg == '--password') {
159 $this->_password = $value;
160 }
161 elseif ($arg == '-o' || $arg == '--output') {
162 $this->_output = TRUE;
163 }
164 elseif ($arg == '-j' || $arg == '--joblog') {
165 $this->_joblog = TRUE;
166 }
167 else {
168 while(list($short, $long) = each ($this->_additional_arguments)) {
169 if ($arg == '-' . $short || $arg == '--' . $long) {
170 $property = '_' . $long;
171 $this->$property = $value;
172 continue;
173 }
174 }
175 // all other arguments are parameters
176 $key = ltrim($arg, '--');
177 $this->_params[$key] = isset($value) ? $value : NULL;
178 }
179 }
180 return TRUE;
181 }
182
183 private function _bootstrap() {
184 // so the configuration works with php-cli
185 $_SERVER['PHP_SELF'] = "/index.php";
186 $_SERVER['HTTP_HOST'] = $this->_site;
187 $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
188 $_SERVER['SERVER_SOFTWARE'] = NULL;
189 $_SERVER['REQUEST_METHOD'] = 'GET';
190
191 // SCRIPT_FILENAME needed by CRM_Utils_System::cmsRootPath
192 $_SERVER['SCRIPT_FILENAME'] = __FILE__;
193
194 // CRM-8917 - check if script name starts with /, if not - prepend it.
195 if (ord($_SERVER['SCRIPT_NAME']) != 47) {
196 $_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
197 }
198
199 $civicrm_root = dirname(__DIR__);
200 chdir($civicrm_root);
201 require_once ('civicrm.config.php');
202 // autoload
203 require_once $civicrm_root . '/CRM/Core/ClassLoader.php';
204 CRM_Core_ClassLoader::singleton()->register();
205
206 $this->_config = CRM_Core_Config::singleton();
207
208 $class = 'CRM_Utils_System_' . $this->_config->userFramework;
209
210 $cms = new $class();
211 if (!CRM_Utils_System::loadBootstrap(array(), FALSE, FALSE, $civicrm_root)) {
212 $this->_log(ts("Failed to bootstrap CMS"));
213 return FALSE;
214 }
215
216 if (strtolower($this->_entity) == 'job') {
217 if (!$this->_user) {
218 $this->_log(ts("Jobs called from cli.php require valid user as parameter"));
219 return FALSE;
220 }
221 }
222
223 if (!empty($this->_user)) {
224 if(!CRM_Utils_System::authenticateScript(TRUE, $this->_user, $this->_password, TRUE, FALSE, FALSE)) {
225 $this->_log(ts("Failed to login as %1. Wrong username or password.", array('1' => $this->_user)));
226 return FALSE;
227 }
228 if (!$cms->loadUser($this->_user)) {
229 $this->_log(ts("Failed to login as %1", array('1' => $this->_user)));
230 return FALSE;
231 }
232 }
233
234 return TRUE;
235 }
236
237 private function _validateOptions() {
238 $required = $this->_required_arguments;
239 while (list(, $var) = each($required)) {
240 $index = '_' . $var;
241 if (empty($this->$index)) {
242 $missing_arg = '--' . $var;
243 $this->_log(ts("The %1 argument is required", array(1 => $missing_arg)));
244 $this->_log($this->_getUsage());
245 return FALSE;
246 }
247 }
248 return TRUE;
249 }
250
251 private function _sanitize($value) {
252 // restrict user input - we should not be needing anything
253 // other than normal alpha numeric plus - and _.
254 return trim(preg_replace('#^[^a-zA-Z0-9\-_=/]$#', '', $value));
255 }
256
257 private function _getUsage() {
258 $out = "Usage: cli.php -e entity -a action [-u user] [-s site] [--output] [PARAMS]\n";
259 $out .= " entity is the name of the entity, e.g. Contact, Event, etc.\n";
260 $out .= " action is the name of the action e.g. Get, Create, etc.\n";
261 $out .= " user is an optional username to run the script as\n";
262 $out .= " site is the domain name of the web site (for Drupal multi site installs)\n";
263 $out .= " --output will print the result from the api call\n";
264 $out .= " PARAMS is one or more --param=value combinations to pass to the api\n";
265 return ts($out);
266 }
267
268 private function _log($error) {
269 // fixme, this should call some CRM_Core_Error:: function
270 // that properly logs
271 print "$error\n";
272 }
273 }
274
275 /**
276 * class used by csv/export.php to export records from
277 * the database in a csv file format.
278 **/
279
280 class civicrm_cli_csv_exporter extends civicrm_cli {
281 var $separator = ',';
282
283 function __construct() {
284 $this->_required_arguments = array('entity');
285 parent::initialize();
286 }
287
288 function run() {
289 $out = fopen("php://output", 'w');
290 fputcsv($out, $this->columns, $this->separator, '"');
291
292 $this->row = 1;
293 $result = civicrm_api($this->_entity, 'Get', $this->_params);
294 $first = true;
295 foreach ($result['values'] as $row) {
296 if($first) {
297 $columns = array_keys($row);
298 fputcsv($out, $columns, $this->separator, '"');
299 $first = false;
300 }
301 //handle values returned as arrays (i.e. custom fields that allow multiple selections) by inserting a control character
302 foreach ($row as &$field) {
303 if(is_array($field)) {
304 //convert to string
305 $field = implode($field,CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR;
306 }
307 }
308 fputcsv($out, $row, $this->separator, '"');
309 }
310 fclose($out);
311 echo "\n";
312 }
313 }
314
315 /**
316 * base class used by both civicrm_cli_csv_import
317 * and civicrm_cli_csv_deleter to add or delete
318 * records based on those found in a csv file
319 * passed to the script.
320 **/
321
322 class civicrm_cli_csv_file extends civicrm_cli {
323 var $header;
324 var $separator = ',';
325
326 function __construct() {
327 $this->_required_arguments = array('entity','file');
328 $this->_additional_arguments = array('f' => 'file');
329 parent::initialize();
330 }
331
332 function run() {
333 $this->row = 1;
334 $handle = fopen($this->_file, "r");
335
336 if (!$handle) {
337 die("Could not open file: " . $this->_file . ". Please provide an absolute path.\n");
338 }
339
340 //header
341 $header = fgetcsv($handle, 0, $this->separator);
342 // In case fgetcsv couldn't parse the header and dumped the whole line in 1 array element
343 // Try a different separator char
344 if (count($header) == 1) {
345 $this->separator = ";";
346 rewind($handle);
347 $header = fgetcsv($handle, 0, $this->separator);
348 if (count($header) == 1) {
349 die("Invalid file format for " . $this->_file . ". It must be a valid csv with separator ',' or ';'\n");
350 }
351 }
352
353 $this->header = $header;
354 while (($data = fgetcsv($handle, 0, $this->separator)) !== FALSE) {
355 // skip blank lines
356 if(count($data) == 1 && is_null($data[0])) continue;
357 $this->row++;
358 $params = $this->convertLine($data);
359 $this->processLine($params);
360 }
361 fclose($handle);
362 return;
363 }
364
365 /* return a params as expected */
366 function convertLine($data) {
367 $params = array();
368 foreach ($this->header as $i => $field) {
369 //split any multiselect data, denoted with CRM_Core_DAO::VALUE_SEPARATOR
370 if (strpos($data[$i], CRM_Core_DAO::VALUE_SEPARATOR) !== FALSE) {
371 $data[$i] = explode(CRM_Core_DAO::VALUE_SEPARATOR,$data[$i]);
372 $data[$i] = array_combine($data[$i], $data[$i]);
373 }
374 $params[$field] = $data[$i];
375 }
376 $params['version'] = 3;
377 return $params;
378 }
379 }
380
381 /**
382 * class for processing records to add
383 * used by csv/import.php
384 *
385 **/
386
387 class civicrm_cli_csv_importer extends civicrm_cli_csv_file {
388 function processline($params) {
389 $result = civicrm_api($this->_entity, 'Create', $params);
390 if ($result['is_error']) {
391 echo "\nERROR line " . $this->row . ": " . $result['error_message'] . "\n";
392 }
393 else {
394 echo "\nline " . $this->row . ": created " . $this->_entity . " id: " . $result['id'] . "\n";
395 }
396 }
397 }
398
399 /**
400 * class for processing records to delete
401 * used by csv/delete.php
402 *
403 **/
404
405 class civicrm_cli_csv_deleter extends civicrm_cli_csv_file {
406 function processline($params) {
407 $result = civicrm_api($this->_entity, 'Delete', $params);
408 if ($result['is_error']) {
409 echo "\nERROR line " . $this->row . ": " . $result['error_message'] . "\n";
410 } else {
411 echo "\nline " . $this->row . ": deleted\n";
412 }
413 }
414 }