-
Notifications
You must be signed in to change notification settings - Fork 68
/
acl-config
executable file
·2328 lines (2024 loc) · 70.9 KB
/
acl-config
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
#!/usr/bin/env php
<?php
/**
* Acl Configuration Tool
*
* PHP Version 5
*
* @package XDMoD
* @author Ryan Rathsam <ryanrath@buffalo.edu>
* @link http://open.xdmod.org/
**/
require_once __DIR__ . '/../configuration/linker.php';
use CCR\DB;
use CCR\DB\iDatabase;
use CCR\Log;
use CCR\Json;
use ETL\Configuration\EtlConfiguration;
use ETL\EtlOverseer;
use ETL\EtlOverseerOptions;
use ETL\Utilities;
use User\Roles;
use Xdmod\Config;
const SCHEMA = 'moddb';
$opts = array(
't' => 'dryrun',
'v' => 'verbose',
'd' => 'debug',
'r' => 'recover',
'h' => 'help'
);
$dryRun = false;
$logLevel = Log::ERR;
$recover = false;
try {
$options = getopt(implode('', array_keys($opts)), array_values($opts));
foreach ($options as $key => $value) {
switch ($key) {
case 't':
case 'dryrun':
$dryRun = true;
break;
case 'v':
case 'verbose':
$logLevel = Log::INFO;
break;
case 'd':
case 'debug':
$logLevel = Log::DEBUG;
break;
case 'h':
case 'help':
displayHelp();
exit(0);
break;
case 'r':
case 'recover':
$recover = true;
break;
}
}
/**
* The Log instance for this script. It defaults to writing to 'console'
*
* @var Log
**/
$log = Log::factory(
'acl-import',
array(
'file' => false,
'db' => false,
'mail' => false,
'console' => true,
'consoleLogLevel' => $logLevel
)
);
main();
} catch (Exception $e) {
do {
fwrite(STDERR, $e->getMessage() . "\n");
fwrite(STDERR, $e->getTraceAsString() . "\n");
} while ($e = $e->getPrevious());
exit(1);
}
/**
*
**/
function main()
{
global $dryRun, $log, $verify, $logLevel, $recover;
$log->notice("*** Beginning Acl Configuration Tool...");
$log->info(
sprintf(
"*** Launched with parameters [verify: %s, dryrun: %s, verbose: %s]",
boolToString($verify),
boolToString($dryRun),
logLevelToVerbosity($logLevel)
)
);
$result = verifyAclSetup();
if ($result > 0) {
exit($result);
}
// Make sure that all of the required tables are present
runEtlProcess('acls-xdmod-management');
// a role/acl blacklist. 'default' doesn't actually exist so don't bother
// processing it.
$blacklist = array('default');
// the sections of roles.json that we want to process.
$sections = array('permitted_modules', 'query_descripters', 'display', 'type', 'hierarchies');
// the ultimate destination for the parsed information from
// roles/datawarehouse
$results = array();
$config = Config::factory();
// Module Retrieval
$modules = $config['modules'];
// Remove the warning to users that this files contents are automatically
// generated and that they modify it at their own risk.
if (isset($modules['#'])) {
unset($modules['#']);
}
if (isset($modules['WARNING'])) {
unset($modules['WARNING']);
}
$moduleNames = array_keys($modules);
$moduleHierarchies = array();
// Role Retrieval
$allRoles = Roles::getRoleNames($blacklist);
// Retrieve the annotated combined config information for each section.
$rawHierarchies = $config->getModuleSection('hierarchies', $moduleNames);
$rawRoles = $config->getModuleSection('roles', $moduleNames);
$rawRealms = $config->getModuleSection('datawarehouse', $moduleNames);
foreach ($modules as $module => $moduleData) {
// Setup the metadata to be used in the filtering.
if ($module !== DEFAULT_MODULE_NAME) {
$metaData = array(
'modules' => array(
DEFAULT_MODULE_NAME,
$module
)
);
} else {
$metaData = array(
'modules' => array(
DEFAULT_MODULE_NAME,
)
);
}
// Retrieve the section information filtered by module.
$hierarchies = $config->filterByMetaData(
$rawHierarchies,
$metaData
);
$roles = $config->filterByMetaData(
$rawRoles,
$metaData
);
$realms = $config->filterByMetaData(
$rawRealms,
$metaData
);
// Process the hierarchies provided by this module, if any.
if (count($hierarchies) > 0 && isset($hierarchies['hierarchies'])) {
$moduleHierarchies[$module] = $hierarchies['hierarchies'];
}
// Process the roles provided by this module, if any.
if (count($roles) > 0 && isset($roles['roles'])) {
$moduleRoles = $roles['roles'];
foreach ($allRoles as $role) {
$roleData = isset($moduleRoles[$role]) ? $moduleRoles[$role] : array();
if (array_key_exists('extends', $roleData)) {
$roleData = array_merge_recursive($moduleRoles[$roleData['extends']], $roleData);
}
foreach ($sections as $section) {
if (isset($roleData[$section])) {
$results[$module]['acls'][$role][$section] = $roleData[$section];
}
}
}
}
// Process the realms provided by this module, if any.
if (count($realms) > 0 && isset($realms['realms'])) {
foreach ($realms['realms'] as $realm => $data) {
$groupBys = isset($data['group_bys']) ? $data['group_bys'] : null;
$statistics = isset($data['statistics']) ? $data['statistics'] : null;
$results[$module]['realms'][$realm] = array(
'group_bys' => $groupBys,
'statistics' => $statistics
);
}
}
}
$db = null;
// The database connection will always be needed, even during dry-run because there are
// informational queries that will be executed even though information is not being changed.
$log->debug("*** Conducting Database Verification...");
if (!verifyDatabase()) {
$log->err("Unable to connect to the database, please check the following: \n\t - settings for 'database' in portal_settings.ini are correct.\n\t - the database identified by the 'database' section of portal_settings.ini is running, accepting connections, and that the user specified has connection privileges.");
exit(1);
}
$log->debug("*** Database Verification Passed!");
$db = DB::factory('database');
// Ensure that we're starting from scratch while backing up the tables that
// we do not manage ( user_acls, user_acl_group_by_parameters ). These
// tables will be re-populated after we are done creating / re-populating
// the managed tables.
/**
* This sql statement should serve as the select query that will be used to
* create the backup table 'user_acls_bkup'.
*/
$userAclCreateBkup = <<<SQL
SELECT
ua.user_id,
a.name AS acl_name
FROM user_acls ua
JOIN acls a ON a.acl_id = ua.acl_id
SQL;
/**
* Serves as the insertion query to utilize when reconstituting the
* user_acls table. Notice the 'LEFT JOIN' on 'acls' and accompanying
* where clause 'a.acl_id IS NOT NULL'. These are to ensure that if an
* acl was removed as part of the sync those orphan records do not make
* their way back into the system.
*/
$userAclRepopulate = <<<SQL
INSERT INTO user_acls (user_id, acl_id)
SELECT
ua.user_id,
a.acl_id
FROM user_acls_bkup ua
LEFT JOIN acls a ON a.name = ua.acl_name
WHERE a.acl_id IS NOT NULL
SQL;
/**
* to serve as the select query that will be used to create the backup
* table 'user_acl_group_by_parameters_bkup'.
*/
$uagbpCreateBkup = <<<SQL
SELECT
uagbp.user_id,
a.name AS acl_name,
m.name AS group_by_module_name,
r.name AS group_by_realm_name,
gb.name AS group_by_name,
uagbp.value
FROM user_acl_group_by_parameters uagbp
JOIN acls a ON a.acl_id = uagbp.acl_id
JOIN group_bys gb ON gb.group_by_id = uagbp.group_by_id
JOIN realms r ON r.realm_id = gb.realm_id
JOIN modules m ON m.module_id = gb.module_id;
SQL;
/**
* Serves as the insertion query to utilize when reconstituting the
* user_acl_group_by_parameters table. A number of steps have been
* taken to ensure that orphan records are not introduced into the
* system post sync. In particular we prevent orphan records from the
* following tables:
* - acls
* - modules
* - realms
* - group_bys
*/
$uagbpRepopulate = <<<SQL
INSERT INTO user_acl_group_by_parameters (user_id, acl_id, group_by_id, value)
SELECT
uagbp.user_id,
a.acl_id,
gb.group_by_id,
uagbp.value
FROM user_acl_group_by_parameters_bkup uagbp
LEFT JOIN acls a ON a.name = uagbp.acl_name
LEFT JOIN modules m ON m.name = uagbp.group_by_module_name
LEFT JOIN realms r ON r.name = uagbp.group_by_realm_name
LEFT JOIN group_bys gb
ON gb.name = uagbp.group_by_name AND
gb.module_id = m.module_id AND
gb.realm_id = r.realm_id
WHERE a.acl_id IS NOT NULL AND
m.module_id IS NOT NULL AND
r.realm_id IS NOT NULL AND
gb.group_by_id IS NOT NULL;
SQL;
$tablesToBeBackedUp = array(
'user_acls' => array(
'create_sql' => $userAclCreateBkup,
'populate_sql' => $userAclRepopulate
),
'user_acl_group_by_parameters' => array(
'create_sql' => $uagbpCreateBkup,
'populate_sql' =>$uagbpRepopulate
)
);
$nonManagedBackupTables = array_reduce(
array_keys($tablesToBeBackedUp),
function($carry, $item) {
$carry[] = "${item}_bkup";
return $carry;
},
array()
);
/* acl-config "recovery" documentation
*
* Before diving into a description of how acl-config's "recovery" flag works, some definitions
* are included below to help while reading the rest of the documentation.
*
* Definitions:
*
* - non-managed tables: These are tables that we are not able to be re-create from our
* available configuration files ( roles.json / datawarehouse.json ). In these tables case,
* a record is added when a user is created with / updated to have a relationship with a
* particular acl. This is most often done via the User Management portion of the Internal
* Dashboard.
* Also, these tables, and their need to re-generate their managed table foreign keys, are
* the reason we have a "recovery" flag in the first place.
*
* Current tables include:
* - user_acls
* - user_acl_group_by_parameters
*
* - managed tables: These tables are able to be re-created from our available configuration
* files ( roles.json / datawarehouse.json ).
*
* Current tables include:
* - user_acl_group_by_parameters
* - user_acls
* - acl_tabs
* - tabs
* - acl_hierarchies
* - acl_group_bys
* - acls
* - acl_types
* - group_bys
* - statistics
* - hierarchies
* - realms
* - modules
*
* Now we will walk through a number of script executions which will provide the necessary
* context for understanding how the "recovery" process is implemented. These script executions
* occur in the order they are presented.
*
* - Successful Script Execution:
* - command line: `acl-config`
* - Order of Operations:
* - Backup tables do not exist by default so the first thing that occurs is that they are
* created / populated.
* - `backupNonManagedTables($db, $tablesToBeBackedUp);`
* - Managed tables are wiped / re-created from the various configuration files ( roles.json,
* datawarehouse.json )
* - The non-managed tables are restored using the newly populated managed tables and the
* backup tables.
* - The backup tables are removed:
* - `dropTables($db, $nonManagedBackupTables);`
* - *** NOTE *** if the script completes successfully the backup tables will not be
* present after the script ends.
*
* - Unsuccessful Script Execution:
* - command line: `acl-config`
* - Order of Operations:
* - Backup tables do not exist by default so the first thing that occurs is that they are
* created / populated.
* - `backupNonManagedTables($db, $tablesToBeBackedUp);`
* - *** at some point during the managed table wipe / re-creation an error occurs or the
* script is killed. ***
* - The removal of the backup tables is never executed and so they are still present.
*
* - Recovery Script Execution:
* - command line: `acl-config [-r|--recovery]`
* - Order of Operations:
* - Backup tables *do* exist as the previous execution was not successful.
* - Because the backup tables exist *and* the recover flag was supplied we skip the step
* that creates / populates the backup tables.
* - Managed tables are wiped / re-created from the various configuration files ( roles.json,
* datawarehouse.json )
* - The non-managed tables are restored from the existing backup tables and newly populated
* managed tables. This is where the *recovery* occurs.
* - The backup tables are removed.
*
* *** Important Notes ***
*
* - If there are changes to the non-managed tables ( user_acls, user_acl_group_by_parameters )
* *after* a failed run but *before* acl-config is run with the --recover flag, then these
* changes will *not* be recovered.
*/
$backupTablesExist = tablesExist($db, $nonManagedBackupTables, SCHEMA, false);
if ($backupTablesExist && !$recover) {
$log->err('Backup tables detected! ');
$log->err('Unable to continue!');
$log->err('This may indicate a failed previous run.');
$log->err('Please see the XDMoD Troubleshooting documentation to resolve.');
exit(1);
} elseif (!$backupTablesExist) {
if ($recover) {
$log->warning('Recover mode specified but no backup tables exist.');
$log->warning('Script execution will continue as normal.');
}
backupNonManagedTables($db, $tablesToBeBackedUp);
}
wipeManagedTables($db);
// Create Managed Tables
runEtlProcess('acls-xdmod-management');
repopulateNonManagedTables($db, $tablesToBeBackedUp);
// Process the xdmod module first
if (array_key_exists(DEFAULT_MODULE_NAME, $modules)) {
processModules(
$db,
array(
DEFAULT_MODULE_NAME => $modules[DEFAULT_MODULE_NAME]
)
);
unset($modules[DEFAULT_MODULE_NAME]);
}
// Process the rest of the modules
processModules($db, $modules);
// Process the xdmod hierarchies into the database first
if (array_key_exists(DEFAULT_MODULE_NAME, $moduleHierarchies)) {
processHierarchies(
$db,
array(
DEFAULT_MODULE_NAME => $moduleHierarchies[DEFAULT_MODULE_NAME]
)
);
unset($moduleHierarchies[DEFAULT_MODULE_NAME]);
}
// process the rest of the modules hierarchies.
processHierarchies($db, $moduleHierarchies);
// Make sure to process the default module first first.
if (array_key_exists(DEFAULT_MODULE_NAME, $results)) {
$xdmod = $results[DEFAULT_MODULE_NAME];
unset($results[DEFAULT_MODULE_NAME]);
processResult($db, DEFAULT_MODULE_NAME, $xdmod, $modules);
}
foreach ($results as $module => $moduleData) {
processResult($db, $module, $moduleData, $modules);
}
// Now re-populate the user related tables.
repopulateNonManagedTables($db, $tablesToBeBackedUp);
// Make sure we drop the backup tables
dropTables($db, $nonManagedBackupTables);
// Run the acl cleanup scripts
runEtlProcess('acls-import');
}
/**
* Create a backup of the user related acl tables so that we can later re-populate
* them
*
* @param iDatabase $db the database that the user related tables will be backed
* up in.
* @param array $tables
* @throws Exception if a problem occurs while executing table backup sql.
*/
function backupNonManagedTables(iDatabase $db, array $tables)
{
global $dryRun, $log;
$log->info("Backing Up User Related Tables...");
foreach($tables as $table => $queries) {
$creationQuery = $queries['create_sql'];
$query = <<<SQL
CREATE TABLE ${table}_bkup AS $creationQuery;
SQL;
$log->debug("Backup query [$table]: $query");
if ($dryRun) {
$log->notice("Table[$table] would have been created");
continue;
}
// throws exception or returns row count
$rows = $db->execute($query);
$log->debug(sprintf('Inserted %d rows into %s', $rows, $table));
}
$log->info("User Related Tables Backed Up!");
}
/**
* Attempt to drop the tables managed by this script.
*
* @param iDatabase $db
* @throws Exception if a problem occurs while executing sql.
*/
function wipeManagedTables(iDatabase $db)
{
global $dryRun, $log;
$log->info("Wiping Managed Tables...");
$tables = array(
'user_acl_group_by_parameters',
'user_acls',
'acl_tabs',
'tabs',
'acl_hierarchies',
'acl_group_bys',
'acls',
'acl_types',
'group_bys',
'statistics',
'hierarchies',
'realms',
'modules'
);
foreach($tables as $table) {
$query = <<<SQL
DROP TABLE $table;
SQL;
if ($dryRun) {
$log->info("Would have dropped: $table");
continue;
}
$log->debug("Dropping Table\n$query");
$db->execute($query);
$log->debug("Table dropped");
}
$log->info("Managed Tables Wiped!");
}
/**
* Re-populate the user related tables
* @param iDatabase $db the database to utilize while re-populating the tables.
* @param array $tables the tables to be re-populated.
*/
function repopulateNonManagedTables(iDatabase $db, array $tables)
{
global $dryRun, $log;
$log->info("Repopulating Tables...");
foreach($tables as $table => $queries) {
$query = $queries['populate_sql'];
if ($dryRun) {
$log->info("For Table[$table]: \n$query");
continue;
}
$rows = $db->execute($query);
$message = $rows > 0
? "Table [$table] => records[$rows] populated"
: "Table [$table] => no records populated";
$log->debug($message);
}
$log->info("Re-Population of Tables Complete!");
}
/**
*
*
* @param iDatabase $db
* @param array $hierarchies
* @return void
* @throws Exception
* @internal param string $module
*/
function processHierarchies(iDatabase $db, $hierarchies)
{
global $dryRun, $log;
$log->notice("Processing Hierarchies...");
// SELECT the incoming data IFF
// There is not a record in hierarchies that has:
// - the same name / display as incoming
// - but a different module_id than incoming
$query = <<<SQL
INSERT INTO hierarchies(module_id, name, display)
SELECT inc.module_id, inc.name, inc.display
FROM
(
SELECT
m.module_id AS module_id,
:name AS name,
:display AS display
FROM modules m
WHERE BINARY m.name = BINARY :module_name
) inc
LEFT JOIN hierarchies cur
ON BINARY cur.name = BINARY inc.name AND
BINARY cur.display = BINARY cur.display
WHERE cur.hierarchy_id IS NULL;
SQL;
$log->debug($query);
$inserted = 0;
$processed = 0;
foreach ($hierarchies as $module => $hierarchyData) {
foreach ($hierarchyData as $hierarchy) {
$name = null;
$display = null;
if (null === $hierarchy['name']) {
throw new Exception("Malformed hierarchy entry for module $module. No name property.");
}
$name = $hierarchy['name'];
if (null === $hierarchy['display']) {
$log->warning("Hierarchy entry for module $module missing 'display' property, generating default value.");
$display = $name;
} else {
$display = $hierarchy['display'];
}
if ($dryRun) {
$log->info("[SUCCESS] created hierarchy [module: $module, name: $name, display: $display]");
continue;
}
$params = array(
':name' => $name,
':display' => $display,
':module_name' => $module
);
$log->debug($params);
$modified = $db->execute($query, $params);
$inserted += $modified;
}
$processed += count($hierarchies);
}
$log->notice("Hierarchies Processed: $processed, Inserted: $inserted");
}
/**
*
* @param iDatabase $db
* @param string $module
* @param array $moduleData
* @param array $modules
*
* @return void
**/
function processResult(iDatabase $db, $module, $moduleData, $modules)
{
global $log;
// Data for a module may contain a list of ACLs, a list of Realms and the access that is
// granted, or both.
$acls = ( isset($moduleData['acls']) ? $moduleData['acls'] : null );
$realms = ( isset($moduleData['realms']) ? $moduleData['realms'] : null );
$log->info("Processing Module: $module");
if ($modules === null) {
$log->err("Unable to process $module, missing module information. Is there a $module.json file in CONF_DIR/datawarehouse.d?");
return;
}
if ($realms !== null) {
processRealms($db, $module, $realms);
} else {
$log->warning("No realm information for module $module skipping...");
}
if ($acls !== null) {
processAcls($db, $module, ( null !== $realms ? $realms : array() ), $acls);
} else {
$log->info("No acl information for module $module skipping...");
}
}
/**
* Attempt to create the module version defined by the provided information.
*
* @param iDatabase $db the db. null in the case of a dryRun.
* @param integer $moduleId the module id
* @param string $installedOn the date this module version was created.
* @param array $version the version information
*
* @return integer|null
**/
function createModuleVersion(iDatabase $db, $moduleId, $installedOn, array $version)
{
global $log, $dryRun;
$major = $version['major'];
$minor = $version['minor'];
$patch = $version['patch'];
$preRelease = $version['pre_release'];
$moduleVersion = "$major.$minor.$patch $preRelease";
$query = <<<SQL
INSERT INTO module_versions (
module_id,
version_major,
version_minor,
version_patch,
version_pre_release,
created_on,
last_modified_on)
SELECT inc.*
FROM (SELECT
:module_id AS module_id,
:version_major AS version_major,
:version_minor AS version_minor,
:version_patch AS version_patch,
:version_pre_release AS version_pre_release,
:installed_on AS installed_on,
NOW() AS last_modified_on) inc
LEFT JOIN module_versions cur
ON BINARY cur.module_id = BINARY inc.module_id AND
BINARY cur.version_major = BINARY inc.version_major AND
BINARY cur.version_minor = BINARY inc.version_minor AND
BINARY cur.version_patch = BINARY inc.version_patch AND
BINARY cur.version_pre_release = BINARY inc.version_pre_release
WHERE cur.module_version_id IS NULL;
SQL;
$parameters = array(
':module_id' => $moduleId,
':version_major' => $major,
':version_minor' => $minor,
':version_patch' => $patch,
':version_pre_release' => $preRelease,
':installed_on' => $installedOn
);
$log->debug($query);
$log->debug(json_encode($parameters));
if ($dryRun) {
$log->info("[SUCCESS] Created Module Version: $moduleVersion");
return null;
}
$inserted = $db->execute(
$query,
$parameters
);
if ($inserted === 0) {
$log->info("[ALREADY EXISTS] Retrieving Identifier for: $moduleVersion");
$query = <<<SQL
SELECT mv.module_version_id
FROM module_versions mv
WHERE BINARY mv.module_id = BINARY :module_id AND
BINARY mv.version_major = BINARY :version_major AND
BINARY mv.version_minor = BINARY :version_minor AND
BINARY mv.version_patch = BINARY :version_patch AND
BINARY mv.version_pre_release = :version_pre_release
SQL;
$results = $db->query(
$query,
array(
':module_id' => $moduleId,
':version_major' => $major,
':version_minor' => $minor,
':version_patch' => $patch,
':version_pre_release' => $preRelease
)
);
$moduleVersionId = $results[0]['module_version_id'];
return $moduleVersionId;
} else {
$log->info("[SUCCESS] Created Module Version: $moduleVersion");
return $db->handle()->lastInsertId();
}
}
/**
* Attempt to create a Module defined by the provided information.
*
* @param iDatabase $db the database to use. null if dryRun is true.
* @param string $name the internal name of the module
* @param string $display the value that should be displayed to users.
* @param boolean $enabled whether or not the module is enabled.
*
* @return integer|null
**/
function createModule(iDatabase $db, $name, $display, $enabled)
{
global $dryRun, $log;
$query = <<<SQL
INSERT INTO modules(name, display, enabled)
SELECT inc.*
FROM (
SELECT :name AS name,
:display AS display,
:enabled AS enabled ) inc
LEFT JOIN modules cur
ON BINARY cur.name = BINARY inc.name AND
BINARY cur.display = BINARY inc.display
WHERE cur.module_id IS NULL
SQL;
$parameters = array(
':name' => $name,
':display' => $display,
':enabled' => $enabled
);
$log->debug($query);
$log->debug(json_encode($parameters));
if ($dryRun) {
$log->info("[SUCCESS] Created module: $name");
return null;
}
$inserted = $db->execute(
$query,
$parameters
);
if ($inserted === 0) {
$log->info("[ALREADY EXISTS] Retrieving Identifier for Module: $name");
$select = <<<SQL
SELECT m.module_id
FROM modules m
WHERE BINARY m.name = BINARY :name AND
BINARY m.display = BINARY :display
SQL;
$results = $db->query(
$select,
array(
':name' => $name,
':display' => $display
)
);
return $results[0]['module_id'];
} else {
$log->info("[SUCCESS] Created module: $name");
return $db->handle()->lastInsertId();
}
}
/**
* Attempt to associate the provided module w/ the provided module version.
*
* @param iDatabase $db the database to be used in the
* operation. null if dryRun is true.
* @param integer $moduleId the id of the module in question
* @param integer $moduleVersionId the id of the version in question
*
* @return void
**/
function associateModuleAndVersion(iDatabase $db, $moduleId, $moduleVersionId)
{
global $dryRun, $log;
$exists = <<<SQL
SELECT m.module_id
FROM modules m
WHERE BINARY m.module_id = BINARY :module_id AND
BINARY m.current_version_id = BINARY :current_version_id
SQL;
$params = array(
':module_id' => $moduleId,
':current_version_id' => $moduleVersionId
);
$log->debug($exists);
$log->debug(json_encode($params));
if ($dryRun) {
$log->info("[SUCCESS] Associated Module and Module Version.");
return;
}
$results = $db->query($exists, $params);
if (count($results) > 0) {
$log->info("[ALREADY EXISTS] This module and version are already associated.");
return;
}
$query = <<<SQL
UPDATE modules
SET current_version_id = :current_version_id
WHERE BINARY module_id = BINARY :module_id
SQL;
$log->debug($query);
$log->debug(json_encode($params));
$updated = $db->execute($query, $params);
if ($updated === 1) {
$log->info("[SUCCESS] Associated Module and Module Version.");
} else {
$log->err("[FAILURE] Unable to associate Module and Module Version.");
}
}
/**
* Process the provided array of modules into the database.
*
* @param iDatabase $db the database that will be used while processing the
* provided modules
* @param array[] $modules the modules to be inserted into the database.
*
* @return void
**/
function processModules(iDatabase $db, array $modules)
{
global $dryRun, $log;
foreach ($modules as $name => $data) {
if (!isset($data['version'])) {
$log->warning("No Version information for Module: $name. skipping...");
break;
}
$display = isset($data['display']) ? $data['display'] : $name;
$enabled = isset($data['enabled']) ? $data['enabled'] : true;
$version = $data['version'];
$installedOn = isset($data['installed_on'])
? $data['installed_on']
: date("Y-m-d");
$moduleId = createModule(
$db,
$name,
$display,
$enabled
);
$moduleVersionId = createModuleVersion(
$db,
$moduleId,
$installedOn,
$version
);
associateModuleAndVersion($db, $moduleId, $moduleVersionId);
}