3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
40 // required values that must be passed
41 // via the command line
42 var $_required_arguments = array('action', 'entity');
43 var $_additional_arguments = array();
51 var $_site = 'localhost';
53 var $_password = NULL;
55 // all other arguments populate the parameters
56 // array that is passed to civicrm_api
57 var $_params = array('version' => 3);
59 var $_errors = array();
64 public function initialize() {
65 if (!$this->_accessing_from_cli()) {
68 if (!$this->_parseOptions()) {
71 if (!$this->_bootstrap()) {
74 if (!$this->_validateOptions()) {
80 public function _accessing_from_cli() {
81 if (PHP_SAPI
=== 'cli') {
85 trigger_error("cli.php can only be run from command line.", E_USER_ERROR
);
92 public function callApi() {
93 require_once 'api/api.php';
95 // CRM-9822 -'execute' action always goes thru Job api and always writes to log
96 if ($this->_action
!= 'execute' && $this->_joblog
) {
97 require_once 'CRM/Core/JobManager.php';
98 $facility = new CRM_Core_JobManager();
99 $facility->setSingleRunParams($this->_entity
, $this->_action
, $this->_params
, 'From Cli.php');
100 $facility->executeJobByAction($this->_entity
, $this->_action
);
103 // CRM-9822 cli.php calls don't require site-key, so bypass site-key authentication
104 $this->_params
['auth'] = FALSE;
105 $result = civicrm_api($this->_entity
, $this->_action
, $this->_params
);
108 if ($result['is_error'] != 0) {
109 $this->_log($result['error_message']);
112 elseif ($this->_output
) {
113 print_r($result['values']);
121 private function _parseOptions() {
122 $args = $_SERVER['argv'];
123 // remove the first argument, which is the name
127 while (list($k, $arg) = each($args)) {
128 // sanitize all user input
129 $arg = $this->_sanitize($arg);
131 // if we're not parsing an option signifier
132 // continue to the next one
133 if (!preg_match('/^-/', $arg)) {
137 // find the value of this arg
138 if (preg_match('/=/', $arg)) {
139 $parts = explode('=', $arg);
144 if (isset($args[$k +
1])) {
145 $next_arg = $this->_sanitize($args[$k +
1]);
146 // if the next argument is not another option
147 // it's the value for this argument
148 if (!preg_match('/^-/', $next_arg)) {
154 // parse the special args first
155 if ($arg == '-e' ||
$arg == '--entity') {
156 $this->_entity
= $value;
158 elseif ($arg == '-a' ||
$arg == '--action') {
159 $this->_action
= $value;
161 elseif ($arg == '-s' ||
$arg == '--site') {
162 $this->_site
= $value;
164 elseif ($arg == '-u' ||
$arg == '--user') {
165 $this->_user
= $value;
167 elseif ($arg == '-p' ||
$arg == '--password') {
168 $this->_password
= $value;
170 elseif ($arg == '-o' ||
$arg == '--output') {
171 $this->_output
= TRUE;
173 elseif ($arg == '-j' ||
$arg == '--joblog') {
174 $this->_joblog
= TRUE;
177 while (list($short, $long) = each($this->_additional_arguments
)) {
178 if ($arg == '-' . $short ||
$arg == '--' . $long) {
179 $property = '_' . $long;
180 $this->$property = $value;
184 // all other arguments are parameters
185 $key = ltrim($arg, '--');
186 $this->_params
[$key] = isset($value) ?
$value : NULL;
195 private function _bootstrap() {
196 // so the configuration works with php-cli
197 $_SERVER['PHP_SELF'] = "/index.php";
198 $_SERVER['HTTP_HOST'] = $this->_site
;
199 $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
200 $_SERVER['SERVER_SOFTWARE'] = NULL;
201 $_SERVER['REQUEST_METHOD'] = 'GET';
203 // SCRIPT_FILENAME needed by CRM_Utils_System::cmsRootPath
204 $_SERVER['SCRIPT_FILENAME'] = __FILE__
;
206 // CRM-8917 - check if script name starts with /, if not - prepend it.
207 if (ord($_SERVER['SCRIPT_NAME']) != 47) {
208 $_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
211 $civicrm_root = dirname(__DIR__
);
212 chdir($civicrm_root);
213 require_once 'civicrm.config.php';
215 if (!class_exists('CRM_Core_ClassLoader')) {
216 require_once $civicrm_root . '/CRM/Core/ClassLoader.php';
218 CRM_Core_ClassLoader
::singleton()->register();
220 $this->_config
= CRM_Core_Config
::singleton();
222 // HTTP_HOST will be 'localhost' unless overwritten with the -s argument.
223 // Now we have a Config object, we can set it from the Base URL.
224 if ($_SERVER['HTTP_HOST'] == 'localhost') {
225 $_SERVER['HTTP_HOST'] = preg_replace(
226 '!^https?://([^/]+)/$!i',
228 $this->_config
->userFrameworkBaseURL
);
231 $class = 'CRM_Utils_System_' . $this->_config
->userFramework
;
234 if (!CRM_Utils_System
::loadBootstrap(array(), FALSE, FALSE, $civicrm_root)) {
235 $this->_log(ts("Failed to bootstrap CMS"));
239 if (strtolower($this->_entity
) == 'job') {
241 $this->_log(ts("Jobs called from cli.php require valid user as parameter"));
246 if (!empty($this->_user
)) {
247 if (!CRM_Utils_System
::authenticateScript(TRUE, $this->_user
, $this->_password
, TRUE, FALSE, FALSE)) {
248 $this->_log(ts("Failed to login as %1. Wrong username or password.", array('1' => $this->_user
)));
251 if (!$cms->loadUser($this->_user
)) {
252 $this->_log(ts("Failed to login as %1", array('1' => $this->_user
)));
263 private function _validateOptions() {
264 $required = $this->_required_arguments
;
265 while (list(, $var) = each($required)) {
267 if (empty($this->$index)) {
268 $missing_arg = '--' . $var;
269 $this->_log(ts("The %1 argument is required", array(1 => $missing_arg)));
270 $this->_log($this->_getUsage());
282 private function _sanitize($value) {
283 // restrict user input - we should not be needing anything
284 // other than normal alpha numeric plus - and _.
285 return trim(preg_replace('#^[^a-zA-Z0-9\-_=/]$#', '', $value));
291 private function _getUsage() {
292 $out = "Usage: cli.php -e entity -a action [-u user] [-s site] [--output] [PARAMS]\n";
293 $out .= " entity is the name of the entity, e.g. Contact, Event, etc.\n";
294 $out .= " action is the name of the action e.g. Get, Create, etc.\n";
295 $out .= " user is an optional username to run the script as\n";
296 $out .= " site is the domain name of the web site (for Drupal multi site installs)\n";
297 $out .= " --output will print the result from the api call\n";
298 $out .= " PARAMS is one or more --param=value combinations to pass to the api\n";
305 private function _log($error) {
306 // fixme, this should call some CRM_Core_Error:: function
307 // that properly logs
314 * class used by csv/export.php to export records from
315 * the database in a csv file format.
317 class civicrm_cli_csv_exporter
extends civicrm_cli
{
318 var $separator = ',';
322 public function __construct() {
323 $this->_required_arguments
= array('entity');
324 parent
::initialize();
327 public function run() {
328 $out = fopen("php://output", 'w');
329 fputcsv($out, $this->columns
, $this->separator
, '"');
332 $result = civicrm_api($this->_entity
, 'Get', $this->_params
);
334 foreach ($result['values'] as $row) {
336 $columns = array_keys($row);
337 fputcsv($out, $columns, $this->separator
, '"');
340 //handle values returned as arrays (i.e. custom fields that allow multiple selections) by inserting a control character
341 foreach ($row as &$field) {
342 if (is_array($field)) {
344 $field = implode($field, CRM_Core_DAO
::VALUE_SEPARATOR
) . CRM_Core_DAO
::VALUE_SEPARATOR
;
347 fputcsv($out, $row, $this->separator
, '"');
356 * base class used by both civicrm_cli_csv_import
357 * and civicrm_cli_csv_deleter to add or delete
358 * records based on those found in a csv file
359 * passed to the script.
361 class civicrm_cli_csv_file
extends civicrm_cli
{
363 var $separator = ',';
367 public function __construct() {
368 $this->_required_arguments
= array('entity', 'file');
369 $this->_additional_arguments
= array('f' => 'file');
370 parent
::initialize();
373 public function run() {
375 $handle = fopen($this->_file
, "r");
378 die("Could not open file: " . $this->_file
. ". Please provide an absolute path.\n");
382 $header = fgetcsv($handle, 0, $this->separator
);
383 // In case fgetcsv couldn't parse the header and dumped the whole line in 1 array element
384 // Try a different separator char
385 if (count($header) == 1) {
386 $this->separator
= ";";
388 $header = fgetcsv($handle, 0, $this->separator
);
389 if (count($header) == 1) {
390 die("Invalid file format for " . $this->_file
. ". It must be a valid csv with separator ',' or ';'\n");
394 $this->header
= $header;
395 while (($data = fgetcsv($handle, 0, $this->separator
)) !== FALSE) {
397 if (count($data) == 1 && is_null($data[0])) {
401 $params = $this->convertLine($data);
402 $this->processLine($params);
408 /* return a params as expected */
414 public function convertLine($data) {
416 foreach ($this->header
as $i => $field) {
417 //split any multiselect data, denoted with CRM_Core_DAO::VALUE_SEPARATOR
418 if (strpos($data[$i], CRM_Core_DAO
::VALUE_SEPARATOR
) !== FALSE) {
419 $data[$i] = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $data[$i]);
420 $data[$i] = array_combine($data[$i], $data[$i]);
422 $params[$field] = $data[$i];
424 $params['version'] = 3;
431 * class for processing records to add
432 * used by csv/import.php
435 class civicrm_cli_csv_importer
extends civicrm_cli_csv_file
{
437 * @param array $params
439 public function processline($params) {
440 $result = civicrm_api($this->_entity
, 'Create', $params);
441 if ($result['is_error']) {
442 echo "\nERROR line " . $this->row
. ": " . $result['error_message'] . "\n";
445 echo "\nline " . $this->row
. ": created " . $this->_entity
. " id: " . $result['id'] . "\n";
452 * class for processing records to delete
453 * used by csv/delete.php
456 class civicrm_cli_csv_deleter
extends civicrm_cli_csv_file
{
458 * @param array $params
460 public function processline($params) {
461 $result = civicrm_api($this->_entity
, 'Delete', $params);
462 if ($result['is_error']) {
463 echo "\nERROR line " . $this->row
. ": " . $result['error_message'] . "\n";
466 echo "\nline " . $this->row
. ": deleted\n";