commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-old / civicrm / drupal / drush / civicrm.drush.inc
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35
36 // $Id: example.drush.inc,v 1.5 2009/09/30 13:15:54 weitzman Exp $
37
38
39 /**
40 * @file
41 * Example drush command.
42 *
43 * Shows how to make your own drush command.
44 *
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.
49 */
50
51 /**
52 * Implementation of hook_drush_command().
53 *
54 * In this hook, you specify which commands your
55 * drush module makes available, what it does and
56 * description.
57 *
58 * Notice how this structure closely resembles how
59 * you define menu hooks.
60 *
61 * @See drush_parse_command() for a list of recognized keys.
62 *
63 * @return
64 * An associative array describing your command(s).
65 */
66 function civicrm_drush_command() {
67 $items = array();
68
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.',
72 'examples' =>
73 array(
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',
76 ),
77 'options' => array(
78 'in' => 'Input type: "args" (command-line), "json" (STDIN)',
79 'out' => 'Output type: "pretty" (STDOUT), "json" (STDOUT)',
80 ),
81 'aliases' => array('cvapi'),
82 );
83 $items['civicrm-install'] = array(
84 'description' => "Install a new instance of CiviCRM.",
85 'options' =>
86 array(
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)',
97 ),
98 'aliases' => array('cvi'),
99 );
100 $items['civicrm-ext-list'] = array(
101 'description' => "List of CiviCRM extensions enabled.",
102 'examples' => array(
103 'Standard example' => 'drush civicrm-ext-list',
104 ),
105 'aliases' => array('cel'),
106 );
107 $items['civicrm-ext-install'] = array(
108 'description' => "Install a CiviCRM extension.",
109 'arguments' => array(
110 'ename' => 'Extension name.',
111 ),
112 'required-arguments' => TRUE,
113 'examples' => array(
114 'Standard example' => 'drush civicrm-ext-install civimobile',
115 ),
116 'aliases' => array('cei'),
117 );
118 $items['civicrm-ext-disable'] = array(
119 'description' => "Disable a CiviCRM extension.",
120 'arguments' => array(
121 'ename' => 'Extension name.',
122 ),
123 'required-arguments' => TRUE,
124 'examples' => array(
125 'Standard example' => 'drush civicrm-ext-disable civimobile',
126 ),
127 'aliases' => array('ced'),
128 );
129 $items['civicrm-ext-uninstall'] = array(
130 'description' => "Uninstall a CiviCRM extension.",
131 'arguments' => array(
132 'ename' => 'Extension name.',
133 ),
134 'required-arguments' => TRUE,
135 'examples' => array(
136 'Standard example' => 'drush civicrm-ext-uninstall civimobile',
137 ),
138 'aliases' => array('ceui'),
139 );
140
141 $items['civicrm-upgrade-db'] = array(
142 'description' => "Execute the civicrm/upgrade?reset=1 process from the command line.",
143 'aliases' => array('cvupdb'),
144 );
145 $items['civicrm-update-cfg'] = array(
146 'description' => "Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.",
147 'examples' =>
148 array(
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.',
151 ),
152 'aliases' => array('cvupcfg'),
153 );
154 $items['civicrm-enable-debug'] = array(
155 'description' => "Enable CiviCRM Debugging.",
156 );
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.",
159 'examples' =>
160 array(
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.',
163 ),
164 'options' =>
165 array(
166 'tarfile' =>
167 'Path of new CiviCRM tarfile, with which current CiviCRM codebase is to be replaced.',
168 'backup-dir' =>
169 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.',
170 ),
171 'aliases' => array('cvup'),
172 );
173 $items['civicrm-restore'] = array(
174 'description' => 'Restore CiviCRM codebase and database back from the specified backup directory.',
175 'examples' =>
176 array(
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',
179 ),
180 'options' =>
181 array(
182 'restore-dir' =>
183 'Path of directory having backed up CiviCRM codebase and database.',
184 'backup-dir' =>
185 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.',
186 ),
187 );
188 $items['civicrm-rest'] = array(
189 'description' => "Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.",
190 'examples' =>
191 array(
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.',
194 ),
195 // TODO: This really makes more sense as an argument.
196 'options' =>
197 array('query' => 'Query part of url. Refer CiviCRM wiki doc for more details.'),
198 'aliases' => array('cvr'),
199 );
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.',
204 );
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.',
209 );
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.',
214 'examples' => array(
215 'drush civicrm-sql-dump --result-file=../CiviCRM.sql' => 'Save SQL dump to the directory above Drupal root.',
216 ),
217 'options' => array(
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.',
222 ),
223 );
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.',
228 'examples' => array(
229 'drush civicrm-sql-query "SELECT * FROM civicrm_contact WHERE id=1"' => 'Browse user record',
230 ),
231 'arguments' => array(
232 'query' => 'A SQL query. Mandatory.',
233 ),
234 );
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'),
240 );
241 $items['civicrm-process-mail-queue'] = array(
242 'description' => "Process pending CiviMail mailing jobs.",
243 'examples' =>
244 array(
245 'drush civicrm-process-mail-queue -u admin' =>
246 'Process CiviMail queue with admin credentials.',
247 ),
248 );
249 $items['civicrm-member-records'] = array(
250 'description' => "Run the CiviMember UpdateMembershipRecord cron (civicrm-member-records).",
251 );
252
253 return $items;
254 }
255
256 /**
257 * Implementation of database specification for the active DB connection
258 */
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();
263 }
264 else {
265 $db_spec = _drush_sql_get_db_spec();
266 }
267 return $db_spec;
268 }
269
270 /**
271 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-install'
272 */
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'];
278 }
279 elseif (drush_get_option('all', FALSE)) {
280 $db_spec = _drush_sql_get_all_db_specs();
281 }
282 if (!isset($db_spec)) {
283 $db_spec = drush_civicrm_get_db_spec();
284 }
285
286 if (!drush_get_option('dbuser', FALSE)) {
287 drush_set_option('dbuser', $db_spec['username']);
288 }
289 if (!drush_get_option('dbpass', FALSE)) {
290 drush_set_option('dbpass', $db_spec['password']);
291 }
292 if (!drush_get_option('dbhost', FALSE)) {
293 drush_set_option('dbhost', $db_spec['host']);
294 }
295 if (!drush_get_option('dbname', FALSE)) {
296 drush_set_option('dbname', $db_spec['database']);
297 }
298
299 $crmpath = _civicrm_get_crmpath();
300 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
301 $modPath = "$drupalRoot/$crmpath";
302
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.'));
305 }
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.'));
308 }
309
310 return TRUE;
311 }
312
313
314 /**
315 * Implementation of command 'civicrm-install'
316 */
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);
322
323 $crmpath = _civicrm_get_crmpath();
324 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
325 $modPath = "$drupalRoot/$crmpath";
326 $lang = drush_get_option('lang', '');
327
328 if (!is_dir("$modPath/civicrm")) {
329 // extract tarfile at right place
330 _civicrm_extract_tarfile($modPath);
331 drush_log(dt("Tarfile unpacked."), 'ok');
332 }
333
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."));
338 }
339
340 if ($lang != '') {
341 _civicrm_extract_tarfile($modPath, "langtarfile");
342 }
343
344 // setup all required files/civicrm/* directories
345 if (!_civicrm_create_files_dirs($civicrmInstallerHelper, $modPath)) {
346 return FALSE;
347 }
348
349 // install database
350 _civicrm_install_db($dbuser, $dbpass, $dbhost, $dbname, $modPath, $lang);
351
352 // generate civicrm.settings.php file
353 _civicrm_generate_settings_file($dbuser, $dbpass, $dbhost, $dbname, $modPath);
354
355 module_enable(array('civicrm'));
356
357 drush_log(dt("CiviCRM installed."), 'ok');
358 }
359
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);
364 }
365 drush_shell_exec("tar -xf $tarpath -C \"$destinationPath\"");
366 }
367
368 function _civicrm_install_db($dbuser, $dbpass, $dbhost, $dbname,
369 $modPath, $lang
370 ) {
371 $drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
372 $siteRoot = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
373
374 $sqlPath = "$modPath/civicrm/sql";
375 $conn = @mysql_connect($dbhost, $dbuser, $dbpass);
376 if (!@mysql_select_db($dbname) &&
377 !@mysql_query("CREATE DATABASE $database")
378 ) {
379 drush_die(dt('CiviCRM database was not found. Failed to create one.'));
380 }
381
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';
390 if ($lang != '') {
391 if (file_exists($sqlPath . '/civicrm_data.' . $lang . '.mysql')
392 and file_exists($sqlPath . '/civicrm_acl.' . $lang . '.mysql')
393 and $lang != ''
394 ) {
395 $data_file = $sqlPath . '/civicrm_data.' . $lang . '.mysql';
396 $acl_file = $sqlPath . '/civicrm_acl.' . $lang . '.mysql';
397 }
398 else {
399 drush_log(dt("No sql files could be retrieved for \"" . $lang .
400 "\", using default language."
401 ), 'warning');
402 }
403 }
404 civicrm_source($dsn, $data_file);
405 civicrm_source($dsn, $acl_file);
406
407 drush_log(dt("CiviCRM database loaded successfully."), 'ok');
408 }
409
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);
413
414 if (!file_exists($civicrmInstallerHelper)) {
415 return drush_set_error('CIVICRM_INSTALLER_HELP_MISSING', dt("CiviCRM installer helper file is missing."));
416 }
417 require_once "$civicrmInstallerHelper";
418
419 // create files/civicrm/* dirs
420 global $crmPath;
421 $crmPath = "$modPath/civicrm";
422 civicrm_setup("$drupalRoot/$siteRoot/files");
423 @drush_op('chmod', "$drupalRoot/$siteRoot/files/civicrm", 0777);
424
425 return TRUE;
426 }
427
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";
433
434 $files = array(
435 "$crmPath/templates/CRM/common/civicrm.settings.php.template",
436 "$crmPath/templates/CRM/common/civicrm.settings.php.tpl"
437 );
438
439 $settingsTplFile = NULL;
440 foreach ($files as $file) {
441 if (file_exists($file)) {
442 $settingsTplFile = $file;
443 }
444 }
445
446 if (!$settingsTplFile) {
447 drush_die(dt("Could not find CiviCRM settings template and therefore could not create settings file."));
448 }
449
450 drush_log(dt("Generating civicrm settings file .."));
451 if ($baseUrl = drush_get_option('site_url', FALSE)) {
452 $ssl = drush_get_option('ssl', FALSE);
453 if ($ssl == 'on') {
454 $protocol = 'https';
455 }
456 else {
457 $protocol = 'http';
458 }
459 }
460
461 $baseUrl = !$baseUrl ? ($GLOBALS['base_url']) : ($protocol . '://' . $baseUrl);
462 $db_spec = drush_civicrm_get_db_spec();
463
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.
467 $cms = 'Drupal';
468
469 if (file_exists("$crmPath/civicrm-version.php")) {
470 require_once "$crmPath/civicrm-version.php";
471 $v = civicrmVersion();
472 $cms = $v['cms'];
473 }
474
475 $params = array(
476 'crmRoot' => $crmPath,
477 'templateCompileDir' => "$drupalRoot/$siteRoot/files/civicrm/templates_c",
478 'frontEnd' => 0,
479 'cms' => $cms,
480 'baseURL' => $baseUrl,
481 'dbUser' => $dbuser,
482 'dbPass' => $dbpass,
483 'dbHost' => $dbhost,
484 'dbName' => $dbname,
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),
490 );
491 $str = file_get_contents($settingsTplFile);
492 foreach ($params as $key => $value) {
493 $str = str_replace('%%' . $key . '%%', $value, $str);
494 }
495 $str = trim($str);
496
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');
501 }
502
503 /**
504 * Implementation of hook_drush_help().
505 *
506 * This function is called whenever a drush user calls
507 * 'drush help <name-of-your-command>'
508 *
509 * @param
510 * A string with the help section (prepend with 'drush:')
511 *
512 * @return
513 * A string with the help text for your command.
514 */
515 function civicrm_drush_help($section) {
516 switch ($section) {
517 case 'drush:civicrm-upgrade-db':
518 return dt("Run civicrm/upgrade?reset=1 just as a web browser would.");
519
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.");
522
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.");
525
526 case 'drush:civicrm-restore':
527 return dt("Restore CiviCRM codebase and database back from the specified backup directory.");
528
529 case 'drush:civicrm-rest':
530 return dt("Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.");
531
532 case 'drush:civicrm-sql-conf':
533 return dt('Show civicrm database connection details.');
534
535 case 'drush:civicrm-sql-connect':
536 return dt('A string which connects to the civicrm database.');
537
538 case 'drush:civicrm-sql-cli':
539 return dt('Quickly enter the mysql command line.');
540
541 case 'drush:civicrm-sql-dump':
542 return dt('Prints the whole CiviCRM database to STDOUT or save to a file.');
543
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.");
546 }
547 }
548
549 /**
550 * Implementation of command 'civicrm-ext-list'
551 */
552 function drush_civicrm_ext_list() {
553 civicrm_initialize();
554 try{
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) {
558 $rows[] = array(
559 $extension_data['key'],
560 $extension_data['status'],
561 );
562 }
563 unset($result);
564 drush_print_table($rows, TRUE);
565 }
566 catch (CiviCRM_API3_Exception $e) {
567 // handle error here
568 $errorMessage = $e->getMessage();
569 $errorCode = $e->getErrorCode();
570 $errorData = $e->getExtraParams();
571 drush_log(dt("!error", array('!error' => $errorData), 'error'));
572 }
573 }
574
575 /**
576 * Implementation of command 'civicrm-ext-install'
577 */
578 function drush_civicrm_ext_install($extension_name) {
579 civicrm_initialize();
580 try{
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)));
584 } else {
585 drush_log(t('Extension !ename could not be installed.', array('!ename' => $extension_name)), 'error');
586 }
587 }
588 catch (CiviCRM_API3_Exception $e) {
589 // handle error here
590 $errorMessage = $e->getMessage();
591 $errorCode = $e->getErrorCode();
592 $errorData = $e->getExtraParams();
593 drush_log(dt("!error", array('!error' => $errorData), 'error'));
594 }
595 }
596
597 /**
598 * Implementation of command 'civicrm-ext-disable'
599 */
600 function drush_civicrm_ext_disable($extension_name) {
601 civicrm_initialize();
602 try{
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)));
606 } else {
607 drush_log(t('Extension !ename could not be disabled.', array('!ename' => $extension_name)), 'error');
608 }
609 }
610 catch (CiviCRM_API3_Exception $e) {
611 // handle error here
612 $errorMessage = $e->getMessage();
613 $errorCode = $e->getErrorCode();
614 $errorData = $e->getExtraParams();
615 drush_log(dt("!error", array('!error' => $errorData), 'error'));
616 }
617 }
618
619 /**
620 * Implementation of command 'civicrm-ext-uninstall'
621 */
622 function drush_civicrm_ext_uninstall($extension_name) {
623 civicrm_initialize();
624 try{
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)));
628 } else {
629 drush_log(t('Extension !ename could not be uninstalled.', array('!ename' => $extension_name)), 'error');
630 }
631 }
632 catch (CiviCRM_API3_Exception $e) {
633 // handle error here
634 $errorMessage = $e->getMessage();
635 $errorCode = $e->getErrorCode();
636 $errorData = $e->getExtraParams();
637 drush_log(dt("!error", array('!error' => $errorData), 'error'));
638 }
639 }
640
641 /**
642 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-upgrade-db'
643 */
644 function drush_civicrm_upgrade_db_validate() {
645 if (!defined('CIVICRM_UPGRADE_ACTIVE')) {
646 define('CIVICRM_UPGRADE_ACTIVE', 1);
647 }
648 $_GET['q'] = 'civicrm/upgrade';
649
650 if (!_civicrm_init()) {
651 return FALSE;
652 }
653
654 $_POST['upgrade'] = 1;
655 $_GET['q'] = 'civicrm/upgrade';
656 require_once 'CRM/Core/Config.php';
657
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();
662 if (!$dbVer) {
663 return drush_set_error('CIVICRM_VERSION_MISSING_DATABASE', dt('Version information missing in civicrm database.'));
664 }
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.'));
667 }
668 elseif (!$codeVer) {
669 return drush_set_error('CIVICRM_VERSION_MISSING_CODE', dt('Version information missing in civicrm codebase.'));
670 }
671 elseif (version_compare($codeVer, $dbVer) > 0) {
672 drush_log(dt("Starting with v!dbVer -> v!codeVer upgrade ..", array('!dbVer' => $dbVer, '!codeVer' => $codeVer)));
673 }
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)));
676 }
677
678 return TRUE;
679 }
680
681 /**
682 * Implementation of command 'civicrm-upgrade-db'
683 */
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)));
691 return TRUE;
692 }
693 $upgradeHeadless = new CRM_Upgrade_Headless();
694 // FIXME Exception handling?
695 $result = $upgradeHeadless->run();
696 drush_print("Upgrade outputs:\n" . $result['text']);
697 }
698 else {
699 require_once 'CRM/Core/Smarty.php';
700 $template = CRM_Core_Smarty::singleton();
701
702 require_once ('CRM/Upgrade/Page/Upgrade.php');
703 $upgrade = new CRM_Upgrade_Page_Upgrade();
704
705 // new since CiviCRM 4.1
706 if (is_callable(array(
707 $upgrade, 'setPrint'))) {
708 $upgrade->setPrint(TRUE);
709 }
710
711 // to suppress html output /w source code.
712 ob_start();
713 $upgrade->run();
714 // capture the required message.
715 $result = $template->get_template_vars('message');
716 ob_end_clean();
717 drush_print("Upgrade outputs: " . "\"$result\"");
718 }
719 }
720
721 /**
722 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-update-cfg'
723 */
724 function drush_civicrm_update_cfg_validate() {
725 return _civicrm_init();
726 }
727
728
729 /**
730 * Implementation of command 'civicrm-update-cfg'
731 */
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);
739 if ($value) {
740 $defaultValues[$name] = $value;
741 }
742 }
743 }
744
745 require_once 'CRM/Core/I18n.php';
746 require_once 'CRM/Core/BAO/ConfigSetting.php';
747 $result = CRM_Core_BAO_ConfigSetting::doSiteMove($defaultValues);
748
749 if ($result) {
750
751 drush_log(dt('Config successfully updated.'), 'completed');
752
753 }
754 else drush_log(dt('Config update failed.'), 'failed');
755 }
756
757 /**
758 * Implements hook_drush_cache_clear.
759 */
760 function civicrm_drush_cache_clear(&$types) {
761 if (_civicrm_init(FALSE)) {
762 $types['civicrm'] = 'drush_civicrm_cacheclear';
763 }
764 }
765
766 /**
767 * Cache clear callback
768 *
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.
772 */
773 function drush_civicrm_cacheclear() {
774 _civicrm_init();
775
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');
781
782 // Flush all caches using the API
783 $params = array('version' => 3);
784 if (drush_get_option('triggers', FALSE)) {
785 $params['triggers'] = 1;
786 }
787
788 if (drush_get_option('sessions', FALSE)) {
789 $params['session'] = 1;
790 }
791
792 // Need to set API version or drush cc civicrm fails
793 $params['version'] = 3;
794 $result = civicrm_api('System', 'flush', $params);
795
796 if ($result['is_error']) {
797 drush_log(dt('An error occurred: !message', array('!message' => $result['error_message'])), 'error');
798 return;
799 }
800
801 drush_log(dt('The CiviCRM cache has been cleared.'), 'ok');
802 }
803
804 /**
805 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-enable-debug'
806 */
807 function drush_civicrm_enable_debug_validate() {
808 return _civicrm_init();
809 }
810
811 function drush_civicrm_enable_debug() {
812 $settings = array(
813 'debug_enabled' => 1,
814 'backtrace' => 1,
815 );
816
817 foreach ($settings as $key => $val) {
818 $result = civicrm_api('Setting', 'create', array('version' => 3, $key => $val));
819
820 if ($result['is_error']) {
821 drush_log(dt('An error occurred: !message', array('!message' => $result['error_message'])), 'error');
822 return;
823 }
824 }
825
826 drush_log(dt('CiviCRM debug setting enabled.'), 'ok');
827 }
828
829 /**
830 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-disable-debug'
831 */
832 function drush_civicrm_disable_debug_validate() {
833 return _civicrm_init();
834 }
835
836 function drush_civicrm_disable_debug() {
837 $settings = array(
838 'debug_enabled' => 0,
839 'backtrace' => 0,
840 );
841
842 foreach ($settings as $key => $val) {
843 $result = civicrm_api('Setting', 'create', array('version' => 3, $key => $val));
844
845 if ($result['is_error']) {
846 drush_log(dt('An error occurred: !message', array('!message' => $result['error_message'])), 'error');
847 return;
848 }
849 }
850
851 drush_log(dt('CiviCRM debug setting disabled.'), 'ok');
852 }
853
854 /**
855 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-upgrade'
856 */
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);
861 if (!$tarfile) {
862 return drush_set_error('CIVICRM_TAR_NOT_SPECIFIED', dt('Tarfile not specified.'));
863 }
864 //FIXME: throw error if tarfile is not in a valid format.
865
866 if (!defined('CIVICRM_UPGRADE_ACTIVE')) {
867 define('CIVICRM_UPGRADE_ACTIVE', 1);
868 }
869 return _civicrm_init();
870 }
871
872 /**
873 * Implementation of command 'civicrm-upgrade'
874 */
875 function drush_civicrm_upgrade() {
876 global $civicrm_root;
877
878 $tarfile = drush_get_option('tarfile', FALSE);
879 $date = date('YmdHis');
880 $backup_file = "civicrm";
881
882 $basepath = explode('/', $civicrm_root);
883 array_pop($basepath);
884 $project_path = implode('/', $basepath) . '/';
885
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, '/');
889
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")
893 ));
894 drush_print(dt("2. Backing up database as => !path",
895 array('!path' => "$backup_dir/modules/$date/$backup_file.sql")
896 ));
897 drush_print(dt("3. Unpacking tarfile to => !path",
898 array('!path' => "$project_path")
899 ));
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();
903 }
904
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)
914 ));
915 }
916 drush_log(dt("\n1. Code backed up."), 'ok');
917
918 drush_set_option('result-file', $backup_target . '.sql');
919 drush_civicrm_sqldump();
920 drush_log(dt('2. Database backed up.'), 'ok');
921
922 // Decompress & Untar
923 _civicrm_extract_tarfile($project_path);
924 drush_log(dt('3. Tarfile unpacked.'), 'ok');
925
926 drush_log(dt("4. "));
927
928 if (drush_civicrm_upgrade_db_validate()) {
929 drush_civicrm_upgrade_db();
930 }
931 drush_log(dt("\nProcess completed."), 'completed');
932 }
933
934 /**
935 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-restore'
936 */
937 function drush_civicrm_restore_validate() {
938 _civicrm_dsn_init();
939
940 $restore_dir = drush_get_option('restore-dir', FALSE);
941 $restore_dir = rtrim($restore_dir, '/');
942 if (!$restore_dir) {
943 return drush_set_error('CIVICRM_RESTORE_NOT_SPECIFIED', dt('Restore-dir not specified.'));
944 }
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.'));
948 }
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.'));
952 }
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.'));
955 }
956
957 return TRUE;
958 }
959
960 /**
961 * Implementation of command 'civicrm-restore'
962 */
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');
969
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) . '/';
974
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, '/');
978
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."));
985 drush_print();
986 drush_print(dt("Note: Before restoring a backup will be taken in '!path' directory.",
987 array('!path' => "$restore_backup_dir/modules/restore")
988 ));
989 drush_print();
990 if (!drush_confirm(dt('Do you really want to continue?'))) {
991 return drush_user_abort();
992 }
993
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);
1002
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)
1008 ));
1009 }
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)
1013 ));
1014 }
1015 drush_log(dt('Codebase restored.'), 'ok');
1016
1017 // 2. backup, drop and create database
1018 drush_set_option('result-file', $restore_backup_dir . '/civicrm.sql');
1019 drush_civicrm_sqldump();
1020
1021 drush_log(dt('Database backed up.'), 'ok');
1022
1023 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1024 $sql = drush_sql_get_class();
1025 $exec = 'mysql ' . $sql->creds() . ' -e ';
1026 $dbDriver = $db_spec['driver'];
1027 }
1028 else {
1029 $exec = 'mysql' . _drush_sql_get_credentials() . ' -e ';
1030 $dbDriver = _drush_sql_get_scheme();
1031 }
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'])));
1035 }
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'])));
1040 }
1041 drush_log(dt('Database created.'), 'ok');
1042
1043 // 3. restore database
1044 switch ($dbDriver) {
1045 case 'mysql':
1046 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1047 $send = 'mysql ' . $sql->creds();
1048 }
1049 else {
1050 $send = 'mysql' . _drush_sql_get_credentials();
1051 }
1052 break;
1053
1054 case 'pgsql':
1055 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1056 $send .= 'psql -d ' . $sql->creds() . ' --file -';
1057 }
1058 else {
1059 $send .= 'psql -d ' . _drush_sql_get_credentials() . ' --file -';
1060 }
1061 break;
1062 }
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');
1067
1068 drush_log(dt('Restore process completed.'), 'completed');
1069
1070 _civicrm_dsn_close();
1071 }
1072
1073 /**
1074 * ?? for command 'civicrm-civimail'
1075 */
1076 function drush_civicrm_civimail_cron() {
1077 civicrm_api('Mailing', 'Process', array('version' => 3));
1078 }
1079
1080 /**
1081 * Implementation of command 'civicrm-member-records'
1082 */
1083 function drush_civicrm_member_records() {
1084 _civicrm_init();
1085
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);
1089
1090 global $argv;
1091 $argv = array(
1092 0 => "drush",
1093 1 => "-u" . $_REQUEST['name'],
1094 2 => "-p" . $_REQUEST['pass'],
1095 3 => "-s" . drush_get_option('uri', FALSE),
1096 );
1097
1098 if (!defined('CIVICRM_CONFDIR')) {
1099 define('CIVICRM_CONFDIR', drush_get_context('DRUSH_DRUPAL_ROOT') . '/sites/');
1100 }
1101
1102 include "bin/UpdateMembershipRecord.php";
1103 }
1104
1105 /**
1106 * Implementation of drush_hook_COMMAND_validate for command 'civicrm-rest' ('cvr')
1107 */
1108 function drush_civicrm_rest_validate() {
1109 $query = drush_get_option('query', FALSE);
1110 if (!$query) {
1111 drush_set_error('CIVICRM_REST_EMPTY_QUERY', dt('query not specified.'));
1112 }
1113
1114 return _civicrm_init();
1115 }
1116
1117 /**
1118 * Implementation of command 'civicrm-rest' ('cvr')
1119 */
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;
1127 $_GET[$key] = $val;
1128 }
1129
1130 require_once 'CRM/Utils/REST.php';
1131 $rest = new CRM_Utils_REST();
1132
1133 require_once 'CRM/Core/Config.php';
1134 $config = CRM_Core_Config::singleton();
1135
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";
1139
1140 if (isset($_GET['json']) &&
1141 $_GET['json']
1142 ) {
1143 header('Content-Type: text/javascript');
1144 }
1145 else {
1146 header('Content-Type: text/xml');
1147 }
1148 echo $rest->run($config);
1149 }
1150
1151 /**
1152 * Implements drush_hook_pre_COMMAND().
1153 *
1154 * this function is called when using drush 6.
1155 */
1156 function drush_civicrm_pre_civicrm_sql_dump() {
1157 _civicrm_dsn_init();
1158 }
1159
1160 /**
1161 * Implements drush_hook_pre_COMMAND().
1162 *
1163 * this function is called when using drush 5.
1164 */
1165 function drush_civicrm_pre_civicrm_sqldump() {
1166 _civicrm_dsn_init();
1167 }
1168
1169 /**
1170 * Implementation of command 'civicrm-sql-dump'
1171 */
1172 function drush_civicrm_sqldump() {
1173 if (version_compare(DRUSH_VERSION, 7, '>=')) {
1174 drush_sql_dump();
1175 }
1176 else {
1177 drush_sql_dump_execute();
1178 }
1179 }
1180
1181 /**
1182 * Implements drush_hook_post_COMMAND().
1183 *
1184 * this function is called when using drush 6.
1185 */
1186 function drush_civicrm_post_civicrm_sql_dump() {
1187 _civicrm_dsn_close();
1188 }
1189
1190 /**
1191 * Implements drush_hook_post_COMMAND().
1192 *
1193 * this function is called when using drush 5.
1194 */
1195 function drush_civicrm_post_civicrm_sqldump() {
1196 _civicrm_dsn_close();
1197 }
1198
1199 /**
1200 * Implements drush_hook_pre_COMMAND().
1201 *
1202 * this function is called when using drush 6.
1203 */
1204 function drush_civicrm_pre_civicrm_sql_conf() {
1205 _civicrm_dsn_init();
1206 }
1207
1208 /**
1209 * Implements drush_hook_post_COMMAND().
1210 *
1211 * this function is called when using drush 5.
1212 */
1213 function drush_civicrm_pre_civicrm_sqlconf() {
1214 _civicrm_dsn_init();
1215 }
1216
1217 /**
1218 * Implementation of command 'civicrm-sql-conf'
1219 */
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
1223 // be called again.
1224 if (version_compare(DRUSH_VERSION, 6, '>=')) {
1225 drush_print_r($conf);
1226 }
1227 }
1228
1229 /**
1230 * Implements drush_hook_post_COMMAND().
1231 *
1232 * this function is called when using drush 6.
1233 */
1234 function drush_civicrm_post_civicrm_sql_conf() {
1235 _civicrm_dsn_close();
1236 }
1237
1238 /**
1239 * Implements drush_hook_post_COMMAND().
1240 *
1241 * this function is called when using drush 5.
1242 */
1243 function drush_civicrm_post_civicrm_sqlconf() {
1244 _civicrm_dsn_close();
1245 }
1246
1247 /**
1248 * Implements drush_hook_pre_COMMAND().
1249 *
1250 * this function is called when using drush 6.
1251 */
1252 function drush_civicrm_pre_civicrm_sql_connect() {
1253 _civicrm_dsn_init();
1254 }
1255
1256 /**
1257 * Implements drush_hook_pre_COMMAND().
1258 *
1259 * this function is called when using drush 5.
1260 */
1261 function drush_civicrm_pre_civicrm_sqlconnect() {
1262 _civicrm_dsn_init();
1263 }
1264
1265 /**
1266 * Implementation of command 'civicrm-sql-connect'
1267 */
1268 function drush_civicrm_sqlconnect() {
1269 return drush_sql_connect();
1270 }
1271
1272 /**
1273 * Implements drush_hook_post_COMMAND().
1274 *
1275 * this function is called when using drush 6.
1276 */
1277 function drush_civicrm_post_civicrm_sql_connect() {
1278 _civicrm_dsn_close();
1279 }
1280
1281 /**
1282 * Implements drush_hook_post_COMMAND().
1283 *
1284 * this function is called when using drush 5.
1285 */
1286 function drush_civicrm_post_civicrm_sqlconnect() {
1287 _civicrm_dsn_close();
1288 }
1289
1290 /**
1291 * Implements drush_hook_pre_COMMAND().
1292 *
1293 * this function is called when using drush 6.
1294 */
1295 function drush_civicrm_pre_civicrm_sql_query() {
1296 _civicrm_dsn_init();
1297 }
1298
1299 /**
1300 * Implements drush_hook_pre_COMMAND().
1301 *
1302 * this function is called when using drush 5.
1303 */
1304 function drush_civicrm_pre_civicrm_sqlquery() {
1305 _civicrm_dsn_init();
1306 }
1307
1308 /**
1309 * Implementation of command 'civicrm-sql-query'
1310 */
1311 function drush_civicrm_sqlquery($query) {
1312 return drush_sql_query($query);
1313 }
1314
1315 /**
1316 * Implements drush_hook_post_COMMAND().
1317 *
1318 * this function is called when using drush 6.
1319 */
1320 function drush_civicrm_post_civicrm_sql_query() {
1321 _civicrm_dsn_close();
1322 }
1323
1324 /**
1325 * Implements drush_hook_post_COMMAND().
1326 *
1327 * this function is called when using drush 5.
1328 */
1329 function drush_civicrm_post_civicrm_sqlquery() {
1330 _civicrm_dsn_close();
1331 }
1332
1333 /**
1334 * Implements drush_hook_pre_COMMAND().
1335 *
1336 * this function is called when using drush 6.
1337 */
1338 function drush_civicrm_pre_civicrm_sql_cli() {
1339 _civicrm_dsn_init();
1340 }
1341
1342 /**
1343 * Implements drush_hook_pre_COMMAND().
1344 *
1345 * this function is called when using drush 5.
1346 */
1347 function drush_civicrm_pre_civicrm_sqlcli() {
1348 _civicrm_dsn_init();
1349 }
1350
1351 /**
1352 * Implementation of command 'civicrm-sql-cli'
1353 */
1354 function drush_civicrm_sqlcli() {
1355 drush_sql_cli();
1356 }
1357
1358 /**
1359 * Implements drush_hook_post_COMMAND().
1360 *
1361 * this function is called when using drush 6.
1362 */
1363 function drush_civicrm_post_civicrm_sql_cli() {
1364 _civicrm_dsn_close();
1365 }
1366
1367 /**
1368 * Implements drush_hook_post_COMMAND().
1369 *
1370 * this function is called when using drush 5.
1371 */
1372 function drush_civicrm_post_civicrm_sqlcli() {
1373 _civicrm_dsn_close();
1374 }
1375
1376 function _civicrm_dsn_init($reset = FALSE) {
1377 static $globalDbUrl = NULL;
1378
1379 if (!_civicrm_init()) {
1380 return FALSE;
1381 }
1382
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];
1392 }
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);
1395 }
1396 }
1397 else {
1398 if (!$globalDbUrl && CIVICRM_DSN) {
1399 // keep a copy so that we can put it back.
1400 $globalDbUrl = $GLOBALS['db_url'];
1401 }
1402 // now modify $GLOBALS so that drush works on CIVICRM_DSN instead of drupal's
1403 $GLOBALS['db_url'] = CIVICRM_DSN;
1404 }
1405 $dbUrl = $globalDbUrl;
1406 $globalDbUrl = $reset ? NULL : $globalDbUrl;
1407
1408 return $dbUrl;
1409 }
1410
1411 function _civicrm_dsn_close() {
1412 $globalDbUrl = _civicrm_dsn_init(TRUE);
1413 if ($globalDbUrl) {
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;
1418 }
1419 else {
1420 $GLOBALS['db_url'] = $globalDbUrl;
1421 }
1422 }
1423 }
1424
1425 /**
1426 * Initializes the CiviCRM environment and configuration.
1427 * TODO: document why we can't call civicrm_initialize() directly.
1428 *
1429 * @param bool fail
1430 * If true, will halt drush. Otherwise, return false but do not interrupt.
1431 *
1432 * @return bool
1433 * Returns TRUE if CiviCRM was initialized.
1434 */
1435 function _civicrm_init($fail = TRUE) {
1436 static $init = NULL;
1437
1438 // return if already initialized
1439 if ($init) {
1440 return $init;
1441 }
1442
1443 global $cmsPath;
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";
1447
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)) {
1452 if ($fail) {
1453 return drush_set_error('CIVICRM_INIT_SETTINGS_NOT_FOUND', dt('Could not locate civicrm settings file.'));
1454 }
1455 else {
1456 return FALSE;
1457 }
1458 }
1459 }
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.'));
1466 }
1467
1468 // Autoload was added in 4.2
1469 require_once 'CRM/Utils/System.php';
1470 $codeVer = CRM_Utils_System::version();
1471
1472 if (substr($codeVer, 0, 3) >= '4.2') {
1473 require_once $civicrm_root . '/CRM/Core/ClassLoader.php';
1474 CRM_Core_ClassLoader::singleton()->register();
1475 }
1476
1477 // also initialize config object
1478 require_once 'CRM/Core/Config.php';
1479 $config = CRM_Core_Config::singleton();
1480
1481 $init = TRUE;
1482 return $init;
1483 }
1484
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";
1490 }
1491 }
1492 return $crmpath;
1493 }
1494
1495 /**
1496 * (Drush callback)
1497 *
1498 * Implementation of command 'civicrm-api'
1499 */
1500 function drush_civicrm_api() {
1501 $DEFAULTS = array('version' => 3);
1502
1503 $args = func_get_args();
1504 list($entity, $action) = explode('.', $args[0]);
1505 array_shift($args);
1506
1507 // Parse $params
1508 switch (drush_get_option('in', 'args')) {
1509 case 'args':
1510 $params = $DEFAULTS;
1511 foreach ($args as $arg) {
1512 preg_match('/^([^=]+)=(.*)$/', $arg, $matches);
1513 $params[$matches[1]] = $matches[2];
1514 }
1515 break;
1516
1517 case 'json':
1518 $json = stream_get_contents(STDIN);
1519 if (empty($json)) {
1520 $params = $DEFAULTS;
1521 }
1522 else {
1523 $params = array_merge($DEFAULTS, json_decode($json, TRUE));
1524 }
1525 break;
1526
1527 default:
1528 drush_set_error(dt('Unknown format: @format', array('@format' => $format)));
1529 break;
1530 }
1531
1532 civicrm_initialize();
1533
1534 global $user;
1535 CRM_Core_BAO_UFMatch::synchronize($user, FALSE, 'Drupal',
1536 civicrm_get_ctype('Individual')
1537 );
1538
1539 $result = civicrm_api($entity, $action, $params);
1540
1541 switch (drush_get_option('out', 'pretty')) {
1542 case 'pretty':
1543 drush_print_r($result);
1544 break;
1545
1546 case 'json':
1547 drush_print(json_encode($result));
1548 break;
1549
1550 default:
1551 return drush_set_error('CIVICRM_UNKNOWN_FORMAT', dt('Unknown format: @format', array('@format' => $format)));
1552 }
1553 }
1554