forked from Dachande663/Plex-Export
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.php
1369 lines (1109 loc) · 39.5 KB
/
cli.php
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
/*
Plex Export
Luke Lanchester <luke@lukelanchester.com>
Inclues the PHP JavascriptPacker at bottom, all credit to the original authors
A CLI script to export information from your Plex library.
Usage:
php cli.php [-plex-url="http://your-plex-library:32400"] [-data-dir="plex-data"] [-sections=1,2,3 or "Movies,TV Shows"]
*/
$timer_start = microtime(true);
$plex_export_version = 1;
ini_set('memory_limit', '512M');
set_error_handler('plex_error_handler');
error_reporting(E_ALL ^ E_NOTICE | E_WARNING);
// Set-up
plex_log('Welcome to the Plex Exporter v'.$plex_export_version);
$defaults = array(
'plex-url' => 'http://localhost:32400',
'data-dir' => 'plex-data',
'thumbnail-width' => 150,
'thumbnail-height' => 250,
'sections' => 'all',
'sort-skip-words' => 'a,the,der,die,das'
);
$options = hl_parse_arguments($_SERVER['argv'], $defaults);
if(substr($options['plex-url'],-1)!='/') $options['plex-url'] .= '/'; // Always have a trailing slash
$options['absolute-data-dir'] = dirname(__FILE__).'/'.$options['data-dir']; // Run in current dir (PHP CLI defect)
$options['sort-skip-words'] = (array) explode(',', $options['sort-skip-words']); # comma separated list of words to skip for sorting titles
check_dependancies(); // Check everything is enabled as necessary
// Load details about all sections
$all_sections = load_all_sections();
if(!$all_sections) {
plex_error('Could not load section data, aborting');
exit();
}
// If user wants to show all (supported) sections...
if($options['sections'] == 'all') {
$sections = $all_sections;
} else {
// Otherwise, match sections by Title first, then ID
$sections_to_show = array_filter(explode(',',$options['sections']));
$section_titles = array();
foreach($all_sections as $i=>$section) $section_titles[strtolower($section['title'])] = $i;
foreach($sections_to_show as $section_key_or_title) {
$section_title = strtolower(trim($section_key_or_title));
if(array_key_exists($section_title, $section_titles)) {
$section_id = $section_titles[$section_title];
$sections[$section_id] = $all_sections[$section_id];
continue;
}
$section_id = intval($section_key_or_title);
if(array_key_exists($section_id, $all_sections)) {
$sections[$section_id] = $all_sections[$section_id];
continue;
}
plex_error('Could not find section: '.$section_key_or_title);
} // end foreach: $sections_to_show
} // end if: !all sections
// If no sections found (or matched)
$num_sections = count($sections);
if($num_sections==0) {
plex_error('No sections were found to scan');
exit();
}
// Load details about each section
$total_items = 0;
$section_display_order = array();
foreach($sections as $i=>$section) {
plex_log('Scanning section: '.$section['title']);
$items = load_items_for_section($section);
if(!$items) {
plex_error('No items were added for '.$section['title'].', skipping');
$sections[$i]['num_items'] = 0;
$sections[$i]['items'] = array();
continue;
}
$num_items = count($items);
if($section['type']=='show') {
$num_items_episodes = 0;
foreach($items as $item) $num_items_episodes += $item['num_episodes'];
$total_items += $num_items_episodes;
} else {
$total_items += $num_items;
}
plex_log('Analysing media items in section...');
$sorts_title = $sorts_release = $sorts_rating = array();
$raw_section_genres = array();
foreach($items as $key=>$item) {
$title_sort = strtolower($item['title']);
$title_first_space = strpos($title_sort, ' ');
if($title_first_space>0) {
$title_first_word = substr($title_sort, 0, $title_first_space);
if(in_array($title_first_word, $options['sort-skip-words'])) {
$title_sort = substr($title_sort, $title_first_space+1);
}
}
$sorts_title[$key] = $title_sort;
$sorts_release[$key] = @strtotime($item['release_date']);
$sorts_rating[$key] = ($item['user_rating'])?$item['user_rating']:$item['rating'];
if(is_array($item['genre']) and count($item['genre'])>0) {
foreach($item['genre'] as $genre) {
$raw_section_genres[$genre]++;
}
}
} // end foreach: $items (for sorting)
asort($sorts_title, SORT_STRING);
asort($sorts_release, SORT_NUMERIC);
asort($sorts_rating, SORT_NUMERIC);
$sorts['title_asc'] = array_keys($sorts_title);
$sorts['release_asc'] = array_keys($sorts_release);
$sorts['rating_asc'] = array_keys($sorts_rating);
$sorts['title_desc'] = array_reverse($sorts['title_asc']);
$sorts['release_desc'] = array_reverse($sorts['release_asc']);
$sorts['rating_desc'] = array_reverse($sorts['rating_asc']);
$section_genres = array();
if(count($raw_section_genres)>0) {
arsort($raw_section_genres);
foreach($raw_section_genres as $genre=>$genre_count) {
$section_genres[] = array(
'genre' => $genre,
'count' => $genre_count,
);
}
}
$section_display_order[] = $i;
$sections[$i]['num_items'] = $num_items;
$sections[$i]['items'] = $items;
$sections[$i]['sorts'] = $sorts;
$sections[$i]['genres'] = $section_genres;
plex_log('Added '.$num_items.' '.hl_inflect($num_items,'item').' from the '.$section['title'].' section');
} // end foreach: $sections_to_export
// Output all data
plex_log('Exporting data for '.$num_sections.' '.hl_inflect($num_sections,'section').' containing '.$total_items.' '.hl_inflect($total_items,'item'));
$output = array(
'status' => 'success',
'version' => $plex_export_version,
'last_generated' => time()*1000,
'total_items' => $total_items,
'num_sections' => $num_sections,
'section_display_order' => $section_display_order,
'sections' => $sections
);
plex_log('Generating and minifying JSON output, this may take some time...');
$raw_json = json_encode($output);
$raw_js = 'var raw_plex_data = '.$raw_json.';';
//$myPacker = new JavaScriptPacker($raw_js); # See bottom of file for relevant Class
//$packed_js = $myPacker->pack();
$packed_js = $raw_js;
if(!$packed_js) {
plex_error('Could not minify JSON output, aborting.');
exit();
}
$filename = $options['absolute-data-dir'].'/data.js';
$bytes_written = file_put_contents($filename, $packed_js);
if(!$bytes_written) {
plex_error('Could not save JSON data to '.$filename.', please make sure directory is writeable');
exit();
}
plex_log('Wrote '.$bytes_written.' bytes to '.$filename);
$timer_end = microtime(true);
$time_taken = $timer_end - $timer_start;
plex_log('Plex Export completed in '.round($time_taken,2).' seconds');
// Methods //////////////////////////////////////////////////////////////
/**
* Parse a Movie
**/
function load_data_for_movie($el) {
global $options;
$_el = $el->attributes();
$key = intval($_el->ratingKey);
if($key<=0) return false;
$title = strval($_el->title);
plex_log('Scanning movie: '.$title);
$thumb = generate_item_thumbnail(strval($_el->thumb), $key, $title);
$item = array(
'key' => $key,
'type' => 'movie',
'thumb' => $thumb,
'title' => $title,
'duration' => floatval($_el->duration),
'view_count' => intval($_el->viewCount),
'tagline' => ($_el->tagline)?strval($_el->tagline):false,
'rating' => ($_el->rating)?floatval($_el->rating):false,
'user_rating' => ($_el->userRating)?floatval($_el->userRating):false,
'release_year' => ($_el->year)?intval($_el->year):false,
'release_date' => ($_el->originallyAvailableAt)?strval($_el->originallyAvailableAt):false,
'content_rating' => ($_el->contentRating)?strval($_el->contentRating):false,
'summary' => ($_el->summary)?strval($_el->summary):false,
'studio' => ($_el->studio)?strval($_el->studio):false,
'genre' => false,
'director' => false,
'role' => false,
'media' => false,
);
$media_el = $el->Media->attributes();
if(intval($media_el->duration)>0) {
$item['media'] = array(
'bitrate' => ($media_el->bitrate)?intval($media_el->bitrate):false,
'aspect_ratio' => ($media_el->aspectRatio)?floatval($media_el->aspectRatio):false,
'audio_channels' => ($media_el->audioChannels)?intval($media_el->audioChannels):false,
'audio_codec' => ($media_el->audioCodec)?strval($media_el->audioCodec):false,
'video_codec' => ($media_el->videoCodec)?strval($media_el->videoCodec):false,
'video_resolution' => ($media_el->videoResolution)?intval($media_el->videoResolution):false,
'video_framerate' => ($media_el->videoFrameRate)?strval($media_el->videoFrameRate):false,
'total_size' => false
);
$total_size = 0;
foreach($el->Media->Part as $part) {
$total_size += floatval($part->attributes()->size);
}
if($total_size>0) {
$item['media']['total_size'] = $total_size;
}
}
$url = $options['plex-url'].'library/metadata/'.$key;
$xml = load_xml_from_url($url);
if(!$xml) {
plex_error('Could not load additional metadata for '.$title);
return $item;
}
$genres = array();
foreach($xml->Video->Genre as $genre) $genres[] = strval($genre->attributes()->tag);
if(count($genres)>0) $item['genre'] = $genres;
$directors = array();
foreach($xml->Video->Director as $director) $directors[] = strval($director->attributes()->tag);
if(count($directors)>0) $item['director'] = $directors;
$roles = array();
foreach($xml->Video->Role as $role) $roles[] = strval($role->attributes()->tag);
if(count($roles)>0) $item['role'] = $roles;
return $item;
} // end func: load_data_for_movie
/**
* Parse a TV Show
**/
function load_data_for_show($el) {
global $options;
$_el = $el->attributes();
$key = intval($_el->ratingKey);
if($key<=0) return false;
$title = strval($_el->title);
plex_log('Scanning show: '.$title);
$thumb = generate_item_thumbnail(strval($_el->thumb), $key, $title);
$item = array(
'key' => $key,
'type' => 'show',
'thumb' => $thumb,
'title' => $title,
'rating' => ($_el->rating)?floatval($_el->rating):false,
'user_rating' => ($_el->userRating)?floatval($_el->userRating):false,
'release_year' => ($_el->year)?intval($_el->year):false,
'release_date' => ($_el->originallyAvailableAt)?strval($_el->originallyAvailableAt):false,
'duration' => floatval($_el->duration),
'content_rating' => ($_el->contentRating)?strval($_el->contentRating):false,
'summary' => ($_el->summary)?strval($_el->summary):false,
'studio' => ($_el->studio)?strval($_el->studio):false,
'tagline' => false,
'num_episodes' => intval($_el->leafCount),
'num_seasons' => false,
'seasons' => array()
);
$genres = array();
foreach($el->Genre as $genre) $genres[] = strval($genre->attributes()->tag);
if(count($genres)>0) $item['genre'] = $genres;
$url = $options['plex-url'].'library/metadata/'.$key.'/children';
$xml = load_xml_from_url($url);
if(!$xml) {
plex_error('Could not load additional metadata for '.$title);
return $item;
}
$seasons = array();
$season_sort_order = array();
foreach($xml->Directory as $el2) {
if($el2->attributes()->type!='season') continue;
$season_key = intval($el2->attributes()->ratingKey);
$season_sort_order[intval($el2->attributes()->index)] = $season_key;
$season = array(
'key' => $season_key,
'title' => strval($el2->attributes()->title),
'num_episodes' => intval($el2->attributes()->leafCount),
'actual_episodes' => 0,
'episodes' => array(),
'index' => intval($el2->attributes()->index)
);
$url = $options['plex-url'].'library/metadata/'.$season_key.'/children';
$xml2 = load_xml_from_url($url);
if(!$xml2) {
plex_error('Could not load season data for '.$item['title'].' : '.$season['title']);
}
$episode_sort_order = array();
foreach($xml2->Video as $el3) {
if($el3->attributes()->type!='episode') continue;
$episode_key = intval($el3->attributes()->ratingKey);
$episode_sort_order[intval($el3->attributes()->index)] = $episode_key;
$episode = array(
'key' => $episode_key,
'title' => strval($el3->attributes()->title),
'index' => intval($el3->attributes()->index),
'summary' => strval($el3->attributes()->summary),
'rating' => floatval($el3->attributes()->rating),
'duration' => floatval($el3->attributes()->duration),
'view_count' => intval($el3->attributes()->viewCount)
);
$season['episodes'][$episode_key] = $episode;
$season['actual_episodes']++;
}
ksort($episode_sort_order);
$season['episode_sort_order'] = array_values($episode_sort_order);
$seasons[$season_key] = $season;
}
ksort($season_sort_order);
$item['season_sort_order'] = array_values($season_sort_order);
$item['num_seasons'] = count($seasons);
if($item['num_seasons']>0) $item['seasons'] = $seasons;
return $item;
} // end func: load_data_for_show
/**
* Load all supported sections from given Plex API endpoint
**/
function load_all_sections() {
global $options;
$url = $options['plex-url'].'library/sections';
plex_log('Searching for sections in the Plex library at '.$options['plex-url']);
$xml = load_xml_from_url($url);
if(!$xml) return false;
$total_sections = intval($xml->attributes()->size);
if($total_sections<=0) {
plex_error('No sections were found in this Plex library');
return false;
}
$sections = array();
$num_sections = 0;
foreach($xml->Directory as $el) {
$_el = $el->attributes();
$key = intval($_el->key);
$type = strval($_el->type);
$title = strval($_el->title);
if($type=='movie' or $type=='show') {
$sections[$key] = array('key'=>$key, 'type'=>$type, 'title'=>$title);
$num_sections++;
} else {
plex_error('Skipping section of unknown type: '.$type);
}
}
if($num_sections==0) {
plex_error('No valid sections found, aborting');
return false;
}
if($total_sections!=$num_sections) {
plex_log('Found '.$num_sections.' valid '.hl_inflect($num_sections, 'section').' out of a possible '.$total_sections.' '.hl_inflect($total_sections, 'section').' in this Plex library');
} else {
plex_log('Found '.$num_sections.' '.hl_inflect($num_sections, 'section').' in this Plex library');
}
return $sections;
} // end func: load_all_sections
/**
* Load all items present in a section
**/
function load_items_for_section($section) {
global $options;
$url = $options['plex-url'].'library/sections/'.$section['key'].'/all';
$xml = load_xml_from_url($url);
if(!$xml) return false;
$num_items = intval($xml->attributes()->size);
if($num_items<=0) {
plex_error('No items were found in this section, skipping');
return false;
}
switch($section['type']) {
case 'movie':
$object_to_loop = $xml->Video;
$object_parser = 'load_data_for_movie';
break;
case 'show':
$object_to_loop = $xml->Directory;
$object_parser = 'load_data_for_show';
break;
default:
plex_error('Unknown section type provided to parse: '.$section['type']);
return false;
}
plex_log('Found '.$num_items.' '.hl_inflect($num_items,$section['type']).' in '.$section['title']);
$items = array();
foreach($object_to_loop as $el) {
$item = $object_parser($el);
if($item) $items[$item['key']] = $item;
}
return $items;
} // end func: load_items_for_section
/**
* Load URL and parse as XML
**/
function load_xml_from_url($url) {
global $options;
if(!@fopen($url, 'r')) {
plex_error('The Plex library could not be found at '.$options['plex-url']);
return false;
}
$xml = @simplexml_load_file($url);
if(!$xml) {
plex_error('Data could not be read from the Plex server at '.$url);
return false;
}
if(!$xml) {
plex_error('Invalid XML returned by the Plex server, aborting');
return false;
}
return $xml;
} // end func: load_xml_from_url
/**
* Load a thumbnail via Plex API and save
**/
function generate_item_thumbnail($thumb_url, $key, $title) {
global $options;
$filename = '/thumb_'.$key.'.jpeg';
$save_filename = $options['absolute-data-dir'].$filename;
$return_filename = $options['data-dir'].$filename;
if(file_exists($save_filename)) return $return_filename;
if($thumb_url=='') {
plex_error('No thumbnail URL was provided for '.$title, ', skipping');
return false;
}
$source_url = $options['plex-url'].substr($thumb_url,1); # e.g. http://local:32400/library/metadata/123/thumb?=date
$transcode_url = $options['plex-url'].'photo/:/transcode?width='.$options['thumbnail-width'].'&height='.$options['thumbnail-height'].'&url='.urlencode($source_url);
$img_data = @file_get_contents($transcode_url);
if(!$img_data) {
plex_error('Could not load thumbnail for '.$title,' skipping');
return false;
}
$result = @file_put_contents($save_filename, $img_data);
if(!$result) {
plex_error('Could not save thumbnail for '.$title,' skipping');
return false;
}
return $return_filename;
} // end func: generate_item_thumbnail
/**
* Output a message to STDOUT
**/
function plex_log($str) {
$str = @date('H:i:s')." $str\n";
fwrite(STDOUT, $str);
} // end func: plex_log
/**
* Output an error to STDERR
**/
function plex_error($str) {
$str = @date('H:i:s')." Error: $str\n";
fwrite(STDERR, $str);
} // end func: plex_error
/**
* Capture PHP error events
**/
function plex_error_handler($errno, $errstr, $errfile=null, $errline=null) {
if(!(error_reporting() & $errno)) return;
$str = @date('H:i:s')." Error: $errstr". ($errline?' on line '.$errline:'') ."\n";
fwrite(STDERR, $str);
} // end func: plex_error_handler
/**
* Check environment meets dependancies, exit() if not
**/
function check_dependancies() {
global $options;
$errors = false;
if(!extension_loaded('simplexml')) {
plex_error('SimpleXML is not enabled');
$errors = true;
}
if(!ini_get('allow_url_fopen')) {
plex_error('Remote URL access is disabled (allow_url_fopen)');
$errors = true;
}
if(!is_writable($options['absolute-data-dir'])) {
plex_error('Data directory is not writeable at '.$options['absolute-data-dir']);
$errors = true;
}
if($errors) {
plex_error('Failed one or more dependancy checks; aborting');
exit();
}
} // end func: check_dependancies
/**
* Produce output array from merger of inputs and defaults
**/
function hl_parse_arguments($cli_args, $defaults) {
$output = (array) $defaults;
foreach($cli_args as $str) {
if(substr($str,0,1)!='-') continue;
$eq_pos = strpos($str, '=');
$key = substr($str, 1, $eq_pos-1);
if(!array_key_exists($key, $output)) continue;
$output[$key] = substr($str, $eq_pos+1);
}
return $output;
} // end func: hl_parse_arguments
/**
* Return plural form if !=1
**/
function hl_inflect($num, $single, $plural=false) {
if($num==1) return $single;
if($plural) return $plural;
return $single.'s';
} // end func: hl_inflect
/*
* This is the php version of the Dean Edwards JavaScript's Packer,
* Based on :
*
* ParseMaster, version 1.0.2 (2005-08-19) Copyright 2005, Dean Edwards
* a multi-pattern parser.
* KNOWN BUG: erroneous behavior when using escapeChar with a replacement
* value that is a function
*
* packer, version 2.0.2 (2005-08-19) Copyright 2004-2005, Dean Edwards
*
* License: http://creativecommons.org/licenses/LGPL/2.1/
*
* Ported to PHP by Nicolas Martin.
*/
class JavaScriptPacker {
// constants
const IGNORE = '$1';
// validate parameters
private $_script = '';
private $_encoding = 62;
private $_fastDecode = true;
private $_specialChars = false;
private $LITERAL_ENCODING = array(
'None' => 0,
'Numeric' => 10,
'Normal' => 62,
'High ASCII' => 95
);
public function __construct($_script, $_encoding = 62, $_fastDecode = true, $_specialChars = false)
{
$this->_script = $_script . "\n";
if (array_key_exists($_encoding, $this->LITERAL_ENCODING))
$_encoding = $this->LITERAL_ENCODING[$_encoding];
$this->_encoding = min((int)$_encoding, 95);
$this->_fastDecode = $_fastDecode;
$this->_specialChars = $_specialChars;
}
public function pack() {
$this->_addParser('_basicCompression');
if ($this->_specialChars)
$this->_addParser('_encodeSpecialChars');
if ($this->_encoding)
$this->_addParser('_encodeKeywords');
// go!
return $this->_pack($this->_script);
}
// apply all parsing routines
private function _pack($script) {
for ($i = 0; isset($this->_parsers[$i]); $i++) {
$script = call_user_func(array(&$this,$this->_parsers[$i]), $script);
}
return $script;
}
// keep a list of parsing functions, they'll be executed all at once
private $_parsers = array();
private function _addParser($parser) {
$this->_parsers[] = $parser;
}
// zero encoding - just removal of white space and comments
private function _basicCompression($script) {
$parser = new ParseMaster();
// make safe
$parser->escapeChar = '\\';
// protect strings
$parser->add('/\'[^\'\\n\\r]*\'/', self::IGNORE);
$parser->add('/"[^"\\n\\r]*"/', self::IGNORE);
// remove comments
$parser->add('/\\/\\/[^\\n\\r]*[\\n\\r]/', ' ');
$parser->add('/\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\//', ' ');
// protect regular expressions
$parser->add('/\\s+(\\/[^\\/\\n\\r\\*][^\\/\\n\\r]*\\/g?i?)/', '$2'); // IGNORE
$parser->add('/[^\\w\\x24\\/\'"*)\\?:]\\/[^\\/\\n\\r\\*][^\\/\\n\\r]*\\/g?i?/', self::IGNORE);
// remove: ;;; doSomething();
if ($this->_specialChars) $parser->add('/;;;[^\\n\\r]+[\\n\\r]/');
// remove redundant semi-colons
$parser->add('/\\(;;\\)/', self::IGNORE); // protect for (;;) loops
$parser->add('/;+\\s*([};])/', '$2');
// apply the above
$script = $parser->exec($script);
// remove white-space
$parser->add('/(\\b|\\x24)\\s+(\\b|\\x24)/', '$2 $3');
$parser->add('/([+\\-])\\s+([+\\-])/', '$2 $3');
$parser->add('/\\s+/', '');
// done
return $parser->exec($script);
}
private function _encodeSpecialChars($script) {
$parser = new ParseMaster();
// replace: $name -> n, $$name -> na
$parser->add('/((\\x24+)([a-zA-Z$_]+))(\\d*)/',
array('fn' => '_replace_name')
);
// replace: _name -> _0, double-underscore (__name) is ignored
$regexp = '/\\b_[A-Za-z\\d]\\w*/';
// build the word list
$keywords = $this->_analyze($script, $regexp, '_encodePrivate');
// quick ref
$encoded = $keywords['encoded'];
$parser->add($regexp,
array(
'fn' => '_replace_encoded',
'data' => $encoded
)
);
return $parser->exec($script);
}
private function _encodeKeywords($script) {
// escape high-ascii values already in the script (i.e. in strings)
if ($this->_encoding > 62)
$script = $this->_escape95($script);
// create the parser
$parser = new ParseMaster();
$encode = $this->_getEncoder($this->_encoding);
// for high-ascii, don't encode single character low-ascii
$regexp = ($this->_encoding > 62) ? '/\\w\\w+/' : '/\\w+/';
// build the word list
$keywords = $this->_analyze($script, $regexp, $encode);
$encoded = $keywords['encoded'];
// encode
$parser->add($regexp,
array(
'fn' => '_replace_encoded',
'data' => $encoded
)
);
if (empty($script)) return $script;
else {
//$res = $parser->exec($script);
//$res = $this->_bootStrap($res, $keywords);
//return $res;
return $this->_bootStrap($parser->exec($script), $keywords);
}
}
private function _analyze($script, $regexp, $encode) {
// analyse
// retreive all words in the script
$all = array();
preg_match_all($regexp, $script, $all);
$_sorted = array(); // list of words sorted by frequency
$_encoded = array(); // dictionary of word->encoding
$_protected = array(); // instances of "protected" words
$all = $all[0]; // simulate the javascript comportement of global match
if (!empty($all)) {
$unsorted = array(); // same list, not sorted
$protected = array(); // "protected" words (dictionary of word->"word")
$value = array(); // dictionary of charCode->encoding (eg. 256->ff)
$this->_count = array(); // word->count
$i = count($all); $j = 0; //$word = null;
// count the occurrences - used for sorting later
do {
--$i;
$word = '$' . $all[$i];
if (!isset($this->_count[$word])) {
$this->_count[$word] = 0;
$unsorted[$j] = $word;
// make a dictionary of all of the protected words in this script
// these are words that might be mistaken for encoding
//if (is_string($encode) && method_exists($this, $encode))
$values[$j] = call_user_func(array(&$this, $encode), $j);
$protected['$' . $values[$j]] = $j++;
}
// increment the word counter
$this->_count[$word]++;
} while ($i > 0);
// prepare to sort the word list, first we must protect
// words that are also used as codes. we assign them a code
// equivalent to the word itself.
// e.g. if "do" falls within our encoding range
// then we store keywords["do"] = "do";
// this avoids problems when decoding
$i = count($unsorted);
do {
$word = $unsorted[--$i];
if (isset($protected[$word]) /*!= null*/) {
$_sorted[$protected[$word]] = substr($word, 1);
$_protected[$protected[$word]] = true;
$this->_count[$word] = 0;
}
} while ($i);
// sort the words by frequency
// Note: the javascript and php version of sort can be different :
// in php manual, usort :
// " If two members compare as equal,
// their order in the sorted array is undefined."
// so the final packed script is different of the Dean's javascript version
// but equivalent.
// the ECMAscript standard does not guarantee this behaviour,
// and thus not all browsers (e.g. Mozilla versions dating back to at
// least 2003) respect this.
usort($unsorted, array(&$this, '_sortWords'));
$j = 0;
// because there are "protected" words in the list
// we must add the sorted words around them
do {
if (!isset($_sorted[$i]))
$_sorted[$i] = substr($unsorted[$j++], 1);
$_encoded[$_sorted[$i]] = $values[$i];
} while (++$i < count($unsorted));
}
return array(
'sorted' => $_sorted,
'encoded' => $_encoded,
'protected' => $_protected);
}
private $_count = array();
private function _sortWords($match1, $match2) {
return $this->_count[$match2] - $this->_count[$match1];
}
// build the boot function used for loading and decoding
private function _bootStrap($packed, $keywords) {
$ENCODE = $this->_safeRegExp('$encode\\($count\\)');
// $packed: the packed script
$packed = "'" . $this->_escape($packed) . "'";
// $ascii: base for encoding
$ascii = min(count($keywords['sorted']), $this->_encoding);
if ($ascii == 0) $ascii = 1;
// $count: number of words contained in the script
$count = count($keywords['sorted']);
// $keywords: list of words contained in the script
foreach ($keywords['protected'] as $i=>$value) {
$keywords['sorted'][$i] = '';
}
// convert from a string to an array
ksort($keywords['sorted']);
$keywords = "'" . implode('|',$keywords['sorted']) . "'.split('|')";
$encode = ($this->_encoding > 62) ? '_encode95' : $this->_getEncoder($ascii);
$encode = $this->_getJSFunction($encode);
$encode = preg_replace('/_encoding/','$ascii', $encode);
$encode = preg_replace('/arguments\\.callee/','$encode', $encode);
$inline = '\\$count' . ($ascii > 10 ? '.toString(\\$ascii)' : '');
// $decode: code snippet to speed up decoding
if ($this->_fastDecode) {
// create the decoder
$decode = $this->_getJSFunction('_decodeBody');
if ($this->_encoding > 62)
$decode = preg_replace('/\\\\w/', '[\\xa1-\\xff]', $decode);
// perform the encoding inline for lower ascii values
elseif ($ascii < 36)
$decode = preg_replace($ENCODE, $inline, $decode);
// special case: when $count==0 there are no keywords. I want to keep
// the basic shape of the unpacking funcion so i'll frig the code...
if ($count == 0)
$decode = preg_replace($this->_safeRegExp('($count)\\s*=\\s*1'), '$1=0', $decode, 1);
}
// boot function
$unpack = $this->_getJSFunction('_unpack');
if ($this->_fastDecode) {
// insert the decoder
$this->buffer = $decode;
$unpack = preg_replace_callback('/\\{/', array(&$this, '_insertFastDecode'), $unpack, 1);
}
$unpack = preg_replace('/"/', "'", $unpack);
if ($this->_encoding > 62) { // high-ascii
// get rid of the word-boundaries for regexp matches
$unpack = preg_replace('/\'\\\\\\\\b\'\s*\\+|\\+\s*\'\\\\\\\\b\'/', '', $unpack);
}
if ($ascii > 36 || $this->_encoding > 62 || $this->_fastDecode) {
// insert the encode function
$this->buffer = $encode;
$unpack = preg_replace_callback('/\\{/', array(&$this, '_insertFastEncode'), $unpack, 1);
} else {
// perform the encoding inline
$unpack = preg_replace($ENCODE, $inline, $unpack);
}
// pack the boot function too
$unpackPacker = new JavaScriptPacker($unpack, 0, false, true);
$unpack = $unpackPacker->pack();
// arguments
$params = array($packed, $ascii, $count, $keywords);
if ($this->_fastDecode) {
$params[] = 0;
$params[] = '{}';
}
$params = implode(',', $params);
// the whole thing
return 'eval(' . $unpack . '(' . $params . "))\n";
}
private $buffer;
private function _insertFastDecode($match) {
return '{' . $this->buffer . ';';
}
private function _insertFastEncode($match) {
return '{$encode=' . $this->buffer . ';';
}
// mmm.. ..which one do i need ??
private function _getEncoder($ascii) {
return $ascii > 10 ? $ascii > 36 ? $ascii > 62 ?
'_encode95' : '_encode62' : '_encode36' : '_encode10';
}