3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
36 // $Id: example.drush.inc,v 1.5 2009/09/30 13:15:54 weitzman Exp $
41 * Example drush command.
43 * Shows how to make your own drush command.
45 * You can copy this file to any of the following
46 * 1. A .drush folder in your HOME folder.
47 * 2. Anywhere in a folder tree below an active module on your site.
48 * 3. In an arbitrary folder specified with the --include option.
52 * Implementation of hook_drush_command().
54 * In this hook, you specify which commands your
55 * drush module makes available, what it does and
58 * Notice how this structure closely resembles how
59 * you define menu hooks.
61 * @See drush_parse_command() for a list of recognized keys.
64 * An associative array describing your command(s).
66 function civicrm_drush_command() {
69 // the key in the $items array is the name of the command.
70 $items['civicrm-api'] = array(
71 'description' => 'CLI access to CiviCRM APIs. It can return pretty-printor json formatted data.',
74 'drush civicrm-api contact.create first_name=John last_name=Doe contact_type=Individual' => 'Create a new contact named John Doe',
75 'drush civicrm-api contact.create id=1 --out=json' => 'Find/display a contact in JSON format',
78 'in' => 'Input type: "args" (command-line), "json" (STDIN)',
79 'out' => 'Output type: "pretty" (STDOUT), "json" (STDOUT)',
81 'aliases' => array('cvapi'),
83 $items['civicrm-install'] = array(
84 'description' => "Install a new instance of CiviCRM.",
87 'dbuser' => 'MySQL username for your Drupal/CiviCRM database.',
88 'dbpass' => 'MySQL password for your Drupal/CiviCRM database.',
89 'dbhost' => 'MySQL host for your Drupal/CiviCRM database. Defaults to localhost.',
90 'dbname' => 'MySQL database name of your Drupal/CiviCRM database.',
91 'tarfile' => 'Path to your CiviCRM tar.gz file.',
92 'destination' => 'Destination modules path to extract CiviCRM (eg : sites/all/modules ).',
93 'lang' => 'Default language to use for installation.',
94 'langtarfile' => 'Path to your l10n tar.gz file.',
95 'site_url' => 'Base Url for your drupal/CiviCRM website without http (e.g. mysite.com)',
96 'ssl' => 'Using ssl for your drupal/CiviCRM website if set to on (e.g. --ssl=on)',
98 'aliases' => array('cvi'),
100 $items['civicrm-ext-list'] = array(
101 'description' => "List of CiviCRM extensions enabled.",
103 'Standard example' => 'drush civicrm-ext-list',
105 'aliases' => array('cel'),
107 $items['civicrm-ext-install'] = array(
108 'description' => "Install a CiviCRM extension.",
109 'arguments' => array(
110 'ename' => 'Extension name.',
112 'required-arguments' => TRUE,
114 'Standard example' => 'drush civicrm-ext-install civimobile',
116 'aliases' => array('cei'),
118 $items['civicrm-ext-disable'] = array(
119 'description' => "Disable a CiviCRM extension.",
120 'arguments' => array(
121 'ename' => 'Extension name.',
123 'required-arguments' => TRUE,
125 'Standard example' => 'drush civicrm-ext-disable civimobile',
127 'aliases' => array('ced'),
129 $items['civicrm-ext-uninstall'] = array(
130 'description' => "Uninstall a CiviCRM extension.",
131 'arguments' => array(
132 'ename' => 'Extension name.',
134 'required-arguments' => TRUE,
136 'Standard example' => 'drush civicrm-ext-uninstall civimobile',
138 'aliases' => array('ceui'),
141 $items['civicrm-upgrade-db'] = array(
142 'description' => "Execute the civicrm/upgrade?reset=1 process from the command line.",
143 'aliases' => array('cvupdb'),
145 $items['civicrm-update-cfg'] = array(
146 'description' => "Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.",
149 'drush -l http://example.com/civicrm civicrm-update-cfg' =>
150 'Update config_backend to correct config settings for civicrm installation on example.com site.',
152 'aliases' => array('cvupcfg'),
154 $items['civicrm-enable-debug'] = array(
155 'description' => "Enable CiviCRM Debugging.",
157 $items['civicrm-upgrade'] = array(
158 'description' => "Replace CiviCRM codebase with new specified tarfile and upgrade database by executing the CiviCRM upgrade process - civicrm/upgrade?reset=1.",
161 'drush civicrm-upgrade --tarfile=~/tarballs/civicrm-4.1.2-drupal.tar.gz' =>
162 'Replace old CiviCRM codebase with new v4.1.2 and run upgrade process.',
167 'Path of new CiviCRM tarfile, with which current CiviCRM codebase is to be replaced.',
169 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.',
171 'aliases' => array('cvup'),
173 $items['civicrm-restore'] = array(
174 'description' => 'Restore CiviCRM codebase and database back from the specified backup directory.',
177 'drush civicrm-restore --restore-dir=../backup/modules/20100309200249' =>
178 'Replace current civicrm codebase with the $restore-dir/civicrm codebase, and reload the database with $restore-dir/civicrm.sql file',
183 'Path of directory having backed up CiviCRM codebase and database.',
185 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.',
188 $items['civicrm-rest'] = array(
189 'description' => "Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.",
192 "drush civicrm-rest --query='civicrm/contact/search&json=1&key=7decb879f28ac4a0c6a92f0f7889a0c9&api_key=7decb879f28ac4a0c6a92f0f7889a0c9'" =>
193 'Use contact search api to return data in json format.',
195 // TODO: This really makes more sense as an argument.
197 array('query' => 'Query part of url. Refer CiviCRM wiki doc for more details.'),
198 'aliases' => array('cvr'),
200 $items['civicrm-sql-conf'] = array(
201 // explicit callback declaration and non-standard name to avoid collision with "sql-conf"
202 'callback' => 'drush_civicrm_sqlconf',
203 'description' => 'Print CiviCRM database connection details.',
205 $items['civicrm-sql-connect'] = array(
206 // explicit callback declaration and non-standard name to avoid collision with "sql-connect"
207 'callback' => 'drush_civicrm_sqlconnect',
208 'description' => 'A string for connecting to the CiviCRM DB.',
210 $items['civicrm-sql-dump'] = array(
211 // explicit callback declaration and non-standard name to avoid collision with "sql-dump"
212 'callback' => 'drush_civicrm_sqldump',
213 'description' => 'Exports the CiviCRM DB as SQL using mysqldump.',
215 'drush civicrm-sql-dump --result-file=../CiviCRM.sql' => 'Save SQL dump to the directory above Drupal root.',
218 'data-only' => 'Dump data without statements to create any of the schema.',
219 'gzip' => 'Compress the dump using the gzip program which must be in your $PATH.',
220 'result-file' => 'Save to a file.',
221 'tables-list' => 'comma-separated list of tables to transfer.',
224 $items['civicrm-sql-query'] = array(
225 // explicit callback declaration and non-standard name to avoid collision with "sql-query"
226 'callback' => 'drush_civicrm_sqlquery',
227 'description' => 'Execute a query against the CiviCRM database.',
229 'drush civicrm-sql-query "SELECT * FROM civicrm_contact WHERE id=1"' => 'Browse user record',
231 'arguments' => array(
232 'query' => 'A SQL query. Mandatory.',
235 $items['civicrm-sql-cli'] = array(
236 // explicit callback declaration and non-standard name to avoid collision with "sql-cli"
237 'callback' => 'drush_civicrm_sqlcli',
238 'description' => "Open a SQL command-line interface using CiviCRM's credentials.",
239 'aliases' => array('cvsqlc'),
241 $items['civicrm-process-mail-queue'] = array(
242 'description' => "Process pending CiviMail mailing jobs.",
245 'drush civicrm-process-mail-queue -u admin' =>
246 'Process CiviMail queue with admin credentials.',
249 $items['civicrm-member-records'] = array(
250 'description' => "Run the CiviMember UpdateMembershipRecord cron (civicrm-member-records).",
257 * Implementation of database specification for the active DB connection
259 function drush_civicrm_get_db_spec() {
260 if (version_compare(DRUSH_VERSION, 7, '>=')) {
261 $sql = drush_sql_get_class();
262 $db_spec = $sql->db_spec();
265 $db_spec = _drush_sql_get_db_spec();
271 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-install'
273 function drush_civicrm_install_validate() {
274 // TODO: Replace these with required options (Drush 5).
275 // Get the drupal credentials in case civi specific db info is not passed.
276 if (drush_get_option('db-url', FALSE)) {
277 $db_spec['db-url'] = $GLOBALS['db_url'];
279 elseif (drush_get_option('all', FALSE)) {
280 $db_spec = _drush_sql_get_all_db_specs();
282 if (!isset($db_spec)) {
283 $db_spec = drush_civicrm_get_db_spec();
286 if (!drush_get_option('dbuser', FALSE)) {
287 drush_set_option('dbuser', $db_spec['username']);
289 if (!drush_get_option('dbpass', FALSE)) {
290 drush_set_option('dbpass', $db_spec['password']);
292 if (!drush_get_option('dbhost', FALSE)) {
293 drush_set_option('dbhost', $db_spec['host']);
295 if (!drush_get_option('dbname', FALSE)) {
296 drush_set_option('dbname', $db_spec['database']);
299 $crmpath = _civicrm_get_crmpath();
300 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
301 $modPath = "$drupalRoot/$crmpath";
303 if (!is_dir("$modPath/civicrm") && !drush_get_option('tarfile', FALSE)) {
304 return drush_set_error('CIVICRM_INSTALL_TARFILE_NOT_SPECIFIED', dt('CiviCRM tarfile not specified.'));
306 if (drush_get_option('lang', FALSE) && !drush_get_option('langtarfile', FALSE)) {
307 return drush_set_error('CIVICRM_INSTALL_LANGTARFILE_NOT_SPECIFIED', dt('CiviCRM language tarfile not specified.'));
315 * Implementation of command 'civicrm-install'
317 function drush_civicrm_install() {
318 $dbuser = drush_get_option('dbuser', FALSE);
319 $dbpass = drush_get_option('dbpass', FALSE);
320 $dbhost = drush_get_option('dbhost', FALSE);
321 $dbname = drush_get_option('dbname', FALSE);
323 $crmpath = _civicrm_get_crmpath();
324 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
325 $modPath = "$drupalRoot/$crmpath";
326 $lang = drush_get_option('lang', '');
328 if (!is_dir("$modPath/civicrm")) {
329 // extract tarfile at right place
330 _civicrm_extract_tarfile($modPath);
331 drush_log(dt("Tarfile unpacked."), 'ok');
334 // include civicrm installer helper file
335 $civicrmInstallerHelper = "$modPath/civicrm/install/civicrm.php";
336 if (!file_exists($civicrmInstallerHelper)) {
337 return drush_set_error('CIVICRM_NOT_PRESENT', dt("CiviCRM installer helper file is missing."));
341 _civicrm_extract_tarfile($modPath, "langtarfile");
344 // setup all required files/civicrm/* directories
345 if (!_civicrm_create_files_dirs($civicrmInstallerHelper, $modPath)) {
350 _civicrm_install_db($dbuser, $dbpass, $dbhost, $dbname, $modPath, $lang);
352 // generate civicrm.settings.php file
353 _civicrm_generate_settings_file($dbuser, $dbpass, $dbhost, $dbname, $modPath);
355 module_enable(array('civicrm'));
357 drush_log(dt("CiviCRM installed."), 'ok');
360 function _civicrm_extract_tarfile($destinationPath, $option = 'tarfile') {
361 $tarpath = drush_get_option($option, FALSE);
362 if (drush_shell_exec("gzip -d " . $tarfile)) {
363 $tarpath = substr($tarfile, 0, strlen($tarfile) - 3);
365 drush_shell_exec("tar -xf $tarpath -C \"$destinationPath\"");
368 function _civicrm_install_db($dbuser, $dbpass, $dbhost, $dbname,
371 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
372 $siteRoot = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
374 $sqlPath = "$modPath/civicrm/sql";
375 $conn = @mysql_connect($dbhost, $dbuser, $dbpass);
376 if (!@mysql_select_db($dbname) &&
377 !@mysql_query("CREATE DATABASE $database")
379 drush_die(dt('CiviCRM database was not found. Failed to create one.'));
382 // setup database with civicrm structure and data
383 $dsn = "mysql://{$dbuser}:{$dbpass}@{$dbhost}/{$dbname}?new_link=true";
384 drush_log(dt("Loading CiviCRM database structure .."));
385 civicrm_source($dsn, $sqlPath . '/civicrm.mysql');
386 drush_log(dt("Loading CiviCRM database with required data .."));
387 // testing the translated sql files availability
388 $data_file = $sqlPath . '/civicrm_data.mysql';
389 $acl_file = $sqlPath . '/civicrm_acl.mysql';
391 if (file_exists($sqlPath . '/civicrm_data.' . $lang . '.mysql')
392 and file_exists($sqlPath . '/civicrm_acl.' . $lang . '.mysql')
395 $data_file = $sqlPath . '/civicrm_data.' . $lang . '.mysql';
396 $acl_file = $sqlPath . '/civicrm_acl.' . $lang . '.mysql';
399 drush_log(dt("No sql files could be retrieved for \"" . $lang .
400 "\", using default language."
404 civicrm_source($dsn, $data_file);
405 civicrm_source($dsn, $acl_file);
407 drush_log(dt("CiviCRM database loaded successfully."), 'ok');
410 function _civicrm_create_files_dirs($civicrmInstallerHelper, $modPath) {
411 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
412 $siteRoot = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
414 if (!file_exists($civicrmInstallerHelper)) {
415 return drush_set_error('CIVICRM_INSTALLER_HELP_MISSING', dt("CiviCRM installer helper file is missing."));
417 require_once "$civicrmInstallerHelper";
419 // create files/civicrm/* dirs
421 $crmPath = "$modPath/civicrm";
422 civicrm_setup("$drupalRoot/$siteRoot/files");
423 @drush_op('chmod', "$drupalRoot/$siteRoot/files/civicrm", 0777);
428 // generates civicrm.settings.php file
429 function _civicrm_generate_settings_file($dbuser, $dbpass, $dbhost, $dbname, $modPath) {
430 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
431 $siteRoot = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
432 $crmPath = "$modPath/civicrm";
435 "$crmPath/templates/CRM/common/civicrm.settings.php.template",
436 "$crmPath/templates/CRM/common/civicrm.settings.php.tpl"
439 $settingsTplFile = NULL;
440 foreach ($files as $file) {
441 if (file_exists($file)) {
442 $settingsTplFile = $file;
446 if (!$settingsTplFile) {
447 drush_die(dt("Could not find CiviCRM settings template and therefore could not create settings file."));
450 drush_log(dt("Generating civicrm settings file .."));
451 if ($baseUrl = drush_get_option('site_url', FALSE)) {
452 $ssl = drush_get_option('ssl', FALSE);
461 $baseUrl = !$baseUrl ? ($GLOBALS['base_url']) : ($protocol . '://' . $baseUrl);
462 $db_spec = drush_civicrm_get_db_spec();
464 // Check version: since 4.1, Drupal6 must be used for the UF in D6
465 // The file civicrm-version.php appeared around 4.0, so it is safe to assume
466 // that if it's not there, it's 3.x, in which case the CMS 'Drupal' is D6.
469 if (file_exists("$crmPath/civicrm-version.php")) {
470 require_once "$crmPath/civicrm-version.php";
471 $v = civicrmVersion();
476 'crmRoot' => $crmPath,
477 'templateCompileDir' => "$drupalRoot/$siteRoot/files/civicrm/templates_c",
480 'baseURL' => $baseUrl,
485 'CMSdbUser' => $db_spec['username'],
486 'CMSdbPass' => $db_spec['password'],
487 'CMSdbHost' => $db_spec['host'],
488 'CMSdbName' => $db_spec['database'],
489 'siteKey' => md5(uniqid('', TRUE) . $baseUrl),
491 $str = file_get_contents($settingsTplFile);
492 foreach ($params as $key => $value) {
493 $str = str_replace('%%' . $key . '%%', $value, $str);
497 $configFile = "$drupalRoot/$siteRoot/civicrm.settings.php";
498 civicrm_write_file($configFile, $str);
499 @drush_op('chmod', "$configFile", 0644);
500 drush_log(dt("Settings file generated: !file", array('!file' => $configFile)), 'ok');
504 * Implementation of hook_drush_help().
506 * This function is called whenever a drush user calls
507 * 'drush help <name-of-your-command>'
510 * A string with the help section (prepend with 'drush:')
513 * A string with the help text for your command.
515 function civicrm_drush_help($section) {
517 case 'drush:civicrm-upgrade-db':
518 return dt("Run civicrm/upgrade?reset=1 just as a web browser would.");
520 case 'drush:civicrm-update-cfg':
521 return dt("Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.");
523 case 'drush:civicrm-upgrade':
524 return dt("Take backups, replace CiviCRM codebase with new specified tarfile and upgrade database by executing the CiviCRM upgrade process - civicrm/upgrade?reset=1. Use civicrm-restore to revert to previous state in case anything goes wrong.");
526 case 'drush:civicrm-restore':
527 return dt("Restore CiviCRM codebase and database back from the specified backup directory.");
529 case 'drush:civicrm-rest':
530 return dt("Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.");
532 case 'drush:civicrm-sql-conf':
533 return dt('Show civicrm database connection details.');
535 case 'drush:civicrm-sql-connect':
536 return dt('A string which connects to the civicrm database.');
538 case 'drush:civicrm-sql-cli':
539 return dt('Quickly enter the mysql command line.');
541 case 'drush:civicrm-sql-dump':
542 return dt('Prints the whole CiviCRM database to STDOUT or save to a file.');
544 case 'drush:civicrm-sql-query':
545 return dt("Usage: drush [options] civicrm-sql-query <query>...\n<query> is a SQL statement, which can alternatively be passed via STDIN. Any additional arguments are passed to the mysql command directly.");
550 * Implementation of command 'civicrm-ext-list'
552 function drush_civicrm_ext_list() {
553 civicrm_initialize();
555 $result = civicrm_api('extension', 'get', array('version' => 3));
556 $rows = array(array(dt('App name'), dt('Status')));
557 foreach ($result['values'] as $k => $extension_data) {
559 $extension_data['key'],
560 $extension_data['status'],
564 drush_print_table($rows, TRUE);
566 catch (CiviCRM_API3_Exception $e) {
568 $errorMessage = $e->getMessage();
569 $errorCode = $e->getErrorCode();
570 $errorData = $e->getExtraParams();
571 drush_log(dt("!error", array('!error' => $errorData), 'error'));
576 * Implementation of command 'civicrm-ext-install'
578 function drush_civicrm_ext_install($extension_name) {
579 civicrm_initialize();
581 $result = civicrm_api('extension', 'install', array('key' => $extension_name, 'version' => 3));
582 if($result['values'] && $result['values'] == 1) {
583 drush_print(dt("Extension !ename installed.", array('!ename' => $extension_name)));
585 drush_log(t('Extension !ename could not be installed.', array('!ename' => $extension_name)), 'error');
588 catch (CiviCRM_API3_Exception $e) {
590 $errorMessage = $e->getMessage();
591 $errorCode = $e->getErrorCode();
592 $errorData = $e->getExtraParams();
593 drush_log(dt("!error", array('!error' => $errorData), 'error'));
598 * Implementation of command 'civicrm-ext-disable'
600 function drush_civicrm_ext_disable($extension_name) {
601 civicrm_initialize();
603 $result = civicrm_api('extension', 'disable', array('key' => $extension_name, 'version' => 3));
604 if($result['values'] && $result['values'] == 1) {
605 drush_print(dt("Extension !ename disabled.", array('!ename' => $extension_name)));
607 drush_log(t('Extension !ename could not be disabled.', array('!ename' => $extension_name)), 'error');
610 catch (CiviCRM_API3_Exception $e) {
612 $errorMessage = $e->getMessage();
613 $errorCode = $e->getErrorCode();
614 $errorData = $e->getExtraParams();
615 drush_log(dt("!error", array('!error' => $errorData), 'error'));
620 * Implementation of command 'civicrm-ext-uninstall'
622 function drush_civicrm_ext_uninstall($extension_name) {
623 civicrm_initialize();
625 $result = civicrm_api('extension', 'uninstall', array('key' => $extension_name, 'version' => 3));
626 if($result['values'] && $result['values'] == 1) {
627 drush_print(dt("Extension !ename uninstalled.", array('!ename' => $extension_name)));
629 drush_log(t('Extension !ename could not be uninstalled.', array('!ename' => $extension_name)), 'error');
632 catch (CiviCRM_API3_Exception $e) {
634 $errorMessage = $e->getMessage();
635 $errorCode = $e->getErrorCode();
636 $errorData = $e->getExtraParams();
637 drush_log(dt("!error", array('!error' => $errorData), 'error'));
642 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-upgrade-db'
644 function drush_civicrm_upgrade_db_validate() {
645 if (!defined('CIVICRM_UPGRADE_ACTIVE')) {
646 define('CIVICRM_UPGRADE_ACTIVE', 1);
648 $_GET['q'] = 'civicrm/upgrade';
650 if (!_civicrm_init()) {
654 $_POST['upgrade'] = 1;
655 $_GET['q'] = 'civicrm/upgrade';
656 require_once 'CRM/Core/Config.php';
658 require_once 'CRM/Utils/System.php';
659 require_once 'CRM/Core/BAO/Domain.php';
660 $codeVer = CRM_Utils_System::version();
661 $dbVer = CRM_Core_BAO_Domain::version();
663 return drush_set_error('CIVICRM_VERSION_MISSING_DATABASE', dt('Version information missing in civicrm database.'));
665 elseif (stripos($dbVer, 'upgrade')) {
666 return drush_set_error('CIVICRM_DATABASE_CHECK_FAIL', dt('Database check failed - the database looks to have been partially upgraded. You may want to reload the database with the backup and try the upgrade process again.'));
669 return drush_set_error('CIVICRM_VERSION_MISSING_CODE', dt('Version information missing in civicrm codebase.'));
671 elseif (version_compare($codeVer, $dbVer) > 0) {
672 drush_log(dt("Starting with v!dbVer -> v!codeVer upgrade ..", array('!dbVer' => $dbVer, '!codeVer' => $codeVer)));
674 elseif (version_compare($codeVer, $dbVer) < 0) {
675 return drush_set_error('CIVICRM_VERSION_UNEXPECTED', dt("Database is marked with an unexpected version '!dbVer' which is higher than that of codebase version '!codeVer'.", array('!dbVer' => $dbVer, '!codeVer' => $codeVer)));
682 * Implementation of command 'civicrm-upgrade-db'
684 function drush_civicrm_upgrade_db() {
685 if (class_exists('CRM_Upgrade_Headless')) {
686 // Note: CRM_Upgrade_Headless introduced in 4.2 -- at the same time as class auto-loading
687 $codeVer = CRM_Utils_System::version();
688 $dbVer = CRM_Core_BAO_Domain::version();
689 if (version_compare($codeVer, $dbVer) == 0) {
690 drush_print(dt("You are already upgraded to CiviCRM @version", array('@version' => $codeVer)));
693 $upgradeHeadless = new CRM_Upgrade_Headless();
694 // FIXME Exception handling?
695 $result = $upgradeHeadless->run();
696 drush_print("Upgrade outputs:\n" . $result['text']);
699 require_once 'CRM/Core/Smarty.php';
700 $template = CRM_Core_Smarty::singleton();
702 require_once ('CRM/Upgrade/Page/Upgrade.php');
703 $upgrade = new CRM_Upgrade_Page_Upgrade();
705 // new since CiviCRM 4.1
706 if (is_callable(array(
707 $upgrade, 'setPrint'))) {
708 $upgrade->setPrint(TRUE);
711 // to suppress html output /w source code.
714 // capture the required message.
715 $result = $template->get_template_vars('message');
717 drush_print("Upgrade outputs: " . "\"$result\"");
722 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-update-cfg'
724 function drush_civicrm_update_cfg_validate() {
725 return _civicrm_init();
730 * Implementation of command 'civicrm-update-cfg'
732 function drush_civicrm_update_cfg() {
733 $defaultValues = array();
734 $states = array('old', 'new');
735 for ($i = 1; $i <= 3; $i++) {
736 foreach ($states as $state) {
737 $name = "{$state}Val_{$i}";
738 $value = drush_get_option($name, NULL);
740 $defaultValues[$name] = $value;
745 require_once 'CRM/Core/I18n.php';
746 require_once 'CRM/Core/BAO/ConfigSetting.php';
747 $result = CRM_Core_BAO_ConfigSetting::doSiteMove($defaultValues);
751 drush_log(dt('Config successfully updated.'), 'completed');
754 else drush_log(dt('Config update failed.'), 'failed');
758 * Implements hook_drush_cache_clear.
760 function civicrm_drush_cache_clear(&$types) {
761 if (_civicrm_init(FALSE)) {
762 $types['civicrm'] = 'drush_civicrm_cacheclear';
767 * Cache clear callback
769 * Warning: do not name drush_civicrm_cache_clear() otherwise it will
770 * conflict with hook_drush_cache_clear() and be called systematically
771 * when "drush cc" is called.
773 function drush_civicrm_cacheclear() {
776 // Clear the classloader cache variable
777 // Should be done in CiviCRM core so that the system flush always deletes
778 // the variable, however, it needs to be done early enough before the
779 // ClassLoader initialization. FIXME.
780 variable_del('civicrm_class_loader');
782 // Flush all caches using the API
783 $params = array('version' => 3);
784 if (drush_get_option('triggers', FALSE)) {
785 $params['triggers'] = 1;
788 if (drush_get_option('sessions', FALSE)) {
789 $params['session'] = 1;
792 // Need to set API version or drush cc civicrm fails
793 $params['version'] = 3;
794 $result = civicrm_api('System', 'flush', $params);
796 if ($result['is_error']) {
797 drush_log(dt('An error occurred: !message', array('!message' => $result['error_message'])), 'error');
801 drush_log(dt('The CiviCRM cache has been cleared.'), 'ok');
805 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-enable-debug'
807 function drush_civicrm_enable_debug_validate() {
808 return _civicrm_init();
811 function drush_civicrm_enable_debug() {
813 'debug_enabled' => 1,
817 foreach ($settings as $key => $val) {
818 $result = civicrm_api('Setting', 'create', array('version' => 3, $key => $val));
820 if ($result['is_error']) {
821 drush_log(dt('An error occurred: !message', array('!message' => $result['error_message'])), 'error');
826 drush_log(dt('CiviCRM debug setting enabled.'), 'ok');
830 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-disable-debug'
832 function drush_civicrm_disable_debug_validate() {
833 return _civicrm_init();
836 function drush_civicrm_disable_debug() {
838 'debug_enabled' => 0,
842 foreach ($settings as $key => $val) {
843 $result = civicrm_api('Setting', 'create', array('version' => 3, $key => $val));
845 if ($result['is_error']) {
846 drush_log(dt('An error occurred: !message', array('!message' => $result['error_message'])), 'error');
851 drush_log(dt('CiviCRM debug setting disabled.'), 'ok');
855 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-upgrade'
857 function drush_civicrm_upgrade_validate() {
858 // TODO: use Drush to download tarfile.
859 // TODO: if tarfile is not specified, see if the code already exists and use that instead.
860 $tarfile = drush_get_option('tarfile', FALSE);
862 return drush_set_error('CIVICRM_TAR_NOT_SPECIFIED', dt('Tarfile not specified.'));
864 //FIXME: throw error if tarfile is not in a valid format.
866 if (!defined('CIVICRM_UPGRADE_ACTIVE')) {
867 define('CIVICRM_UPGRADE_ACTIVE', 1);
869 return _civicrm_init();
873 * Implementation of command 'civicrm-upgrade'
875 function drush_civicrm_upgrade() {
876 global $civicrm_root;
878 $tarfile = drush_get_option('tarfile', FALSE);
879 $date = date('YmdHis');
880 $backup_file = "civicrm";
882 $basepath = explode('/', $civicrm_root);
883 array_pop($basepath);
884 $project_path = implode('/', $basepath) . '/';
886 $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
887 $backup_dir = drush_get_option('backup-dir', $drupal_root . '/../backup');
888 $backup_dir = rtrim($backup_dir, '/');
890 drush_print(dt("\nThe upgrade process involves - "));
891 drush_print(dt("1. Backing up current CiviCRM code as => !path",
892 array('!path' => "$backup_dir/modules/$date/$backup_file")
894 drush_print(dt("2. Backing up database as => !path",
895 array('!path' => "$backup_dir/modules/$date/$backup_file.sql")
897 drush_print(dt("3. Unpacking tarfile to => !path",
898 array('!path' => "$project_path")
900 drush_print(dt("4. Executing civicrm/upgrade?reset=1 just as a browser would.\n"));
901 if (!drush_confirm(dt('Do you really want to continue?'))) {
902 return drush_user_abort();
905 @drush_op('mkdir', $backup_dir, 0777);
906 $backup_dir .= '/modules';
907 @drush_op('mkdir', $backup_dir, 0777);
908 $backup_dir .= "/$date";
909 @drush_op('mkdir', $backup_dir, 0777);
910 $backup_target = $backup_dir . '/' . $backup_file;
911 if (!drush_op('rename', $civicrm_root, $backup_target)) {
912 return drush_set_error('CIVICRM_BACKUP_FAILED', dt('Failed to backup CiviCRM project directory !source to !backup_target',
913 array('!source' => $civicrm_root, '!backup_target' => $backup_target)
916 drush_log(dt("\n1. Code backed up."), 'ok');
918 drush_set_option('result-file', $backup_target . '.sql');
919 drush_civicrm_sqldump();
920 drush_log(dt('2. Database backed up.'), 'ok');
922 // Decompress & Untar
923 _civicrm_extract_tarfile($project_path);
924 drush_log(dt('3. Tarfile unpacked.'), 'ok');
926 drush_log(dt("4. "));
928 if (drush_civicrm_upgrade_db_validate()) {
929 drush_civicrm_upgrade_db();
931 drush_log(dt("\nProcess completed."), 'completed');
935 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-restore'
937 function drush_civicrm_restore_validate() {
940 $restore_dir = drush_get_option('restore-dir', FALSE);
941 $restore_dir = rtrim($restore_dir, '/');
943 return drush_set_error('CIVICRM_RESTORE_NOT_SPECIFIED', dt('Restore-dir not specified.'));
945 $sql_file = $restore_dir . '/civicrm.sql';
946 if (!file_exists($sql_file)) {
947 return drush_set_error('CIVICRM_RESTORE_CIVICRM_SQL_NOT_FOUND', dt('Could not locate civicrm.sql file in the restore directory.'));
949 $code_dir = $restore_dir . '/civicrm';
950 if (!is_dir($code_dir)) {
951 return drush_set_error('CIVICRM_RESTORE_DIR_NOT_FOUND', dt('Could not locate civicrm directory inside restore-dir.'));
953 elseif (!file_exists("$code_dir/civicrm-version.php")) {
954 return drush_set_error('CIVICRM_RESTORE_DIR_NOT_VALID', dt('civicrm directory inside restore-dir, doesn\'t look to be a valid civicrm codebase.'));
961 * Implementation of command 'civicrm-restore'
963 function drush_civicrm_restore() {
964 $restore_dir = drush_get_option('restore-dir', FALSE);
965 $restore_dir = rtrim($restore_dir, '/');
966 $sql_file = $restore_dir . '/civicrm.sql';
967 $code_dir = $restore_dir . '/civicrm';
968 $date = date('YmdHis');
970 global $civicrm_root;
971 $civicrm_root_base = explode('/', $civicrm_root);
972 array_pop($civicrm_root_base);
973 $civicrm_root_base = implode('/', $civicrm_root_base) . '/';
975 $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
976 $restore_backup_dir = drush_get_option('backup-dir', $drupal_root . '/../backup');
977 $restore_backup_dir = rtrim($restore_backup_dir, '/');
979 // get confirmation from user -
980 $db_spec = drush_civicrm_get_db_spec();
981 drush_print(dt("\nProcess involves :"));
982 drush_print(dt("1. Restoring '\$restore-dir/civicrm' directory to '!toDir'.", array('!toDir' => $civicrm_root_base)));
983 drush_print(dt("2. Dropping and creating '!db' database.", array('!db' => $db_spec['database'])));
984 drush_print(dt("3. Loading '\$restore-dir/civicrm.sql' file into the database."));
986 drush_print(dt("Note: Before restoring a backup will be taken in '!path' directory.",
987 array('!path' => "$restore_backup_dir/modules/restore")
990 if (!drush_confirm(dt('Do you really want to continue?'))) {
991 return drush_user_abort();
994 // create restore-backup-dir if not already exists
995 @drush_op('mkdir', $restore_backup_dir, 0777);
996 $restore_backup_dir .= '/modules';
997 @drush_op('mkdir', $restore_backup_dir, 0777);
998 $restore_backup_dir .= '/restore';
999 @drush_op('mkdir', $restore_backup_dir, 0777);
1000 $restore_backup_dir .= "/$date";
1001 @drush_op('mkdir', $restore_backup_dir, 0777);
1003 // 1. backup and restore codebase
1004 drush_log(dt('Restoring civicrm codebase ..'));
1005 if (is_dir($civicrm_root) && !drush_op('rename', $civicrm_root, $restore_backup_dir . '/civicrm')) {
1006 return drush_set_error('CIVICRM_RESTORE_CODE_FAILED', dt("Failed to take backup for '!destination' directory",
1007 array('!destination' => $civicrm_root)
1010 if (!drush_op('rename', $code_dir, $civicrm_root)) {
1011 return drush_set_error('CIVICRM_RESTORE_DESTINATION_FAILED', dt("Failed to restore civicrm directory '!source' to '!dest'",
1012 array('!source' => $code_dir, '!dest' => $civicrm_root_base)
1015 drush_log(dt('Codebase restored.'), 'ok');
1017 // 2. backup, drop and create database
1018 drush_set_option('result-file', $restore_backup_dir . '/civicrm.sql');
1019 drush_civicrm_sqldump();
1021 drush_log(dt('Database backed up.'), 'ok');
1023 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1024 $sql = drush_sql_get_class();
1025 $exec = 'mysql ' . $sql->creds() . ' -e ';
1026 $dbDriver = $db_spec['driver'];
1029 $exec = 'mysql' . _drush_sql_get_credentials() . ' -e ';
1030 $dbDriver = _drush_sql_get_scheme();
1032 drush_log(dt("\nDropping database '!db' ..", array('!db' => $db_spec['database'])));
1033 if (drush_op('system', $exec . '"DROP DATABASE IF EXISTS ' . $db_spec['database'] . '"')) {
1034 return drush_set_error('CIVICRM_RESTORE_DATABASE_DROP_FAILED', dt('Could not drop database: @name', array('@name' => $db_spec['database'])));
1036 drush_log(dt('Database dropped.'), 'ok');
1037 $exec = str_replace($db_spec['database'], '', $exec);
1038 if (drush_op('system', $exec . '"CREATE DATABASE ' . $db_spec['database'] . '"')) {
1039 return drush_set_error('CIVICRM_RESTORE_DATABASE_CREATE_FAILED', dt('Could not create new database: @name', array('@name' => $db_spec['database'])));
1041 drush_log(dt('Database created.'), 'ok');
1043 // 3. restore database
1044 switch ($dbDriver) {
1046 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1047 $send = 'mysql ' . $sql->creds();
1050 $send = 'mysql' . _drush_sql_get_credentials();
1055 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1056 $send .= 'psql -d ' . $sql->creds() . ' --file -';
1059 $send .= 'psql -d ' . _drush_sql_get_credentials() . ' --file -';
1063 $exec = "$send < $sql_file";
1064 drush_log(dt('Loading civicrm.sql file from restore-dir ..'));
1065 drush_op('system', $exec);
1066 drush_log(dt('Database restored.'), 'ok');
1068 drush_log(dt('Restore process completed.'), 'completed');
1070 _civicrm_dsn_close();
1074 * ?? for command 'civicrm-civimail'
1076 function drush_civicrm_civimail_cron() {
1077 civicrm_api('Mailing', 'Process', array('version' => 3));
1081 * Implementation of command 'civicrm-member-records'
1083 function drush_civicrm_member_records() {
1086 $_REQUEST['name'] = drush_get_option('civicrm_cron_username', NULL);
1087 $_REQUEST['pass'] = drush_get_option('civicrm_cron_password', NULL);
1088 $_REQUEST['key'] = drush_get_option('civicrm_sitekey', NULL);
1093 1 => "-u" . $_REQUEST['name'],
1094 2 => "-p" . $_REQUEST['pass'],
1095 3 => "-s" . drush_get_option('uri', FALSE),
1098 if (!defined('CIVICRM_CONFDIR')) {
1099 define('CIVICRM_CONFDIR', drush_get_context('DRUSH_DRUPAL_ROOT') . '/sites/');
1102 include "bin/UpdateMembershipRecord.php";
1106 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-rest' ('cvr')
1108 function drush_civicrm_rest_validate() {
1109 $query = drush_get_option('query', FALSE);
1111 drush_set_error('CIVICRM_REST_EMPTY_QUERY', dt('query not specified.'));
1114 return _civicrm_init();
1118 * Implementation of command 'civicrm-rest' ('cvr')
1120 function drush_civicrm_rest() {
1121 $query = drush_get_option('query', FALSE);
1122 $query = explode('&', $query);
1123 $_GET['q'] = array_shift($query);
1124 foreach ($query as $keyVal) {
1125 list($key, $val) = explode('=', $keyVal);
1126 $_REQUEST[$key] = $val;
1130 require_once 'CRM/Utils/REST.php';
1131 $rest = new CRM_Utils_REST();
1133 require_once 'CRM/Core/Config.php';
1134 $config = CRM_Core_Config::singleton();
1136 global $civicrm_root;
1137 // adding dummy script, since based on this api file path is computed.
1138 $_SERVER['SCRIPT_FILENAME'] = "$civicrm_root/extern/rest.php";
1140 if (isset($_GET['json']) &&
1143 header('Content-Type: text/javascript');
1146 header('Content-Type: text/xml');
1148 echo $rest->run($config);
1152 * Implements drush_hook_pre_COMMAND().
1154 * this function is called when using drush 6.
1156 function drush_civicrm_pre_civicrm_sql_dump() {
1157 _civicrm_dsn_init();
1161 * Implements drush_hook_pre_COMMAND().
1163 * this function is called when using drush 5.
1165 function drush_civicrm_pre_civicrm_sqldump() {
1166 _civicrm_dsn_init();
1170 * Implementation of command 'civicrm-sql-dump'
1172 function drush_civicrm_sqldump() {
1173 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1177 drush_sql_dump_execute();
1182 * Implements drush_hook_post_COMMAND().
1184 * this function is called when using drush 6.
1186 function drush_civicrm_post_civicrm_sql_dump() {
1187 _civicrm_dsn_close();
1191 * Implements drush_hook_post_COMMAND().
1193 * this function is called when using drush 5.
1195 function drush_civicrm_post_civicrm_sqldump() {
1196 _civicrm_dsn_close();
1200 * Implements drush_hook_pre_COMMAND().
1202 * this function is called when using drush 6.
1204 function drush_civicrm_pre_civicrm_sql_conf() {
1205 _civicrm_dsn_init();
1209 * Implements drush_hook_post_COMMAND().
1211 * this function is called when using drush 5.
1213 function drush_civicrm_pre_civicrm_sqlconf() {
1214 _civicrm_dsn_init();
1218 * Implementation of command 'civicrm-sql-conf'
1220 function drush_civicrm_sqlconf() {
1221 $conf = drush_sql_conf();
1222 // Before drush 6 drush_sql_conf already does drush_print_r, so it shouldn't
1224 if (version_compare(DRUSH_VERSION, 6, '>=')) {
1225 drush_print_r($conf);
1230 * Implements drush_hook_post_COMMAND().
1232 * this function is called when using drush 6.
1234 function drush_civicrm_post_civicrm_sql_conf() {
1235 _civicrm_dsn_close();
1239 * Implements drush_hook_post_COMMAND().
1241 * this function is called when using drush 5.
1243 function drush_civicrm_post_civicrm_sqlconf() {
1244 _civicrm_dsn_close();
1248 * Implements drush_hook_pre_COMMAND().
1250 * this function is called when using drush 6.
1252 function drush_civicrm_pre_civicrm_sql_connect() {
1253 _civicrm_dsn_init();
1257 * Implements drush_hook_pre_COMMAND().
1259 * this function is called when using drush 5.
1261 function drush_civicrm_pre_civicrm_sqlconnect() {
1262 _civicrm_dsn_init();
1266 * Implementation of command 'civicrm-sql-connect'
1268 function drush_civicrm_sqlconnect() {
1269 return drush_sql_connect();
1273 * Implements drush_hook_post_COMMAND().
1275 * this function is called when using drush 6.
1277 function drush_civicrm_post_civicrm_sql_connect() {
1278 _civicrm_dsn_close();
1282 * Implements drush_hook_post_COMMAND().
1284 * this function is called when using drush 5.
1286 function drush_civicrm_post_civicrm_sqlconnect() {
1287 _civicrm_dsn_close();
1291 * Implements drush_hook_pre_COMMAND().
1293 * this function is called when using drush 6.
1295 function drush_civicrm_pre_civicrm_sql_query() {
1296 _civicrm_dsn_init();
1300 * Implements drush_hook_pre_COMMAND().
1302 * this function is called when using drush 5.
1304 function drush_civicrm_pre_civicrm_sqlquery() {
1305 _civicrm_dsn_init();
1309 * Implementation of command 'civicrm-sql-query'
1311 function drush_civicrm_sqlquery($query) {
1312 return drush_sql_query($query);
1316 * Implements drush_hook_post_COMMAND().
1318 * this function is called when using drush 6.
1320 function drush_civicrm_post_civicrm_sql_query() {
1321 _civicrm_dsn_close();
1325 * Implements drush_hook_post_COMMAND().
1327 * this function is called when using drush 5.
1329 function drush_civicrm_post_civicrm_sqlquery() {
1330 _civicrm_dsn_close();
1334 * Implements drush_hook_pre_COMMAND().
1336 * this function is called when using drush 6.
1338 function drush_civicrm_pre_civicrm_sql_cli() {
1339 _civicrm_dsn_init();
1343 * Implements drush_hook_pre_COMMAND().
1345 * this function is called when using drush 5.
1347 function drush_civicrm_pre_civicrm_sqlcli() {
1348 _civicrm_dsn_init();
1352 * Implementation of command 'civicrm-sql-cli'
1354 function drush_civicrm_sqlcli() {
1359 * Implements drush_hook_post_COMMAND().
1361 * this function is called when using drush 6.
1363 function drush_civicrm_post_civicrm_sql_cli() {
1364 _civicrm_dsn_close();
1368 * Implements drush_hook_post_COMMAND().
1370 * this function is called when using drush 5.
1372 function drush_civicrm_post_civicrm_sqlcli() {
1373 _civicrm_dsn_close();
1376 function _civicrm_dsn_init($reset = FALSE) {
1377 static $globalDbUrl = NULL;
1379 if (!_civicrm_init()) {
1383 // check if we're using the old-style $GLOBALS['db_url']
1384 // or the new style ( > drupal 7 )
1385 if (drush_drupal_major_version() >= 7) {
1386 $database = drush_get_option('database', 'default');
1387 $target = drush_get_option('target', 'default');
1388 if (!$globalDbUrl && CIVICRM_DSN) {
1389 if (isset($GLOBALS['databases'][$database][$target])) {
1390 // keep a copy so that we can put it back.
1391 $globalDbUrl = $GLOBALS['databases'][$database][$target];
1393 // now modify $GLOBALS so that drush works on CIVICRM_DSN instead of drupal's
1394 $GLOBALS['databases'][$database][$target] = drush_convert_db_from_db_url(CIVICRM_DSN);
1398 if (!$globalDbUrl && CIVICRM_DSN) {
1399 // keep a copy so that we can put it back.
1400 $globalDbUrl = $GLOBALS['db_url'];
1402 // now modify $GLOBALS so that drush works on CIVICRM_DSN instead of drupal's
1403 $GLOBALS['db_url'] = CIVICRM_DSN;
1405 $dbUrl = $globalDbUrl;
1406 $globalDbUrl = $reset ? NULL : $globalDbUrl;
1411 function _civicrm_dsn_close() {
1412 $globalDbUrl = _civicrm_dsn_init(TRUE);
1414 if (drush_drupal_major_version() >= 7) {
1415 $database = drush_get_option('database', 'default');
1416 $target = drush_get_option('target', 'default');
1417 $GLOBALS['databases'][$database][$target] = $globalDbUrl;
1420 $GLOBALS['db_url'] = $globalDbUrl;
1426 * Initializes the CiviCRM environment and configuration.
1427 * TODO: document why we can't call civicrm_initialize() directly.
1430 * If true, will halt drush. Otherwise, return false but do not interrupt.
1433 * Returns TRUE if CiviCRM was initialized.
1435 function _civicrm_init($fail = TRUE) {
1436 static $init = NULL;
1438 // return if already initialized
1444 $cmsPath = $drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
1445 $site_root = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
1446 $civicrmSettingsFile = "$drupal_root/$site_root/civicrm.settings.php";
1448 if (!file_exists($civicrmSettingsFile)) {
1449 $sites_subdir = drush_get_option('sites-subdir', 'default');
1450 $civicrmSettingsFile = "$drupal_root/sites/$sites_subdir/civicrm.settings.php";
1451 if (!file_exists($civicrmSettingsFile)) {
1453 return drush_set_error('CIVICRM_INIT_SETTINGS_NOT_FOUND', dt('Could not locate civicrm settings file.'));
1460 // include settings file
1461 define('CIVICRM_SETTINGS_PATH', $civicrmSettingsFile);
1462 include_once $civicrmSettingsFile;
1463 global $civicrm_root;
1464 if (!is_dir($civicrm_root)) {
1465 return drush_set_error('CIVICRM_INIT_CODEBASE_NOT_FOUND', dt('Could not locate CiviCRM codebase. Make sure CiviCRM settings file has correct information.'));
1468 // Autoload was added in 4.2
1469 require_once 'CRM/Utils/System.php';
1470 $codeVer = CRM_Utils_System::version();
1472 if (substr($codeVer, 0, 3) >= '4.2') {
1473 require_once $civicrm_root . '/CRM/Core/ClassLoader.php';
1474 CRM_Core_ClassLoader::singleton()->register();
1477 // also initialize config object
1478 require_once 'CRM/Core/Config.php';
1479 $config = CRM_Core_Config::singleton();
1485 function _civicrm_get_crmpath() {
1486 if (!$crmpath = drush_get_option('destination', FALSE)) {
1487 $crmpath = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE) . '/modules/';
1488 if (!is_dir($crmpath)) {
1489 $crmpath = "sites/all/modules";
1498 * Implementation of command 'civicrm-api'
1500 function drush_civicrm_api() {
1501 $DEFAULTS = array('version' => 3);
1503 $args = func_get_args();
1504 list($entity, $action) = explode('.', $args[0]);
1508 switch (drush_get_option('in', 'args')) {
1510 $params = $DEFAULTS;
1511 foreach ($args as $arg) {
1512 preg_match('/^([^=]+)=(.*)$/', $arg, $matches);
1513 $params[$matches[1]] = $matches[2];
1518 $json = stream_get_contents(STDIN);
1520 $params = $DEFAULTS;
1523 $params = array_merge($DEFAULTS, json_decode($json, TRUE));
1528 drush_set_error(dt('Unknown format: @format', array('@format' => $format)));
1532 civicrm_initialize();
1535 CRM_Core_BAO_UFMatch::synchronize($user, FALSE, 'Drupal',
1536 civicrm_get_ctype('Individual')
1539 $result = civicrm_api($entity, $action, $params);
1541 switch (drush_get_option('out', 'pretty')) {
1543 drush_print_r($result);
1547 drush_print(json_encode($result));
1551 return drush_set_error('CIVICRM_UNKNOWN_FORMAT', dt('Unknown format: @format', array('@format' => $format)));