-
-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathcivicrm.drush.inc
More file actions
1726 lines (1538 loc) · 52.9 KB
/
civicrm.drush.inc
File metadata and controls
1726 lines (1538 loc) · 52.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
/**
* @file
* Example drush command.
*
* Shows how to make your own drush command.
*
* You can copy this file to any of the following
* 1. A .drush folder in your HOME folder.
* 2. Anywhere in a folder tree below an active module on your site.
* 3. In an arbitrary folder specified with the --include option.
*/
use Civi\Core\Exception\DBQueryException;
/**
* Implements hook_drush_command().
*
* In this hook, you specify which commands your
* drush module makes available, what it does and
* description.
*
* Notice how this structure closely resembles how
* you define menu hooks.
*
* @See drush_parse_command() for a list of recognized keys.
*
*/
function civicrm_drush_command() {
$items = [];
// the key in the $items array is the name of the command.
$items['civicrm-api'] = [
'description' => 'CLI access to CiviCRM APIs. It can return pretty-printor json formatted data.',
'examples' => [
'drush civicrm-api contact.create first_name=John last_name=Doe contact_type=Individual' => 'Create a new contact named John Doe',
'drush civicrm-api contact.create id=1 --out=json' => 'Find/display a contact in JSON format',
],
'options' => [
'in' => 'Input type: "args" (command-line), "json" (STDIN)',
'out' => 'Output type: "pretty" (STDOUT), "json" (STDOUT)',
],
'aliases' => ['cvapi'],
];
$items['civicrm-install'] = [
'description' => 'Install a new instance of CiviCRM.',
'options' => [
'dbuser' => 'MySQL username for your Drupal/CiviCRM database.',
'dbpass' => 'MySQL password for your Drupal/CiviCRM database.',
'dbhost' => 'MySQL host for your Drupal/CiviCRM database. Defaults to localhost.',
'dbname' => 'MySQL database name of your Drupal/CiviCRM database.',
'tarfile' => 'Path to your CiviCRM tar.gz file.',
'destination' => 'Destination modules path to extract CiviCRM (eg : sites/all/modules ).',
'lang' => 'Default language to use for installation.',
'langtarfile' => 'Path to your l10n tar.gz file.',
'site_url' => 'Base Url for your drupal/CiviCRM website without http (e.g. mysite.com)',
'ssl' => 'Using ssl for your drupal/CiviCRM website if set to on (e.g. --ssl=on)',
],
'aliases' => ['cvi'],
];
$items['civicrm-ext-list'] = [
'description' => "List of CiviCRM extensions enabled.",
'options' => [
'status' => 'Filter by extension status (installed, uninstalled, disabled).',
'out' => 'Output type: "pretty" (STDOUT) by default, "json" (STDOUT)',
],
'examples' => [
'Standard example' => 'drush civicrm-ext-list',
'Display installed extensions' => 'drush civicrm-ext-list --status=installed',
'Display disabled extensions as json' => 'drush civicrm-ext-list --status=disabled --out=json',
],
'aliases' => ['cel'],
];
$items['civicrm-ext-install'] = [
'description' => 'Install a CiviCRM extension.',
'arguments' => [
'ename' => 'Extension name.',
],
'required-arguments' => TRUE,
'examples' => [
'Standard example' => 'drush civicrm-ext-install civimobile',
],
'aliases' => ['cei'],
];
$items['civicrm-ext-disable'] = [
'description' => 'Disable a CiviCRM extension.',
'arguments' => [
'ename' => 'Extension name.',
],
'required-arguments' => TRUE,
'examples' => [
'Standard example' => 'drush civicrm-ext-disable civimobile',
],
'aliases' => ['ced'],
];
$items['civicrm-ext-uninstall'] = [
'description' => 'Uninstall a CiviCRM extension.',
'arguments' => [
'ename' => 'Extension name.',
],
'required-arguments' => TRUE,
'examples' => [
'Standard example' => 'drush civicrm-ext-uninstall civimobile',
],
'aliases' => ['ceui'],
];
$items['civicrm-upgrade-db'] = [
'description' => 'Execute the civicrm/upgrade?reset=1 process from the command line.',
'aliases' => ['cvupdb'],
];
$items['civicrm-update-cfg'] = [
'description' => 'Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.',
'examples' => [
'drush -l http://example.com/civicrm civicrm-update-cfg' => 'Update config_backend to correct config settings for civicrm installation on example.com site.',
],
'aliases' => ['cvupcfg'],
];
$items['civicrm-enable-debug'] = [
'description' => "Enable CiviCRM Debugging.",
];
$items['civicrm-disable-debug'] = [
'description' => "Disable CiviCRM Debugging.",
];
$items['civicrm-pipe'] = [
'description' => 'Start a Civi::pipe session (JSON-RPC 2.0)',
'examples' => [
'drush civicrm-pipe' => 'Begin a session with default flags',
'drush civicrm-pipe vt' => 'Begin a session with connection flags (ex: version, trusted)',
'drush civicrm-pipe vu' => 'Begin a session with connection flags (ex: version, untrusted)',
],
'arguments' => [
'connection-flags' => 'List of connection flags (https://docs.civicrm.org/dev/en/latest/framework/pipe#flags)',
],
'aliases' => ['cvpipe'],
];
$items['civicrm-upgrade'] = [
'description' => 'Replace CiviCRM codebase with new specified tarfile and upgrade database by executing the CiviCRM upgrade process - civicrm/upgrade?reset=1.',
'examples' => [
'drush civicrm-upgrade --tarfile=~/tarballs/civicrm-4.1.2-drupal.tar.gz' => 'Replace old CiviCRM codebase with new v4.1.2 and run upgrade process.',
],
'options' => [
'tarfile' => 'Path of new CiviCRM tarfile, with which current CiviCRM codebase is to be replaced.',
'backup-dir' => 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.',
],
'aliases' => ['cvup'],
];
$items['civicrm-restore'] = [
'description' => 'Restore CiviCRM codebase and database back from the specified backup directory.',
'examples' => [
'drush civicrm-restore --restore-dir=../backup/modules/20100309200249' => 'Replace current civicrm codebase with the $restore-dir/civicrm codebase, and reload the database with $restore-dir/civicrm.sql file',
],
'options' => [
'restore-dir' => 'Path of directory having backed up CiviCRM codebase and database.',
'backup-dir' => 'Specify a directory to backup current CiviCRM codebase and database into, defaults to a backup directory above your Drupal root.',
],
];
$items['civicrm-rest'] = [
'description' => 'Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.',
'examples' => [
"drush civicrm-rest --query='civicrm/contact/search&json=1&key=7decb879f28ac4a0c6a92f0f7889a0c9&api_key=7decb879f28ac4a0c6a92f0f7889a0c9'" => 'Use contact search api to return data in json format.',
],
// TODO: This really makes more sense as an argument.
'options' => ['query' => 'Query part of url. Refer CiviCRM wiki doc for more details.'],
'aliases' => ['cvr'],
];
$items['civicrm-sql-conf'] = [
// explicit callback declaration and non-standard name to avoid collision with "sql-conf"
'callback' => 'drush_civicrm_sqlconf',
'description' => 'Print CiviCRM database connection details.',
'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION,
];
$items['civicrm-sql-connect'] = [
// explicit callback declaration and non-standard name to avoid collision with "sql-connect"
'callback' => 'drush_civicrm_sqlconnect',
'description' => 'A string for connecting to the CiviCRM DB.',
];
$items['civicrm-sql-dump'] = [
// explicit callback declaration and non-standard name to avoid collision with "sql-dump"
'callback' => 'drush_civicrm_sqldump',
'description' => 'Exports the CiviCRM DB as SQL using mysqldump.',
'examples' => [
'drush civicrm-sql-dump --result-file=../CiviCRM.sql' => 'Save SQL dump to the directory above Drupal root.',
'drush civicrm-sql-dump --extra-options=--quick' => 'Pass the --quick option to mysqldump to help with large tables.',
],
'options' => [
'data-only' => 'Dump data without statements to create any of the schema.',
'gzip' => 'Compress the dump using the gzip program which must be in your $PATH.',
'result-file' => 'Save to a file.',
'tables-list' => 'comma-separated list of tables to transfer.',
'extra-options' => 'Add custom options to the dump command.',
],
];
$items['civicrm-sql-query'] = [
// explicit callback declaration and non-standard name to avoid collision with "sql-query"
'callback' => 'drush_civicrm_sqlquery',
'description' => 'Execute a query against the CiviCRM database.',
'examples' => [
'drush civicrm-sql-query "SELECT * FROM civicrm_contact WHERE id=1"' => 'Browse user record',
'drush civicrm-sql-query --file=example.sql' => 'Alternate way to import sql statements from a file.',
],
'arguments' => [
'query' => 'A SQL query. Ignored if \'file\' is provided.',
],
'options' => [
'file' => 'Path to a file containing the SQL to be run. ',
],
];
$items['civicrm-sql-cli'] = [
// explicit callback declaration and non-standard name to avoid collision with "sql-cli"
'callback' => 'drush_civicrm_sqlcli',
'description' => "Open a SQL command-line interface using CiviCRM's credentials.",
'aliases' => ['cvsqlc'],
'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION,
];
$items['civicrm-sql-rebuild-triggers'] = [
'description' => 'Rebuild SQL triggers',
'aliases' => ['cvsqlrt'],
'options' => [
'table' => 'Specific table to target. If omitted, triggers for all tables are rebuilt.',
],
];
$items['civicrm-process-mail-queue'] = [
'description' => "Process pending CiviMail mailing jobs.",
'examples' => [
'drush civicrm-process-mail-queue -u admin' => 'Process CiviMail queue with admin credentials.',
],
];
$items['civicrm-member-records'] = [
'description' => "Run the CiviMember UpdateMembershipRecord cron (civicrm-member-records).",
];
$items['civicrm-sync-users-contacts'] = [
'description' => "Synchronize Users to Contacts: CiviCRM will check each user record for a contact record. A new contact record will be created for each user where one does not already exist.",
];
return $items;
}
/**
* Implementation of database specification for the active DB connection
*/
function drush_civicrm_get_db_spec() {
if (version_compare(DRUSH_VERSION, 7, '>=')) {
$sql = drush_sql_get_class();
$db_spec = $sql->db_spec();
}
else {
$db_spec = _drush_sql_get_db_spec();
}
return $db_spec;
}
/**
* Implements hook_COMMAND_validate() for civicrm-install().
*/
function drush_civicrm_install_validate() {
// TODO: Replace these with required options (Drush 5).
// Get the drupal credentials in case civi specific db info is not passed.
if (drush_get_option('db-url', FALSE)) {
$db_spec['db-url'] = $GLOBALS['db_url'];
}
elseif (drush_get_option('all', FALSE)) {
$db_spec = _drush_sql_get_all_db_specs();
}
if (!isset($db_spec)) {
$db_spec = drush_civicrm_get_db_spec();
}
if (!drush_get_option('dbuser', FALSE)) {
drush_set_option('dbuser', $db_spec['username']);
}
if (!drush_get_option('dbpass', FALSE)) {
drush_set_option('dbpass', $db_spec['password']);
}
if (!drush_get_option('dbhost', FALSE)) {
drush_set_option('dbhost', $db_spec['host']);
}
if (!drush_get_option('dbname', FALSE)) {
drush_set_option('dbname', $db_spec['database']);
}
$crmpath = _civicrm_get_crmpath();
$drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
$modPath = "$drupalRoot/$crmpath";
if (!is_dir("$modPath/civicrm") && !drush_get_option('tarfile', FALSE)) {
return drush_set_error('CIVICRM_INSTALL_TARFILE_NOT_SPECIFIED', dt('CiviCRM tarfile not specified.'));
}
if (drush_get_option('lang', FALSE) && !drush_get_option('langtarfile', FALSE)) {
return drush_set_error('CIVICRM_INSTALL_LANGTARFILE_NOT_SPECIFIED', dt('CiviCRM language tarfile not specified.'));
}
return TRUE;
}
/**
* Implementation of command 'civicrm-install'
*/
function drush_civicrm_install() {
$dbuser = drush_get_option('dbuser', FALSE);
$dbpass = drush_get_option('dbpass', FALSE);
$dbhost = drush_get_option('dbhost', FALSE);
$dbname = drush_get_option('dbname', FALSE);
$crmpath = _civicrm_get_crmpath();
$drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
$modPath = "$drupalRoot/$crmpath";
$lang = drush_get_option('lang', '');
if (!is_dir("$modPath/civicrm")) {
// extract tarfile at right place
_civicrm_extract_tarfile($modPath);
drush_log(dt('Tarfile unpacked.'), 'ok');
}
// include civicrm installer helper file
$civicrmInstallerHelper = "$modPath/civicrm/install/civicrm.php";
if (!file_exists($civicrmInstallerHelper)) {
return drush_set_error('CIVICRM_NOT_PRESENT', dt('CiviCRM installer helper file is missing.'));
}
if ($lang != '') {
_civicrm_extract_tarfile($modPath, "langtarfile");
}
// setup all required files/civicrm/* directories
if (!_civicrm_create_files_dirs($civicrmInstallerHelper, $modPath)) {
return FALSE;
}
// install database
_civicrm_install_db($dbuser, $dbpass, $dbhost, $dbname, $modPath, $lang);
// generate civicrm.settings.php file
_civicrm_generate_settings_file($dbuser, $dbpass, $dbhost, $dbname, $modPath);
module_enable(['civicrm']);
drush_log(dt("CiviCRM installed."), 'ok');
}
function _civicrm_extract_tarfile($destinationPath, $option = 'tarfile') {
$tarpath = drush_get_option($option, FALSE);
if (drush_shell_exec("gzip -d " . $tarpath)) {
$tarpath = preg_replace('/(tar\.gz|tgz)$/', 'tar', $tarpath);
}
drush_shell_exec("tar -xf $tarpath -C \"$destinationPath\"");
}
function _civicrm_install_db($dbuser, $dbpass, $dbhost, $dbname,
$modPath, $lang
) {
$drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
$siteRoot = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
$sqlPath = "$modPath/civicrm/sql";
if (function_exists('mysqli_connect')) {
$dbhostParts = explode(':', $dbhost);
$conn = @mysqli_connect($dbhostParts[0], $dbuser, $dbpass, '', isset($dbhostParts[1]) ? $dbhostParts[1] : NULL);
$dbOK = ($a = @mysqli_select_db($conn, $dbname)) || ($b = @mysqli_query($conn, "CREATE DATABASE $dbname"));
}
elseif (function_exists('mysql_connect')) {
$conn = @mysql_connect($dbhost, $dbuser, $dbpass);
$dbOK = @mysql_select_db($dbname, $conn) || @mysql_query("CREATE DATABASE $dbname", $conn);
}
else {
$dbOK = FALSE;
}
if (!$dbOK) {
drush_die(dt('CiviCRM database was not found. Failed to create one.'));
}
// setup database with civicrm structure and data
$dsn = "mysql://{$dbuser}:{$dbpass}@{$dbhost}/{$dbname}?new_link=true";
drush_log(dt('Loading CiviCRM database structure ..'));
civicrm_source($dsn, $sqlPath . '/civicrm.mysql');
drush_log(dt('Loading CiviCRM database with required data ..'));
// testing the translated sql files availability
$data_file = $sqlPath . '/civicrm_data.mysql';
$acl_file = $sqlPath . '/civicrm_acl.mysql';
if ($lang != '') {
if (file_exists($sqlPath . '/civicrm_data.' . $lang . '.mysql')
and file_exists($sqlPath . '/civicrm_acl.' . $lang . '.mysql')
and $lang != ''
) {
$data_file = $sqlPath . '/civicrm_data.' . $lang . '.mysql';
$acl_file = $sqlPath . '/civicrm_acl.' . $lang . '.mysql';
}
else {
drush_log(dt('No sql files could be retrieved for "' . $lang .
"\", using default language."
), 'warning');
}
}
civicrm_source($dsn, $data_file);
civicrm_source($dsn, $acl_file);
drush_log(dt('CiviCRM database loaded successfully.'), 'ok');
}
function _civicrm_create_files_dirs($civicrmInstallerHelper, $modPath) {
$drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
$siteRoot = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
if (!file_exists($civicrmInstallerHelper)) {
return drush_set_error('CIVICRM_INSTALLER_HELP_MISSING', dt("CiviCRM installer helper file is missing."));
}
require_once "$civicrmInstallerHelper";
// create files/civicrm/* dirs
global $crmPath;
$crmPath = "$modPath/civicrm";
civicrm_setup("$drupalRoot/$siteRoot/files");
@drush_op('chmod', "$drupalRoot/$siteRoot/files/civicrm", 0777);
return TRUE;
}
/**
* Generates civicrm.settings.php file
*/
function _civicrm_generate_settings_file($dbuser, $dbpass, $dbhost, $dbname, $modPath) {
$drupalRoot = drush_get_context('DRUSH_DRUPAL_ROOT');
$siteRoot = drush_get_context('DRUSH_DRUPAL_SITE_ROOT', FALSE);
$crmPath = "$modPath/civicrm";
$files = [
"$crmPath/templates/CRM/common/civicrm.settings.php.template",
"$crmPath/templates/CRM/common/civicrm.settings.php.tpl",
];
$settingsTplFile = NULL;
foreach ($files as $file) {
if (file_exists($file)) {
$settingsTplFile = $file;
}
}
if (!$settingsTplFile) {
drush_die(dt('Could not find CiviCRM settings template and therefore could not create settings file.'));
}
drush_log(dt('Generating civicrm settings file ..'));
if ($baseUrl = drush_get_option('site_url', FALSE)) {
$ssl = drush_get_option('ssl', FALSE);
if ($ssl == 'on') {
$protocol = 'https';
}
else {
$protocol = 'http';
}
}
$baseUrl = !$baseUrl ? ($GLOBALS['base_url']) : ($protocol . '://' . $baseUrl);
$db_spec = drush_civicrm_get_db_spec();
// Check version: since 4.1, Drupal6 must be used for the UF in D6
// The file civicrm-version.php appeared around 4.0, so it is safe to assume
// that if it's not there, it's 3.x, in which case the CMS 'Drupal' is D6.
$cms = 'Drupal';
if (file_exists("$crmPath/civicrm-version.php")) {
require_once "$crmPath/civicrm-version.php";
$v = civicrmVersion();
$cms = $v['cms'];
}
$params = [
'crmRoot' => $crmPath,
'templateCompileDir' => "$drupalRoot/$siteRoot/files/civicrm/templates_c",
'frontEnd' => 0,
'cms' => $cms,
'baseURL' => $baseUrl,
'dbUser' => $dbuser,
'dbPass' => $dbpass,
'dbHost' => $dbhost,
'dbName' => $dbname,
'CMSdbUser' => $db_spec['username'],
'CMSdbPass' => $db_spec['password'],
'CMSdbHost' => $db_spec['host'],
'CMSdbName' => $db_spec['database'],
// These two are only filled in when using the newer civicrm-setup.
'dbSSL' => '',
'CMSdbSSL' => '',
'siteKey' => preg_replace(';[^a-zA-Z0-9];', '', base64_encode(random_bytes(37))),
'credKeys' => 'aes-cbc:hkdf-sha256:' . preg_replace(';[^a-zA-Z0-9];', '', base64_encode(random_bytes(37))),
'signKeys' => 'jwt-hs256:hkdf-sha256:' . preg_replace(';[^a-zA-Z0-9];', '', base64_encode(random_bytes(37))),
];
$str = file_get_contents($settingsTplFile);
foreach ($params as $key => $value) {
$str = str_replace('%%' . $key . '%%', $value, $str);
}
$str = trim($str);
$configFile = "$drupalRoot/$siteRoot/civicrm.settings.php";
civicrm_write_file($configFile, $str);
@drush_op('chmod', "$configFile", 0644);
drush_log(dt('Settings file generated: !file', ['!file' => $configFile]), 'ok');
}
/**
* Implements hook_drush_help().
*
* This function is called whenever a drush user calls
* 'drush help <name-of-your-command>'
*
*/
function civicrm_drush_help($section) {
switch ($section) {
case 'drush:civicrm-upgrade-db':
return dt('Run civicrm/upgrade?reset=1 just as a web browser would.');
case 'drush:civicrm-update-cfg':
return dt("Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.");
case 'drush:civicrm-upgrade':
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.');
case 'drush:civicrm-restore':
return dt("Restore CiviCRM codebase and database back from the specified backup directory.");
case 'drush:civicrm-rest':
return dt("Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.");
case 'drush:civicrm-sql-conf':
return dt('Show civicrm database connection details.');
case 'drush:civicrm-sql-connect':
return dt('A string which connects to the civicrm database.');
case 'drush:civicrm-sql-cli':
return dt('Quickly enter the mysql command line.');
case 'drush:civicrm-sql-dump':
return dt('Prints the whole CiviCRM database to STDOUT or save to a file.');
case 'drush:civicrm-sql-query':
return dt("Usage: drush [options] civicrm-sql-query <query>...\n<query> is a SQL statement. Any additional arguments are passed to the mysql command directly.");
}
}
/**
* Implementation of command 'civicrm-ext-list'
*/
function drush_civicrm_ext_list() {
if (!civicrm_initialize()) {
drush_print(dt("CiviCRM is not setup."));
return;
}
$status = drush_get_option('status', FALSE);
$params = [
'options' => [
'limit' => 0,
],
];
if ($status) {
if (!in_array($status, ['installed', 'uninstalled', 'disabled'])) {
return drush_set_error('CIVICRM_INVALID_STATUS', dt("Extension status {$status} is invalid."));
}
$params['status'] = $status;
}
try {
$result = civicrm_api3('extension', 'get', $params);
$rows = [[dt('App name'), dt('Status'), dt('Version')]];
foreach ($result['values'] as $k => $extension_data) {
$rows[] = [
$extension_data['key'],
$extension_data['status'],
$extension_data['version'],
];
}
unset($result);
$format = drush_get_option('out', 'pretty');
switch ($format) {
case 'pretty':
drush_print_table($rows, TRUE);
break;
case 'json':
drush_print(json_encode($rows));
break;
default:
return drush_set_error('CIVICRM_UNKNOWN_FORMAT', dt('Unknown format: @format', array('@format' => $format)));
}
}
catch (CiviCRM_API3_Exception $e) {
// handle error here
$errorMessage = $e->getMessage();
$errorCode = $e->getErrorCode();
$errorData = $e->getExtraParams();
drush_log(dt("!error", ['!error' => $errorData], 'error'));
}
}
/**
* Implementation of command 'civicrm-ext-install'
*/
function drush_civicrm_ext_install($extension_name) {
if (!civicrm_initialize()) {
drush_print(dt('CiviCRM is not setup.'));
return;
}
try {
$result = civicrm_api3('extension', 'install', ['key' => $extension_name]);
if ($result['values'] && $result['values'] == 1) {
drush_print(dt('Extension !ename installed.', ['!ename' => $extension_name]));
}
else {
drush_log(t('Extension !ename could not be installed.', ['!ename' => $extension_name]), 'error');
}
}
catch (CiviCRM_API3_Exception $e) {
// handle error here
$errorMessage = $e->getMessage();
$errorCode = $e->getErrorCode();
$errorData = $e->getExtraParams();
drush_log(dt('!error', ['!error' => $errorData], 'error'));
}
}
/**
* Implementation of command 'civicrm-ext-disable'
*/
function drush_civicrm_ext_disable($extension_name) {
if (!civicrm_initialize()) {
drush_print(dt("CiviCRM is not setup."));
return;
}
try {
$result = civicrm_api3('extension', 'disable', ['key' => $extension_name]);
if ($result['values'] && $result['values'] == 1) {
drush_print(dt("Extension !ename disabled.", ['!ename' => $extension_name]));
}
else {
drush_log(t('Extension !ename could not be disabled.', ['!ename' => $extension_name]), 'error');
}
}
catch (CiviCRM_API3_Exception $e) {
// handle error here
$errorMessage = $e->getMessage();
$errorCode = $e->getErrorCode();
$errorData = $e->getExtraParams();
drush_log(dt("!error", ['!error' => $errorData], 'error'));
}
}
/**
* Implementation of command 'civicrm-ext-uninstall'
*/
function drush_civicrm_ext_uninstall($extension_name) {
if (!civicrm_initialize()) {
drush_print(dt("CiviCRM is not setup."));
return;
}
try {
$result = civicrm_api3('extension', 'uninstall', ['key' => $extension_name]);
if ($result['values'] && $result['values'] == 1) {
drush_print(dt('Extension !ename uninstalled.', ['!ename' => $extension_name]));
}
else {
drush_log(t('Extension !ename could not be uninstalled.', ['!ename' => $extension_name]), 'error');
}
}
catch (CiviCRM_API3_Exception $e) {
// handle error here
$errorMessage = $e->getMessage();
$errorCode = $e->getErrorCode();
$errorData = $e->getExtraParams();
drush_log(dt("!error", ['!error' => $errorData], 'error'));
}
}
/**
* Implements drush_hook_COMMAND_validate() for civicrm-upgrade-db().
*/
function drush_civicrm_upgrade_db_validate() {
if (!defined('CIVICRM_UPGRADE_ACTIVE')) {
define('CIVICRM_UPGRADE_ACTIVE', 1);
}
$_GET['q'] = 'civicrm/upgrade';
if (!_civicrm_init()) {
return FALSE;
}
$_POST['upgrade'] = 1;
$_GET['q'] = 'civicrm/upgrade';
require_once 'CRM/Core/Config.php';
require_once 'CRM/Utils/System.php';
require_once 'CRM/Core/BAO/Domain.php';
$codeVer = CRM_Utils_System::version();
$dbVer = CRM_Core_BAO_Domain::version();
if (!$dbVer) {
return drush_set_error('CIVICRM_VERSION_MISSING_DATABASE', dt('Version information missing in civicrm database.'));
}
elseif (stripos($dbVer, 'upgrade')) {
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.'));
}
elseif (!$codeVer) {
return drush_set_error('CIVICRM_VERSION_MISSING_CODE', dt('Version information missing in civicrm codebase.'));
}
elseif (version_compare($codeVer, $dbVer) > 0) {
drush_log(dt("Starting with v!dbVer -> v!codeVer upgrade ..", ['!dbVer' => $dbVer, '!codeVer' => $codeVer]));
}
elseif (version_compare($codeVer, $dbVer) < 0) {
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'.", [
'!dbVer' => $dbVer,
'!codeVer' => $codeVer,
]));
}
return TRUE;
}
/**
* Implementation of command 'civicrm-upgrade-db'
*
* @throws \CRM_Core_Exception
*/
function drush_civicrm_upgrade_db() {
$codeVer = CRM_Utils_System::version();
$dbVer = CRM_Core_BAO_Domain::version();
if (version_compare($codeVer, $dbVer) == 0) {
drush_print(dt('You are already upgraded to CiviCRM @version', ['@version' => $codeVer]));
return TRUE;
}
$upgradeHeadless = new CRM_Upgrade_Headless();
// FIXME Exception handling?
$result = $upgradeHeadless->run();
drush_print("Upgrade outputs:\n" . $result['text']);
}
/**
* Implements drush_hook_COMMAND_validate() for civicrm-update-cfg().
*/
function drush_civicrm_update_cfg_validate() {
return _civicrm_init();
}
/**
* Implementation of command 'civicrm-update-cfg'
*/
function drush_civicrm_update_cfg() {
$defaultValues = [];
$states = ['old', 'new'];
for ($i = 1; $i <= 3; $i++) {
foreach ($states as $state) {
$name = "{$state}Val_{$i}";
$value = drush_get_option($name, NULL);
if ($value) {
$defaultValues[$name] = $value;
}
}
}
require_once 'CRM/Core/I18n.php';
require_once 'CRM/Core/BAO/ConfigSetting.php';
$result = CRM_Core_BAO_ConfigSetting::doSiteMove($defaultValues);
if ($result) {
drush_log(dt('Config successfully updated.'), 'completed');
}
else {
drush_log(dt('Config update failed.'), 'failed');
}
}
/**
* Implements hook_drush_cache_clear().
*/
function civicrm_drush_cache_clear(&$types) {
if (_civicrm_init(FALSE)) {
$types['civicrm'] = 'drush_civicrm_cacheclear';
}
}
/**
* Cache clear callback
*
* Warning: do not name drush_civicrm_cache_clear() otherwise it will
* conflict with hook_drush_cache_clear() and be called systematically
* when "drush cc" is called.
*/
function drush_civicrm_cacheclear() {
_civicrm_init();
// Clear the classloader cache variable
// Should be done in CiviCRM core so that the system flush always deletes
// the variable, however, it needs to be done early enough before the
// ClassLoader initialization. FIXME.
variable_del('civicrm_class_loader');
// Flush all caches using the API
$params = ['version' => 3];
if (drush_get_option('triggers', FALSE)) {
$params['triggers'] = 1;
}
if (drush_get_option('sessions', FALSE)) {
$params['session'] = 1;
}
try {
$result = civicrm_api3('System', 'flush', $params);
}
catch (CiviCRM_API3_Exception $e) {
drush_log(dt('An error occurred: !message', ['!message' => $e->getMessage()]), 'error');
return;
}
drush_log(dt('The CiviCRM cache has been cleared.'), 'ok');
}
/**
* Implements drush_hook_COMMAND_validate() for civicrm-enable-debug().
*/
function drush_civicrm_enable_debug_validate() {
return _civicrm_init();
}
function drush_civicrm_enable_debug() {
$settings = [
'debug_enabled' => 1,
'backtrace' => 1,
];
foreach ($settings as $key => $val) {
try {
$result = civicrm_api3('Setting', 'create', [$key => $val]);
}
catch (CiviCRM_API3_Exception $e) {
drush_log(dt('An error occurred: !message', ['!message' => $e->getMessage()]), 'error');
return;
}
}
drush_log(dt('CiviCRM debug setting enabled.'), 'ok');
}
/**
* Implements drush_hook_COMMAND_validate() for civicrm-disable-debug().
*/
function drush_civicrm_disable_debug_validate() {
return _civicrm_init();
}
function drush_civicrm_disable_debug() {
$settings = [
'debug_enabled' => 0,
'backtrace' => 0,
];
foreach ($settings as $key => $val) {
try {
$result = civicrm_api3('Setting', 'create', [$key => $val]);
}
catch (CiviCRM_API3_Exception $e) {
drush_log(dt('An error occurred: !message', ['!message' => $e->getMessage()]), 'error');
return;
}
}
drush_log(dt('CiviCRM debug setting disabled.'), 'ok');
}
/**
* Implements drush_hook_COMMAND_validate() for civicrm-upgrade().
*/
function drush_civicrm_upgrade_validate() {
// TODO: use Drush to download tarfile.
// TODO: if tarfile is not specified, see if the code already exists and use that instead.
$tarfile = drush_get_option('tarfile', FALSE);
if (!$tarfile) {
return drush_set_error('CIVICRM_TAR_NOT_SPECIFIED', dt('Tarfile not specified.'));
}
//FIXME: throw error if tarfile is not in a valid format.
if (!defined('CIVICRM_UPGRADE_ACTIVE')) {
define('CIVICRM_UPGRADE_ACTIVE', 1);
}
return _civicrm_init();
}
/**
* Implementation of command 'civicrm-upgrade'
*/
function drush_civicrm_upgrade() {
global $civicrm_root;
$tarfile = drush_get_option('tarfile', FALSE);
$date = date('YmdHis');
$backup_file = "civicrm";
$basepath = explode('/', $civicrm_root);
array_pop($basepath);
$project_path = implode('/', $basepath) . '/';
$drupal_root = drush_get_context('DRUSH_DRUPAL_ROOT');
$backup_dir = drush_get_option('backup-dir', $drupal_root . '/../backup');
$backup_dir = rtrim($backup_dir, '/');
drush_print(dt("\nThe upgrade process involves - "));
drush_print(dt("1. Backing up current CiviCRM code as => !path",
['!path' => "$backup_dir/modules/$date/$backup_file"]
));
drush_print(dt("2. Backing up database as => !path",
['!path' => "$backup_dir/modules/$date/$backup_file.sql"]
));
drush_print(dt("3. Unpacking tarfile to => !path",
['!path' => "$project_path"]
));
drush_print(dt("4. Executing civicrm/upgrade?reset=1 just as a browser would.\n"));
if (!drush_confirm(dt('Do you really want to continue?'))) {
return drush_user_abort();
}
@drush_op('mkdir', $backup_dir, 0777);
$backup_dir .= '/modules';
@drush_op('mkdir', $backup_dir, 0777);
$backup_dir .= "/$date";
@drush_op('mkdir', $backup_dir, 0777);
$backup_target = $backup_dir . '/' . $backup_file;
if (!drush_op('rename', $civicrm_root, $backup_target)) {
return drush_set_error('CIVICRM_BACKUP_FAILED', dt('Failed to backup CiviCRM project directory !source to !backup_target',
['!source' => $civicrm_root, '!backup_target' => $backup_target]
));
}
drush_log(dt("\n1. Code backed up."), 'ok');
drush_set_option('result-file', $backup_target . '.sql');
drush_civicrm_sqldump();
drush_log(dt('2. Database backed up.'), 'ok');
// Decompress & Untar
_civicrm_extract_tarfile($project_path);
drush_log(dt('3. Tarfile unpacked.'), 'ok');
drush_log(dt("4. "));
if (drush_civicrm_upgrade_db_validate()) {
drush_civicrm_upgrade_db();
}
drush_log(dt("\nProcess completed."), 'completed');
}
/**
* Implements drush_hook_COMMAND_validate() for civicrm-restore().
*/
function drush_civicrm_restore_validate() {
_civicrm_dsn_init();
$restore_dir = drush_get_option('restore-dir', FALSE);
$restore_dir = rtrim($restore_dir, '/');
if (!$restore_dir) {
return drush_set_error('CIVICRM_RESTORE_NOT_SPECIFIED', dt('Restore-dir not specified.'));
}
$sql_file = $restore_dir . '/civicrm.sql';
if (!file_exists($sql_file)) {
return drush_set_error('CIVICRM_RESTORE_CIVICRM_SQL_NOT_FOUND', dt('Could not locate civicrm.sql file in the restore directory.'));
}
$code_dir = $restore_dir . '/civicrm';
if (!is_dir($code_dir)) {
return drush_set_error('CIVICRM_RESTORE_DIR_NOT_FOUND', dt('Could not locate civicrm directory inside restore-dir.'));
}
elseif (!file_exists("$code_dir/civicrm-version.php")) {
return drush_set_error('CIVICRM_RESTORE_DIR_NOT_VALID', dt('civicrm directory inside restore-dir, doesn\'t look to be a valid civicrm codebase.'));
}
return TRUE;
}
/**
* Implementation of command 'civicrm-restore'
*/
function drush_civicrm_restore() {
$restore_dir = drush_get_option('restore-dir', FALSE);
$restore_dir = rtrim($restore_dir, '/');