forked from ronald132/Nanodicom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nanodcm
682 lines (553 loc) · 15.9 KB
/
nanodcm
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
#!/usr/bin/env php
<?php
/**
* nanodcm file
*
* @package Nanodicom
* @category Base
* @author Nano Documet <[email protected]>
* @version 1.3.1
* @copyright (c) 2010-2011
* @license http://www.opensource.org/licenses/mit-license.php MIT-license
*/
/**
* The Command Line interface for Nanodicom.
*
* This cli script helps you run Nanodicom from the command line without the need to create php files.
* WARNING: Tested in Linux only.
*
* Heavily inspired by Goyote's Kohana Installer
* [https://github.com/goyote/kohana-installer]
*
* @package Nanodicom
* @category Cli
* @author Nano Documet <[email protected]>
* @version 1.3.1
* @copyright (c) 2010-2011
* @license http://www.opensource.org/licenses/mit-license.php MIT-license
* @license http://kohanaframework.org/license
*/
class Nanodicom_CLI
{
/**
* Raw CLI arguments and options.
*
* @var array
*/
protected $argv = array();
/**
* Parsed CLI options.
*
* @var array
*/
protected $passed_options = array();
/**
* Found options to be used.
*
* @var array
*/
protected $options = array();
/**
* Class constructor.
*
* @param array $argv
*/
public function __construct(array $argv)
{
$this->argv = $argv;
$this->parse_options();
$this->root_dir = trim(shell_exec('pwd'));
}
/**
* Parses and stores all the valid options from the raw $argv array.
*/
public function parse_options()
{
foreach ($this->argv as $option)
{
if (substr($option, 0, 2) !== '--')
{
continue;
}
$option = ltrim($option, '--');
if (strpos($option, '=') !== FALSE)
{
list($option, $value) = explode('=', $option);
if (strtolower($value) === 'false')
{
$value = FALSE;
}
}
else
{
$value = TRUE;
}
$this->passed_options[strtolower($option)] = $value;
}
}
/**
* Retrieves the value of a passed in CLI option.
*
* e.g. If --name=value was passed in it returns "value".
*
* @param string $name
* @param string $default
* @return string
*/
public function get_option($name, $default = NULL)
{
if ($this->has_option($name))
{
return $this->passed_options[strtolower($name)];
}
return $default;
}
/**
* Checks to see if a option was passed in.
*
* Both --name and --name=value are valid formats, and will return true.
*
* @param string $name
* @return boolean
*/
public function has_option($name)
{
return array_key_exists(strtolower($name), $this->passed_options);
}
/**
* Gets the common options shared by all tools
*/
public function common_options()
{
// Get the path, default to current dir
$path = $this->get_option('path', $this->root_dir);
// Only remove the trailing slash
$path = rtrim($path, '/').'/';
if (strlen($path) AND substr($path, 0, 1) != '/')
{
// Append "root_dir" only when is not an absolute path
$path = $this->root_dir.'/'.$path;
}
// The mask to match
$mask = $this->get_option('mask', '*');
// Do it recursively
$recursive = $this->get_option('recursive', TRUE);
// Show errors?
$errors = $this->get_option('errors', TRUE);
// Show warnings?
$warnings = $this->get_option('warnings', TRUE);
// Show warnings?
$debug = $this->get_option('debug', TRUE);
return array($path, $mask, $recursive, $errors, $warnings, $debug);
}
/**
* Outputs the summary of the matched dicom files
*/
public function execute_summary()
{
// Grab the common options
list($path, $mask, $recursive, $errors, $warnings, $debug) = $this->common_options();
// Get the list of files (with full path)
$files = $this->sdir($path, $mask, $recursive, TRUE);
$return = '';
foreach ($files as $file)
{
$return .= $this->colorize_output("Summary of file: ~\"".$file."\"~\n\n");
// Create a dumper
$dicom = Nanodicom::factory($file);
// Get the summary
$return .= $dicom->summary();
if ($errors)
{
// Record any error if present
$return .= $this->output_messages('errors', $dicom);
}
if ($warnings)
{
// Record any warning if present
$return .= $this->output_messages('warnings', $dicom);
}
// Is a valid DICOM?
$is_dicom = $dicom->is_dicom();
if ($debug)
{
// Show the parsed time
$return .= $this->colorize_output('File parsed in '.$dicom->profiler_diff('parse')." ms\n");
}
// Release memory
unset($dicom);
if ( ! $is_dicom )
{
continue;
}
$return .= $this->colorize_output('File ~'.$file."~ was successfully parsed\n\n");
}
exit($return);
}
/**
* Dumps the matched dicom files
*/
public function execute_dump()
{
// Grab the common options
list($path, $mask, $recursive, $errors, $warnings, $debug) = $this->common_options();
// The mode of output
$output = $this->get_option('out', 'echo');
// Get the list of files (with full path)
$files = $this->sdir($path, $mask, $recursive, TRUE);
$return = '';
foreach ($files as $file)
{
$return .= $this->colorize_output("Dumping file: ~\"".$file."\"~\n\n");
// Create a dumper
$dicom = Nanodicom::factory($file, 'dumper');
// Perform the dump
$return .= $dicom->dump($output);
if ($errors)
{
// Record any error if present
$return .= $this->output_messages('errors', $dicom);
}
if ($warnings)
{
// Record any warning if present
$return .= $this->output_messages('warnings', $dicom);
}
// Is a valid DICOM?
$is_dicom = $dicom->is_dicom();
if ($debug)
{
// Show the parsed time
$return .= $this->colorize_output('File parsed in '.$dicom->profiler_diff('parse')." ms\n");
// Show the dumping time
$return .= $this->colorize_output('File dumped in '.$dicom->profiler_diff('dump')." ms\n");
}
// Release memory
unset($dicom);
if ( ! $is_dicom )
{
continue;
}
$return .= $this->colorize_output('File ~'.$file."~ was successfully dumped\n\n");
}
exit($return);
}
/**
* Anonymizes the matched dicom files
*/
public function execute_anonymize()
{
// Grab the common options
list($path, $mask, $recursive, $errors, $warnings, $debug) = $this->common_options();
// Overwrite?
$overwride = $this->get_option('overwrite', FALSE);
// Any tags?
$tags = $this->get_option('tags', NULL);
$tags = ($tags !== NULL) ? json_decode($tags) : $tags;
// Any mapping?
$map = $this->get_option('map', NULL);
$map = ($map !== NULL) ? json_decode($map) : $map;
// Get the list of files (with full path)
$files = $this->sdir($path, $mask, $recursive, TRUE);
$return = '';
foreach ($files as $file)
{
$return .= $this->colorize_output("Anonymizing file: ~\"".$file."\"~\n\n");
// Create an anonymizer
$dicom = Nanodicom::factory($file, 'anonymizer');
// Perform the dump
$blob = $dicom->anonymize($tags, $map);
if ($errors)
{
// Record any error if present
$return .= $this->output_messages('errors', $dicom);
}
if ($warnings)
{
// Record any warning if present
$return .= $this->output_messages('warnings', $dicom);
}
// Is a valid DICOM?
$is_dicom = $dicom->is_dicom();
if ($debug)
{
// Show the parsed time
$return .= $this->colorize_output('File parsed in '.$dicom->profiler_diff('parse')." ms\n");
// Show the anonymizing time
$return .= $this->colorize_output('File dumped in '.$dicom->profiler_diff('anonymize')." ms\n");
}
// Release memory
unset($dicom);
if ( ! $is_dicom )
{
continue;
}
if ( ! $overwride)
{
// Get new backup file name
$new_file = $this->get_backup_file($file);
// Move original file to backup file
rename($file, $new_file);
}
// Save anonymized file into original name
file_put_contents($file, $blob);
$return .= $this->colorize_output('File ~'.$file."~ was successfully anonymized\n\n");
}
exit($return);
}
/**
* Function to grab the messages (if exist) from last operation in DICOM object
*
* @param string $type The type of message to output (errors or warnings)
* @param object $dicom Nanodicom object
*/
public function output_messages($type = 'errors', $dicom)
{
$return = '';
if ($dicom->status != Nanodicom::SUCCESS)
{
foreach ($dicom->{$type} as $message)
{
$label = substr(strtoupper($type), 0, -1);
$return .= $this->colorize_output('!'.$label.': '.$message.'!')."\n";
}
}
return $return;
}
/**
* Function to get a unique name for the backup file
*
* @param string $file the file to which we will create the backup
*/
public function get_backup_file($file)
{
$count = 1;
while (file_exists($file.'.bak'.$count))
{
$count++;
}
return $file.'.bak'.$count;
}
/**
* Function to get the files of a given directory. Based on original
* function written by [phpnet at novaclic dot com]
* (http://www.php.net/manual/en/function.scandir.php#95588)
*
*
* @param string $path the path to scan
* @param string $mask the mask used to match the files
* @param boolean $recursive whether to iterate subfolders or not
* @param boolean $no_cache whether to cache the results
*/
public function sdir($path = '.', $mask = '*', $recursive = FALSE, $no_cache = FALSE)
{
static $dir = array(); // cache result in memory
if ( ! is_dir($path))
{
exit($this->colorize_output("Path ~\"{$path}\"~ does not exist!\n\n"));
}
if ( ! isset($dir[$path]) OR $no_cache)
{
$dir[$path] = scandir($path);
}
$sdir = array();
foreach ($dir[$path] as $i => $entry)
{
if ($entry == '.' OR $entry == '..')
continue;
if (is_dir($path.$entry) AND $recursive)
{
$files = $this->sdir($path.$entry.'/', $mask, $recursive, $no_cache);
$sdir += $files;
}
if (is_file($path.$entry) AND fnmatch($mask, $entry))
{
$sdir[] = $path.$entry;
}
}
return $sdir;
}
/**
* Shows the list of available commands.
*/
public function execute_help()
{
if ($this->has_option('verbose'))
{
$this->show_verbose_help_screen();
}
else
{
$this->show_help_screen();
}
}
/**
* Creates a directory or series of directories.
*
* Any directory that currently doesn't exist will be created. Upon completion it will fix the
* permissions so that it's writable by everyone (appropriate for development,) the mode can
* be overridden.
*
* @param string $dir
* @param string $mode
*/
public function mkdir($dir, $mode = NULL)
{
system(sprintf('mkdir -p %s', escapeshellarg($dir)));
$this->fix_permissions($dir, $mode);
}
/**
* Changes the permissions of a directory.
*
* Note: this function is recursive, so all of the folders and files underneath the target
* directory will also receive the same permissions. The default behaviour is to 777 the whole
* thing, makes it easier to develop locally.
*
* @param string $dir
* @param string $mode
*/
public function fix_permissions($dir, $mode = NULL)
{
if ( ! $mode)
{
// Default the mode to rxw by everyone
$mode = '0777';
}
system(sprintf('chmod -R %s %s', escapeshellarg($mode), escapeshellarg($dir)));
}
/**
* Builds the desired path directory structure, fixing the permissions on all new directories.
*
* @param string $dir
* @param string $mode
* @return string
*/
public function build_path_dir($dir = NULL, $mode = NULL)
{
$dir = trim($dir, '/');
if ( ! $dir)
{
return $this->root_dir;
}
$dirs = explode('/', $dir);
do
{
$folder = array_shift($dirs);
$folder = substr($dir, 0, strpos($dir, $folder) + strlen($folder));
if ( ! is_dir($this->root_dir.'/'.$folder))
{
$this->mkdir($this->root_dir.'/'.$dir, $mode);
$this->fix_permissions($this->root_dir.'/'.$folder, $mode);
break;
}
}
while (count($dirs));
return $this->root_dir.'/'.$dir;
}
/**
* Displays the full help screen; contains the list of available commands.
*/
public function show_verbose_help_screen()
{
exit($this->colorize_output(<<<EOF
*********************************************
* Nanodicom Command Line helper *
*********************************************
** Specify a command to run **
!All options are optional, if not set, default values will be used!
~$ nanodcm [command] --[option1]=[value] --[option2]=[value] ...~
common options
~$ --path=my/dir~ <- Path to search. Absolute or relative.
~Default:~ Current directory
~$ --mask=*.dcm~ <- Mask to match the filenames
~Default:~ Any file "*"
~$ --recursive=false~ <- To avoid searching in subfolders.
~Default:~ Do it recursively
~$ --errors=true~ <- Output errors found
~Default:~ true.
~$ --warnings=true~ <- Output warnings found
~Default:~ true.
~$ --debug=true~ <- Shows debug messages. Mostly profiling values, currently
only 'parsing' time, 'dumping' time and 'anonymizing' time.
~Default:~ true.
> summary: Outputs the summary of the DICOM files found
~$ nanodcm summary --[option1]=[value] --[option2]=[value] ...~
~no extra options~
> dumper: Dumps the DICOM files found
~$ nanodcm dump --[option1]=[value] --[option2]=[value] ...~
options
~$ --out=html~ <- Output mode. Available by distribution: html or echo
~Default:~ "echo" mode.
> anonymizer: Anonymizes the matched files
~$ nanodcm anonymize --[option1]=[value] --[option2]=[value] ...~
options
~$ --overwrite=true~ <- Anonymizes and overwrites all files found.
~Default:~ false. Creates a backup.
~$ --map={json_string}~ <- Adds a mapping capability in json format.
~Default:~ empty. Uses default from anonymizer tool.
~$ --tags={json_string}~ <- Adds a mapping capability in json format.
~Default:~ empty. Uses default from anonymizer tool.
EOF
));
}
/**
* Displays the minimal help screen; contains the list of available commands.
*/
public function show_help_screen()
{
exit($this->colorize_output(<<<EOF
*********************************************
* Nanodicom Command Line helper *
*********************************************
[!] For quick snippets, try "nanodcm --verbose"
** Specify a command to run **
~summary~ Outputs the summaries of the DICOM files matched
~dump~ Dumps the files matched with the given pattern
~anonymize~ Anonymizes the files matched
~pixel~ Creates images out of the files matched [SOON!]
EOF
));
}
/**
* Colorizes the output so it's more legible.
*
* @param string $output
* @return string
*/
public function colorize_output($output)
{
// Color green for highlights
preg_match_all('/~(.*?)~/', $output, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
{
$output = str_replace($match[0], "\033[0;32m".$match[1]."\033[0m", $output);
}
// Color red for Errors!
preg_match_all('/!(.*?)!/', $output, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
{
$output = str_replace($match[0], "\033[0;31m".$match[1]."\033[0m", $output);
}
return $output;
}
}
class Nanodcm extends Nanodicom_Cli
{
}
set_time_limit(0);
// First index is the name of this script
array_shift($argv);
$helper = new Nanodcm($argv);
if (empty($argv) OR $helper->has_option('verbose'))
{
$helper->execute_help();
}
else if (method_exists($helper, $method = 'execute_'.strtolower(str_replace('-', '_', $argv[0]))))
{
require_once 'nanodicom.php';
call_user_func(array($helper, $method));
}
else if ( ! empty($argv[0]))
{
exit("\"{$argv[0]}\" is not a valid command!\n\n");
}