-
Notifications
You must be signed in to change notification settings - Fork 3
/
dmt
654 lines (530 loc) · 23.8 KB
/
dmt
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
#!/usr/bin/php -q
<?php
use \StructuredDynamics\osf\php\api\ws\dataset\create\DatasetCreateQuery;
use \StructuredDynamics\osf\php\api\ws\auth\lister\AuthListerQuery;
use \StructuredDynamics\osf\php\api\ws\auth\registrar\access\AuthRegistrarAccessQuery;
use \StructuredDynamics\osf\php\api\framework\CRUDPermission;
use \StructuredDynamics\osf\framework\Namespaces;
// Set the working directory of this script to its home directory. That way, if it is ran from elsewhere,
// the relative paths will follow.
chdir(dirname(realpath($argv[0])));
include_once('inc/clt.php');
/*
The sync.php script does manage the importation of files on the file system.
A dataset can be composed of one or multiple files. One or multiple records are defined
in each file.
This scripts only check if a file has been modified on the file system and keep the
index of files' states updated.
Then "converters" are called by this script to perform specific conversion steps
needed by different datasets.
*/
if(PHP_SAPI != 'cli')
{
die('This is a shell application, so make sure to run this application in your terminal.');
}
// Get commandline options
$arguments = getopt('e::l::d::n::h::s::c:', array('help::',
'osf-web-services::',
'delete::',
'uri::',
'creator::',
'group::',
'title::',
'description::',
'queryextension::',
'config-id::',
'mime::',
'file::'));
// Displaying DSF's help screen if required
if(isset($arguments['h']) || isset($arguments['help']) || count($arguments) == 0)
{
cecho("Usage: dmt [OPTIONS]\n\n\n", 'WHITE');
cecho("Usage examples: \n", 'WHITE');
cecho(" Synchronizing all datasets: dmt -s\n", 'WHITE');
cecho(" Synchronizing a single dataset: dmt -s --config-id=\"My-Dataset-Id-From-Sync.ini\"\n", 'WHITE');
cecho(" Deleting a dataset: dmt -d --uri=\"http://.../uri/of/record/to/delete/\" --osf-web-services=\"http://osf-web-services-instance.com/ws/\"\n", 'WHITE');
cecho(" Creating an empty dataset: dmt --title=\"Foo\" -n --uri=\"http://.../uri/of/record/to/delete/\" --osf-web-services=\"http://osf-web-services-instance.com/ws/\"\n", 'WHITE');
cecho(" List existing datasets: dmt -l --osf-web-services=\"http://osf-web-services-instance.com/ws/\"\n", 'WHITE');
cecho("Options:\n", 'WHITE');
cecho("-s Synchronize all the datasets listed in dmt.ini\n", 'WHITE');
cecho("-n Create a new empty dataset\n", 'WHITE');
cecho("-d Delete an existing dataset\n", 'WHITE');
cecho("-l List all the accessible datasets\n", 'WHITE');
cecho("-e Export a dataset\n", 'WHITE');
cecho("-h, --help Show this help section\n\n", 'WHITE');
cecho("Dataset Creation Options:\n", 'WHITE');
cecho("--osf-web-services=\"[URL]\" (required) Target OSF Web Services endpoints URL.\n", 'WHITE');
cecho(" Example: 'http://localhost/ws/'\n", 'WHITE');
cecho("--uri=\"[URI]\" (required) URI of the dataset to create\n", 'WHITE');
cecho("--title=\"[TITLE]\" (required) Title of the new dataset\n", 'WHITE');
cecho("--group=\"[URI]\" (required) URI of the first group that will have access to this dataset\n", 'WHITE');
cecho("--creator=\"[URI]\" (optional) URI of the creator of this dataset\n", 'WHITE');
cecho("--description=\"[DESCRIPTION]\" (optional) Description of the new dataset\n", 'WHITE');
cecho("--queryextension=\"[CLASS]\" (optional) Class of the QueryExtension to use for creating this new dataset.\n", 'WHITE');
cecho(" The class should include the full namespace.'\n", 'WHITE');
cecho(" Example: 'StructuredDynamics\\osf\\framework\\MyQuerierExtension'\n", 'WHITE');
cecho("Dataset Deletation Options:\n", 'WHITE');
cecho("--osf-web-services=\"[URL]\" (required) Target OSF Web Services endpoints URL.\n", 'WHITE');
cecho(" Example: 'http://localhost/ws/'\n", 'WHITE');
cecho("Dataset Export Options:\n", 'WHITE');
cecho("--osf-web-services=\"[URL]\" (required) Target OSF Web Services endpoints URL.\n", 'WHITE');
cecho(" Example: 'http://localhost/ws/'\n", 'WHITE');
cecho("--file=\"[FILE]\" (required) File where to export the dataset.\n", 'WHITE');
cecho(" Example: '/tmp/my_exported_dataset.rdf'\n", 'WHITE');
cecho("--mime=\"[URL]\" (optional) Specify the export format; One of:\n", 'WHITE');
cecho(" (a) application/rdf+xml (default)'\n", 'WHITE');
cecho(" (b) application/rdf+n3'\n", 'WHITE');
cecho("--uri=\"[URI]\" (optional) URI of the dataset to create\n\n", 'WHITE');
cecho("Dataset Listing Options:\n", 'WHITE');
cecho("--osf-web-services=\"[URL]\" (required) Target OSF Web Services endpoints URL.\n", 'WHITE');
cecho(" Example: 'http://localhost/ws/'\n", 'WHITE');
cecho("Configuration File Options:\n", 'WHITE');
cecho("-c [FILE] Specifies the configuration file to use. Can include the \n", 'WHITE');
cecho(" full path. If the full path is not specified, the DSF \n", 'WHITE');
cecho(" will try to find it from the current folder.\n", 'WHITE');
cecho("--config-id=\"[ID]\" (optional) Dataset ID, within the target configuration file,\n", 'WHITE');
cecho(" to run for this query\n", 'WHITE');
exit;
}
if(isset($arguments['n']))
{
// Make sure the required arguments are defined in the arguments
if(empty($arguments['osf-web-services']))
{
cecho("Missing the --osf-web-services parameter for creating a new dataset.\n", 'RED');
exit;
}
if(empty($arguments['uri']))
{
cecho("Missing the --uri parameter for creating a new dataset.\n", 'RED');
exit;
}
if(empty($arguments['group']))
{
cecho("Missing the --group parameter for creating a new dataset.\n", 'RED');
exit;
}
if(empty($arguments['title']))
{
cecho("Missing the --title parameter for creating a new dataset.\n", 'RED');
exit;
}
}
// Reading the INI file to synch all setuped datasets
$setup = NULL;
$syncFilePath = '';
if(isset($arguments['c']))
{
if(file_exists($arguments['c']))
{
// The full path of the file is defined in the -c argument
$setup = parse_ini_file($arguments['c'], TRUE);
$syncFilePath = $arguments['c'];
}
elseif(file_exists(getcwd().'/'.$arguments['c']))
{
// The full path of the config file is not defined in the -c argument,
// This means that we try to load it from the local folder.
$setup = parse_ini_file(getcwd().'/'.$arguments['c'], TRUE);
$syncFilePath = getcwd().'/'.$arguments['c'];
}
else
{
$syncFilePath = $arguments['c'];
}
}
else
{
// The -c argument is not defined, so we try to find the dmt.ini file from
// the current directory
$setup = parse_ini_file(getcwd()."/dmt.ini", TRUE);
$syncFilePath = getcwd()."/dmt.ini";
}
if(!$setup)
{
cecho('An error occured when we tried to parse the '.$syncFilePath.' file. Make sure it is parseable and try again.', 'GREEN');
exit;
}
// Create credentials array
$credentials = array(
'osf-web-services' => (isset($arguments['osf-web-services']) ? $arguments['osf-web-services'] : ''),
'application-id' => $setup["credentials"]["application-id"],
'api-key' => $setup["credentials"]["api-key"],
'user' => $setup["credentials"]["user"],
);
// Initiliaze needed resources to run this script
ini_set("display_errors", "On");
ini_set("memory_limit", $setup["config"]["memory"]."M");
set_time_limit(65535);
$osfWebServicesFolder = rtrim($setup["config"]["osfWebServicesFolder"], "/");
include_once($osfWebServicesFolder."/StructuredDynamics/SplClassLoader.php");
// The user want to list all the accessible datasets
if(isset($arguments['l']))
{
// Make sure the required arguments are defined in the arguments
if(empty($arguments['osf-web-services']))
{
cecho("Missing the --osf-web-services parameter for listing accessible datasets.\n", 'RED');
exit;
}
include_once('inc/getDatasets.php');
$datasets = getDatasets($credentials);
showDatasets($datasets);
exit;
}
// The user want to delete a dataset
if(isset($arguments['d']))
{
// Make sure the required arguments are defined in the arguments
if(empty($arguments['osf-web-services']))
{
cecho("Missing the --osf-web-services parameter for deleting the dataset.\n", 'RED');
exit;
}
include_once('inc/deleteDataset.php');
if(isset($arguments['uri']) && $arguments['uri'] != '')
{
cecho("Deleting dataset: ".$arguments['uri']."\n", 'CYAN');
$deleted = deleteDataset($arguments['uri'], $credentials);
}
else
{
// Show the list of accessible datasets
include_once('inc/getDatasets.php');
$datasets = getDatasets($credentials);
showDatasets($datasets);
$datasetNum = getInput('Which dataset number would you like to delete?');
$nb = 0;
$yes = FALSE;
$dataset = NULL;
foreach($datasets as $key => $dset)
{
$nb++;
if($nb == $datasetNum)
{
$yes = getInput('Are you sure you want to delete the '.$datasets[$key]['label'].'?');
$dataset = $datasets[$key];
break;
}
}
$yes = filter_var($yes, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE));
if($yes === NULL)
{
$yes = FALSE;
}
if($yes)
{
cecho("Deleting dataset: ".$dataset['label']."\n", 'CYAN');
$deleted = deleteDataset($dataset['uri'], $credentials);
}
}
exit;
}
// The user want to export a dataset
if(isset($arguments['e']))
{
// Make sure the required arguments are defined in the arguments
if(empty($arguments['osf-web-services']))
{
cecho("Missing the --osf-web-services parameter for exporting the dataset.\n", 'RED');
exit;
}
if(empty($arguments['file']))
{
cecho("Missing the --file parameter for exporting the dataset.\n", 'RED');
exit;
}
else
{
// Make sure the file is writable
if(!is_writable(dirname($arguments['file'])))
{
cecho("The file specified in the --file parameter is not writable by the DMT tool.\n", 'RED');
exit;
}
}
$mime = 'application/rdf+xml';
if(!empty($arguments['mime']))
{
// Make sure the mime is supported
if($arguments['mime'] != 'application/rdf+xml' &&
$arguments['mime'] != 'application/rdf+n3')
{
cecho("The specified mime type is unsupported.\n", 'RED');
exit;
}
else
{
$mime = $arguments['mime'];
}
}
include_once('inc/exportDataset.php');
if(isset($arguments['uri']) && $arguments['uri'] != '')
{
cecho("Exporting dataset: ".$arguments['uri']."\n", 'CYAN');
$deleted = exportDataset($arguments['uri'], $credentials, $arguments['file'], $mime);
}
else
{
// Show the list of accessible datasets
include_once('inc/getDatasets.php');
$datasets = getDatasets($credentials);
showDatasets($datasets);
$datasetNum = getInput('Which dataset number would you like to export?');
$nb = 0;
$dataset = NULL;
foreach($datasets as $key => $dset)
{
$nb++;
if($nb == $datasetNum)
{
$dataset = $datasets[$key];
break;
}
}
cecho("Exporting dataset: ".$dataset['label']."\n", 'CYAN');
$exported = exportDataset($dataset['uri'], $credentials, $arguments['file'], $mime);
}
exit;
}
// We synchronize a series of dataset defined in a synchronization configuration file
if(isset($arguments['s']))
{
foreach($setup as $datasetName => $dataset)
{
if(isset($arguments['config-id']) && $arguments['config-id'] != $datasetName)
{
continue;
}
if($datasetName != "config")
{
$datasetName = preg_replace("/[^a-zA-Z0-9\-\s]/", "_", $datasetName);
$files = array();
$modifiedFiles = array(); // added or modified files
$hashIndexFile = $setup["config"]["indexesFolder"].$datasetName."hashIndex.md5";
$filesHash = array();
$updateFiles = array(); // array of paths+files to update
$hashFile = "";
$filesUpdated = array();
// Read the hashIndex file to check if files have been modified
/*
The hash table file has this format:
/local/file/path/:md5
*/
$hashIndex = @file_get_contents($hashIndexFile);
if($hashIndex)
{
$hashIndex = explode("\n", $hashIndex);
foreach($hashIndex as $hashRow)
{
$hash = explode(":", $hashRow);
if($hash[0] != "" && $hash[1] != "")
{
$filesHash[$hash[0]] = $hash[1];
}
}
// Free memory of the hash index
$hashIndex = NULL;
}
// Get all the path+files within all directories of the dataset folder
readDirectory($dataset["datasetLocalPath"], $files);
// Check for a filtering pattern.
if(isset($dataset["filteredFilesRegex"]))
{
foreach($files as $f)
{
$file = $f[0];
if(preg_match("/".$dataset["filteredFilesRegex"]."/", $f[1]) > 0)
{
$modified = FALSE;
// Check if the file is new
if(isset($filesHash[$file]))
{
// Check if the file as been modified
if(md5_file($file) != $filesHash[$file])
{
$modified = TRUE;
// Update the hash table that we will re-write later
$filesHash[$file] = md5_file($file);
}
}
else
{
// New file
$modified = TRUE;
// Update the hash table that we will re-write later
$filesHash[$file] = md5_file($file);
}
// Mark as modified if forceReloadSolrIndex or forceReload
// is specified for this dataset
if(strtolower($dataset["forceReload"]) == "true" ||
strtolower($dataset["forceReloadSolrIndex"]) == "true" )
{
$modified = TRUE;
}
// If the file as been added/modified, we re-index in the OSF Web Services
if($modified)
{
// Check for a date-stamp that we will use for sorting purposes.
preg_match("/\.(.*)\.rdf\.xml/", $f[1], $matches);
$key = -1;
if(count($matches) > 0)
{
$key = preg_replace("/[^0-9]*/", "", $matches[1]);
}
if($key != -1)
{
$updateFiles[$key] = $file;
}
else
{
array_push($updateFiles, $file);
}
}
}
}
}
else
{
// Get possible filters
$filteredFiles = explode(";", $dataset["filteredFiles"]);
foreach($files as $f)
{
$file = $f[0];
if(is_array($filteredFiles) && array_search($f[1], $filteredFiles) === FALSE)
{
continue;
}
$modified = FALSE;
// Check if the file is new
if(isset($filesHash[$file]))
{
// Check if the file as been modified
if(md5_file($file) != $filesHash[$file])
{
$modified = TRUE;
// Update the hash table that we will re-write later
$filesHash[$file] = md5_file($file);
}
}
else
{
// New file
$modified = TRUE;
// Update the hash table that we will re-write later
$filesHash[$file] = md5_file($file);
}
// Mark as modified if forceReloadSolrIndex or forceReload
// is specified for this dataset
if((isset($dataset["forceReload"]) && strtolower($dataset["forceReload"]) == "true") ||
(isset($dataset["forceReloadSolrIndex"]) && strtolower($dataset["forceReloadSolrIndex"])) == "true")
{
$modified = TRUE;
}
// If the file as been added/modified, we re-index in the OSF Web Services
if($modified)
{
array_push($updateFiles, $file);
}
}
}
// Order files by their timestamp; if not available, then this step doesn't matter
ksort($updateFiles, SORT_NUMERIC);
// Lets re-write the hash index
foreach($filesHash as $filePath => $md5)
{
$hashFile .= $filePath.":".$md5."\n";
}
// Update all added/modified files
if(count($updateFiles) > 0)
{
include_once($dataset["converterPath"].$dataset["converterScript"]);
foreach($updateFiles as $key => $updateFile)
{
// Propagate the global setting to the dataset's settings.
$setup[$datasetName]["osfWebServicesFolder"] = $setup["config"]["osfWebServicesFolder"];
$setup[$datasetName]["ontologiesStructureFiles"] = $setup["config"]["ontologiesStructureFiles"];
$setup[$datasetName]["missingVocabulary"] = $setup["config"]["missingVocabulary"];
$setup[$datasetName]['credentials'] = $setup["credentials"];
// This is needed in case of name collision; Namespaces are only supported in PHP 6
call_user_func($dataset["converterFunctionName"], $updateFile, $dataset, $setup[$datasetName]);
cecho("File updated: $updateFile\n", 'GREEN');
}
}
// save the new hash index file
file_put_contents($hashIndexFile, $hashFile);
}
}
}
if(isset($arguments['n']))
{
// We are creating a new empty dataset
$datasetCreate = new DatasetCreateQuery($arguments['osf-web-services'], $credentials['application-id'], $credentials['api-key'], $credentials['user']);
$datasetCreate->creator((isset($arguments['creator']) ? $arguments['creator'] : ''))
->uri($arguments['uri'])
->description((isset($arguments['description']) ? $arguments['description'] : ''))
->title((isset($arguments['title']) ? $arguments['title'] : ''))
->send((isset($arguments['queryextension']) ? new $arguments['queryextension'] : NULL));
if(!$datasetCreate->isSuccessful())
{
$debugFile = md5(microtime()).'.error';
file_put_contents('/tmp/'.$debugFile, var_export($datasetCreate, TRUE));
@cecho('Can\'t create the new dataset. '. $datasetCreate->getStatusMessage() .
$datasetCreate->getStatusMessageDescription()."\nDebug file: /tmp/$debugFile\n", 'RED');
exit(1);
}
// Create the initial access permissions for the input group
// Get the list of registered web services
$authLister = new AuthListerQuery($arguments['osf-web-services'], $credentials['application-id'], $credentials['api-key'], $credentials['user']);
$authLister->getRegisteredWebServiceEndpointsUri()
->mime('resultset')
->send((isset($arguments['queryextension']) ? new $arguments['queryextension'] : NULL));
if(!$authLister->isSuccessful())
{
$debugFile = md5(microtime()).'.error';
file_put_contents('/tmp/'.$debugFile, var_export($authLister, TRUE));
@cecho('Can\'t get the list of registered web services to create the permissions for: '.$arguments['uri'].'. '. $authLister->getStatusMessage() .
$authLister->getStatusMessageDescription()."\nDebug file: /tmp/$debugFile\n", 'RED');
exit(1);
}
$webservices = array();
$resultset = $authLister->getResultset()->getResultset();
foreach($resultset['unspecified'] as $list)
{
foreach($list['http://www.w3.org/1999/02/22-rdf-syntax-ns#li'] as $ws)
{
$webservices[] = $ws['uri'];
}
}
// Register the credentials
$authRegistrarAccess = new AuthRegistrarAccessQuery($arguments['osf-web-services'], $credentials['application-id'], $credentials['api-key'], $credentials['user']);
$crudPermissions = new CRUDPermission(TRUE, TRUE, TRUE, TRUE);
$authRegistrarAccess->create($arguments['group'], $arguments['uri'], $crudPermissions, $webservices)
->send((isset($arguments['queryextension']) ? new $arguments['queryextension'] : NULL));
if(!$authRegistrarAccess->isSuccessful())
{
$debugFile = md5(microtime()).'.error';
file_put_contents('/tmp/'.$debugFile, var_export($authRegistrarAccess, TRUE));
@cecho('Can\'t create permissions for this new dataset: '.$arguments['uri'].'. '. $authRegistrarAccess->getStatusMessage() .
$authRegistrarAccess->getStatusMessageDescription()."\nDebug file: /tmp/$debugFile\n", 'RED');
exit(1);
}
cecho("Dataset successfully created!\n", 'BLUE');
exit;
}
function readDirectory($path, &$files)
{
$h = opendir($path);
if($h)
{
while ($file = readdir($h))
{
if($file != "." && $file != ".." && strpos($file, "converted") === FALSE)
{
array_push($files, array($path."$file", $file));
}
}
closedir($h);
}
}
?>