-
Notifications
You must be signed in to change notification settings - Fork 5
/
CFPropertyList.php
2606 lines (2250 loc) · 81.1 KB
/
CFPropertyList.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
/**
* CFPropertyList
* {@link http://developer.apple.com/documentation/Darwin/Reference/ManPages/man5/plist.5.html Property Lists}
* @author Rodney Rehm <rodney.rehm@medialize.de>
* @author Christian Kruse <cjk@wwwtech.de>
* @package plist
* @version $Id$
* @example example-read-01.php Read an XML PropertyList
* @example example-read-02.php Read a Binary PropertyList
* @example example-read-03.php Read a PropertyList without knowing the type
* @example example-create-01.php Using the CFPropertyList API
* @example example-create-02.php Using {@link CFTypeDetector}
* @example example-create-03.php Using {@link CFTypeDetector} with {@link CFDate} and {@link CFData}
* @example example-modify-01.php Read, modify and save a PropertyList
*/
/**
* Property List
* Interface for handling reading, editing and saving Property Lists as defined by Apple.
* @author Rodney Rehm <rodney.rehm@medialize.de>
* @author Christian Kruse <cjk@wwwtech.de>
* @package plist
* @example example-read-01.php Read an XML PropertyList
* @example example-read-02.php Read a Binary PropertyList
* @example example-read-03.php Read a PropertyList without knowing the type
* @example example-create-01.php Using the CFPropertyList API
* @example example-create-02.php Using {@link CFTypeDetector}
* @example example-create-03.php Using {@link CFTypeDetector} with {@link CFDate} and {@link CFData}
* @example example-create-04.php Using and extended {@link CFTypeDetector}
*/
class CFPropertyList extends CFBinaryPropertyList implements Iterator {
/**
* Format constant for binary format
* @var integer
*/
const FORMAT_BINARY = 1;
/**
* Format constant for xml format
* @var integer
*/
const FORMAT_XML = 2;
/**
* Format constant for automatic format recognizing
* @var integer
*/
const FORMAT_AUTO = 0;
/**
* Path of PropertyList
* @var string
*/
protected $file = null;
/**
* Path of PropertyList
* @var integer
*/
protected $format = null;
/**
* CFType nodes
* @var array
*/
protected $value = array();
/**
* Position of iterator {@link http://php.net/manual/en/class.iterator.php}
* @var integer
*/
protected $iteratorPosition = 0;
/**
* List of Keys for numerical iterator access {@link http://php.net/manual/en/class.iterator.php}
* @var array
*/
protected $iteratorKeys = null;
/**
* List of NodeNames to ClassNames for resolving plist-files
* @var array
*/
protected static $types = array(
'string' => 'CFString',
'real' => 'CFNumber',
'integer' => 'CFNumber',
'date' => 'CFDate',
'true' => 'CFBoolean',
'false' => 'CFBoolean',
'data' => 'CFData',
'array' => 'CFArray',
'dict' => 'CFDictionary'
);
/**
* Create new CFPropertyList.
* If a path to a PropertyList is specified, it is loaded automatically.
* @param string $file Path of PropertyList
* @param integer $format he format of the property list, see {@link FORMAT_XML}, {@link FORMAT_BINARY} and {@link FORMAT_AUTO}, defaults to {@link FORMAT_AUTO}
* @throws IOException if file could not be read by {@link load()}
* @uses $file for storing the current file, if specified
* @uses load() for loading the plist-file
*/
public function __construct($file=null,$format=self::FORMAT_AUTO) {
$this->file = $file;
$this->format = $format;
if($this->file) $this->load();
}
/**
* Load an XML PropertyList.
* @param string $file Path of PropertyList, defaults to {@link $file}
* @return void
* @throws IOException if file could not be read
* @throws DOMException if XML-file could not be read properly
* @uses load() to actually load the file
*/
public function loadXML($file=null) {
$this->load($file,CFPropertyList::FORMAT_XML);
}
/**
* Load an XML PropertyList.
* @param resource $stream A stream containing the xml document.
* @return void
* @throws IOException if stream could not be read
* @throws DOMException if XML-stream could not be read properly
*/
public function loadXMLStream($stream) {
if(($contents = stream_get_contents($stream)) === FALSE) throw IOException::notReadable('<stream>');
$this->parse($contents,CFPropertyList::FORMAT_XML);
}
/**
* Load an binary PropertyList.
* @param string $file Path of PropertyList, defaults to {@link $file}
* @return void
* @throws IOException if file could not be read
* @throws PListException if binary plist-file could not be read properly
* @uses load() to actually load the file
*/
public function loadBinary($file=null) {
$this->load($file,CFPropertyList::FORMAT_BINARY);
}
/**
* Load an binary PropertyList.
* @param stream $stream Stream containing the PropertyList
* @return void
* @throws IOException if file could not be read
* @throws PListException if binary plist-file could not be read properly
* @uses parse() to actually load the file
*/
public function loadBinaryStream($stream) {
if(($contents = stream_get_contents($stream)) === FALSE) throw IOException::notReadable('<stream>');
$this->parse($contents,CFPropertyList::FORMAT_BINARY);
}
/**
* Load a plist file.
* Load and import a plist file.
* @param string $file Path of PropertyList, defaults to {@link $file}
* @param integer $format The format of the property list, see {@link FORMAT_XML}, {@link FORMAT_BINARY} and {@link FORMAT_AUTO}, defaults to {@link $format}
* @return void
* @throws PListException if file format version is not 00
* @throws IOException if file could not be read
* @throws DOMException if plist file could not be parsed properly
* @uses $file if argument $file was not specified
* @uses $value reset to empty array
* @uses import() for importing the values
*/
public function load($file=null,$format=null) {
$file = $file ? $file : $this->file;
$format = $format !== null ? $format : $this->format;
$this->value = array();
if(!is_readable($file)) throw IOException::notReadable($file);
switch($format) {
case CFPropertyList::FORMAT_BINARY:
$this->readBinary($file);
break;
case CFPropertyList::FORMAT_AUTO: // what we now do is ugly, but neccessary to recognize the file format
$fd = fopen($file,"rb");
if(($magic_number = fread($fd,8)) === false) throw IOException::notReadable($file);
fclose($fd);
$filetype = substr($magic_number,0,6);
$version = substr($magic_number,-2);
if($filetype == "bplist") {
if($version != "00") throw new PListException("Wrong file format version! Expected 00, got $version!");
$this->readBinary($file);
break;
}
// else: xml format, break not neccessary
case CFPropertyList::FORMAT_XML:
$doc = new DOMDocument();
if(!$doc->load($file)) throw new DOMException();
$this->import($doc->documentElement, $this);
break;
}
}
/**
* Parse a plist string.
* Parse and import a plist string.
* @param string $str String containing the PropertyList, defaults to {@link $content}
* @param integer $format The format of the property list, see {@link FORMAT_XML}, {@link FORMAT_BINARY} and {@link FORMAT_AUTO}, defaults to {@link $format}
* @return void
* @throws PListException if file format version is not 00
* @throws IOException if file could not be read
* @throws DOMException if plist file could not be parsed properly
* @uses $content if argument $str was not specified
* @uses $value reset to empty array
* @uses import() for importing the values
*/
public function parse($str=NULL,$format=NULL) {
$format = $format !== null ? $format : $this->format;
$str = $str !== null ? $str : $this->content;
$this->value = array();
switch($format) {
case CFPropertyList::FORMAT_BINARY:
$this->parseBinary($str);
break;
case CFPropertyList::FORMAT_AUTO: // what we now do is ugly, but neccessary to recognize the file format
if(($magic_number = substr($str,0,8)) === false) throw IOException::notReadable("<string>");
$filetype = substr($magic_number,0,6);
$version = substr($magic_number,-2);
if($filetype == "bplist") {
if($version != "00") throw new PListException("Wrong file format version! Expected 00, got $version!");
$this->parseBinary($str);
break;
}
// else: xml format, break not neccessary
case CFPropertyList::FORMAT_XML:
$doc = new DOMDocument();
if(!$doc->loadXML($str)) throw new DOMException();
$this->import($doc->documentElement, $this);
break;
}
}
/**
* Convert a DOMNode into a CFType.
* @param DOMNode $node Node to import children of
* @param CFDictionary|CFArray|CFPropertyList $parent
* @return void
*/
protected function import(DOMNode $node, $parent) {
// abort if there are no children
if(!$node->childNodes->length) return;
foreach($node->childNodes as $n) {
// skip if we can't handle the element
if(!isset(self::$types[$n->nodeName])) continue;
$class = 'CFPropertyList\\'.self::$types[$n->nodeName];
$key = null;
// find previous <key> if possible
$ps = $n->previousSibling;
while($ps && $ps->nodeName == '#text' && $ps->previousSibling) $ps = $ps->previousSibling;
// read <key> if possible
if($ps && $ps->nodeName == 'key') $key = $ps->firstChild->nodeValue;
switch($n->nodeName) {
case 'date':
$value = new $class(CFDate::dateValue($n->nodeValue));
break;
case 'data':
$value = new $class($n->nodeValue,true);
break;
case 'string':
$value = new $class($n->nodeValue);
break;
case 'real':
case 'integer':
$value = new $class($n->nodeName == 'real' ? floatval($n->nodeValue) : intval($n->nodeValue));
break;
case 'true':
case 'false':
$value = new $class($n->nodeName == 'true');
break;
case 'array':
case 'dict':
$value = new $class();
$this->import($n, $value);
break;
}
// Dictionaries need a key
if($parent instanceof CFDictionary) $parent->add($key, $value);
// others don't
else $parent->add($value);
}
}
/**
* Convert CFPropertyList to XML and save to file.
* @param string $file Path of PropertyList, defaults to {@link $file}
* @return void
* @throws IOException if file could not be read
* @uses $file if $file was not specified
*/
public function saveXML($file) {
$this->save($file,CFPropertyList::FORMAT_XML);
}
/**
* Convert CFPropertyList to binary format (bplist00) and save to file.
* @param string $file Path of PropertyList, defaults to {@link $file}
* @return void
* @throws IOException if file could not be read
* @uses $file if $file was not specified
*/
public function saveBinary($file) {
$this->save($file,CFPropertyList::FORMAT_BINARY);
}
/**
* Convert CFPropertyList to XML or binary and save to file.
* @param string $file Path of PropertyList, defaults to {@link $file}
* @param string $format Format of PropertyList, defaults to {@link $format}
* @return void
* @throws IOException if file could not be read
* @throws PListException if evaluated $format is neither {@link FORMAT_XML} nor {@link FORMAL_BINARY}
* @uses $file if $file was not specified
* @uses $format if $format was not specified
*/
public function save($file=null,$format=null) {
$file = $file ? $file : $this->file;
$format = $format ? $format : $this->format;
if( !in_array( $format, array( self::FORMAT_BINARY, self::FORMAT_XML ) ) )
throw new PListException( "format {$format} is not supported, use CFPropertyList::FORMAT_BINARY or CFPropertyList::FORMAT_XML" );
if(!file_exists($file)) {
// dirname("file.xml") == "" and is treated as the current working directory
if(!is_writable(dirname($file))) throw IOException::notWritable($file);
}
else if(!is_writable($file)) throw IOException::notWritable($file);
$content = $format == self::FORMAT_BINARY ? $this->toBinary() : $this->toXML();
$fh = fopen($file, 'wb');
fwrite($fh,$content);
fclose($fh);
}
/**
* Convert CFPropertyList to XML
* @param bool $formatted Print plist formatted (i.e. with newlines and whitespace indention) if true; defaults to false
* @return string The XML content
*/
public function toXML($formatted=false) {
$domimpl = new DOMImplementation();
// <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
$dtd = $domimpl->createDocumentType('plist', '-//Apple Computer//DTD PLIST 1.0//EN', 'http://www.apple.com/DTDs/PropertyList-1.0.dtd');
$doc = $domimpl->createDocument(null, "plist", $dtd);
$doc->encoding = "UTF-8";
// format output
if($formatted) {
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
}
// get documentElement and set attribs
$plist = $doc->documentElement;
$plist->setAttribute('version', '1.0');
// add PropertyList's children
$plist->appendChild($this->getValue(true)->toXML($doc));
return $doc->saveXML();
}
/************************************************************************************************
* M A N I P U L A T I O N
************************************************************************************************/
/**
* Add CFType to collection.
* @param CFType $value CFType to add to collection
* @return void
* @uses $value for adding $value
*/
public function add(CFType $value=null) {
// anything but CFType is null, null is an empty string - sad but true
if( !$value )
$value = new CFString();
$this->value[] = $value;
}
/**
* Get CFType from collection.
* @param integer $key Key of CFType to retrieve from collection
* @return CFType CFType found at $key, null else
* @uses $value for retrieving CFType of $key
*/
public function get($key) {
if(isset($this->value[$key])) return $this->value[$key];
return null;
}
/**
* Generic getter (magic)
*
* @param integer $key Key of CFType to retrieve from collection
* @return CFType CFType found at $key, null else
* @author Sean Coates <sean@php.net>
* @link http://php.net/oop5.overloading
*/
public function __get($key) {
return $this->get($key);
}
/**
* Remove CFType from collection.
* @param integer $key Key of CFType to removes from collection
* @return CFType removed CFType, null else
* @uses $value for removing CFType of $key
*/
public function del($key) {
if(isset($this->value[$key])) {
$t = $this->value[$key];
unset($this->value[$key]);
return $t;
}
return null;
}
/**
* Empty the collection
* @return array the removed CFTypes
* @uses $value for removing CFType of $key
*/
public function purge() {
$t = $this->value;
$this->value = array();
return $t;
}
/**
* Get first (and only) child, or complete collection.
* @param string $cftype if set to true returned value will be CFArray instead of an array in case of a collection
* @return CFType|array CFType or list of CFTypes known to the PropertyList
* @uses $value for retrieving CFTypes
*/
public function getValue($cftype=false) {
if(count($this->value) === 1) {
$t = array_values( $this->value );
return $t[0];
}
if($cftype) {
$t = new CFArray();
foreach( $this->value as $value ) {
if( $value instanceof CFType ) $t->add($value);
}
return $t;
}
return $this->value;
}
/**
* Create CFType-structure from guessing the data-types.
* The functionality has been moved to the more flexible {@link CFTypeDetector} facility.
* @param mixed $value Value to convert to CFType
* @param array $options Configuration for casting values [autoDictionary, suppressExceptions, objectToArrayMethod, castNumericStrings]
* @return CFType CFType based on guessed type
* @uses CFTypeDetector for actual type detection
* @deprecated
*/
public static function guess($value, $options=array()) {
static $t = null;
if( $t === null )
$t = new CFTypeDetector( $options );
return $t->toCFType( $value );
}
/************************************************************************************************
* S E R I A L I Z I N G
************************************************************************************************/
/**
* Get PropertyList as array.
* @return mixed primitive value of first (and only) CFType, or array of primitive values of collection
* @uses $value for retrieving CFTypes
*/
public function toArray() {
$a = array();
foreach($this->value as $value) $a[] = $value->toArray();
if(count($a) === 1) return $a[0];
return $a;
}
/************************************************************************************************
* I T E R A T O R I N T E R F A C E
************************************************************************************************/
/**
* Rewind {@link $iteratorPosition} to first position (being 0)
* @link http://php.net/manual/en/iterator.rewind.php
* @return void
* @uses $iteratorPosition set to 0
* @uses $iteratorKeys store keys of {@link $value}
*/
public function rewind() {
$this->iteratorPosition = 0;
$this->iteratorKeys = array_keys($this->value);
}
/**
* Get Iterator's current {@link CFType} identified by {@link $iteratorPosition}
* @link http://php.net/manual/en/iterator.current.php
* @return CFType current Item
* @uses $iteratorPosition identify current key
* @uses $iteratorKeys identify current value
*/
public function current() {
return $this->value[$this->iteratorKeys[$this->iteratorPosition]];
}
/**
* Get Iterator's current key identified by {@link $iteratorPosition}
* @link http://php.net/manual/en/iterator.key.php
* @return string key of the current Item
* @uses $iteratorPosition identify current key
* @uses $iteratorKeys identify current value
*/
public function key() {
return $this->iteratorKeys[$this->iteratorPosition];
}
/**
* Increment {@link $iteratorPosition} to address next {@see CFType}
* @link http://php.net/manual/en/iterator.next.php
* @return void
* @uses $iteratorPosition increment by 1
*/
public function next() {
$this->iteratorPosition++;
}
/**
* Test if {@link $iteratorPosition} addresses a valid element of {@link $value}
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean true if current position is valid, false else
* @uses $iteratorPosition test if within {@link $iteratorKeys}
* @uses $iteratorPosition test if within {@link $value}
*/
public function valid() {
return isset($this->iteratorKeys[$this->iteratorPosition]) && isset($this->value[$this->iteratorKeys[$this->iteratorPosition]]);
}
}
/**
* CFPropertyList
* {@link http://developer.apple.com/documentation/Darwin/Reference/ManPages/man5/plist.5.html Property Lists}
* @author Rodney Rehm <rodney.rehm@medialize.de>
* @author Christian Kruse <cjk@wwwtech.de>
* @package plist
* @version $Id$
*/
/**
* Facility for reading and writing binary PropertyLists. Ported from {@link http://www.opensource.apple.com/source/CF/CF-476.15/CFBinaryPList.c CFBinaryPList.c}.
* @author Rodney Rehm <rodney.rehm@medialize.de>
* @author Christian Kruse <cjk@wwwtech.de>
* @package plist
* @example example-read-02.php Read a Binary PropertyList
* @example example-read-03.php Read a PropertyList without knowing the type
*/
abstract class CFBinaryPropertyList {
/**
* Content of the plist (unparsed string)
* @var string
*/
protected $content = NULL;
/**
* position in the (unparsed) string
* @var integer
*/
protected $pos = 0;
/**
* Table containing uniqued objects
* @var array
*/
protected $uniqueTable = Array();
/**
* Number of objects in file
* @var integer
*/
protected $countObjects = 0;
/**
* The length of all strings in the file (byte length, not character length)
* @var integer
*/
protected $stringSize = 0;
/**
* The length of all ints in file (byte length)
* @var integer
*/
protected $intSize = 0;
/**
* The length of misc objects (i.e. not integer and not string) in file
* @var integer
*/
protected $miscSize = 0;
/**
* Number of object references in file (needed to calculate reference byte length)
* @var integer
*/
protected $objectRefs = 0;
/**
* Number of objects written during save phase; needed to calculate the size of the object table
* @var integer
*/
protected $writtenObjectCount = 0;
/**
* Table containing all objects in the file
*/
protected $objectTable = Array();
/**
* The size of object references
*/
protected $objectRefSize = 0;
/**
* The „offsets” (i.e. the different entries) in the file
*/
protected $offsets = Array();
/**
* Read a „null type” (filler byte, true, false, 0 byte)
* @param $length The byte itself
* @return the byte value (e.g. CFBoolean(true), CFBoolean(false), 0 or 15)
* @throws PListException on encountering an unknown null type
*/
protected function readBinaryNullType($length) {
switch($length) {
case 0: return 0; // null type
case 8: return new CFBoolean(false);
case 9: return new CFBoolean(true);
case 15: return 15; // fill type
}
throw new PListException("unknown null type: $length");
}
/**
* Create an 64 bit integer using bcmath or gmp
* @param int $hi The higher word
* @param int $lo The lower word
* @return mixed The integer (as int if possible, as string if not possible)
* @throws PListException if neither gmp nor bc available
*/
protected static function make64Int($hi,$lo) {
// on x64, we can just use int
if(PHP_INT_SIZE > 4) return (((int)$hi)<<32) | ((int)$lo);
// lower word has to be unsigned since we don't use bitwise or, we use bcadd/gmp_add
$lo = sprintf("%u", $lo);
// use GMP or bcmath if possible
if(function_exists("gmp_mul")) return gmp_strval(gmp_add(gmp_mul($hi, "4294967296"), $lo));
if(function_exists("bcmul")) return bcadd(bcmul($hi,"4294967296"), $lo);
if(class_exists('Math_BigInteger')) {
$bi = new \Math_BigInteger($hi);
return $bi->multiply(new \Math_BigInteger("4294967296"))->add(new \Math_BigInteger($lo))->toString();
}
throw new PListException("either gmp or bc has to be installed, or the Math_BigInteger has to be available!");
}
/**
* Read an integer value
* @param integer $length The length (in bytes) of the integer value, coded as „set bit $length to 1”
* @return CFNumber The integer value
* @throws PListException if integer val is invalid
* @throws IOException if read error occurs
* @uses make64Int() to overcome PHP's big integer problems
*/
protected function readBinaryInt($length) {
if($length > 3) throw new PListException("Integer greater than 8 bytes: $length");
$nbytes = 1 << $length;
$val = null;
if(strlen($buff = substr($this->content, $this->pos, $nbytes)) != $nbytes) throw IOException::readError("");
$this->pos += $nbytes;
switch($length) {
case 0:
$val = unpack("C", $buff);
$val = $val[1];
break;
case 1:
$val = unpack("n", $buff);
$val = $val[1];
break;
case 2:
$val = unpack("N", $buff);
$val = $val[1];
break;
case 3:
$words = unpack("Nhighword/Nlowword",$buff);
//$val = $words['highword'] << 32 | $words['lowword'];
$val = self::make64Int($words['highword'],$words['lowword']);
break;
}
return new CFNumber($val);
}
/**
* Read a real value
* @param integer $length The length (in bytes) of the integer value, coded as „set bit $length to 1”
* @return CFNumber The real value
* @throws PListException if real val is invalid
* @throws IOException if read error occurs
*/
protected function readBinaryReal($length) {
if($length > 3) throw new PListException("Real greater than 8 bytes: $length");
$nbytes = 1 << $length;
$val = null;
if(strlen($buff = substr($this->content,$this->pos, $nbytes)) != $nbytes) throw IOException::readError("");
$this->pos += $nbytes;
switch($length) {
case 0: // 1 byte float? must be an error
case 1: // 2 byte float? must be an error
$x = $length + 1;
throw new PListException("got {$x} byte float, must be an error!");
case 2:
$val = unpack("f", strrev($buff));
$val = $val[1];
break;
case 3:
$val = unpack("d", strrev($buff));
$val = $val[1];
break;
}
return new CFNumber($val);
}
/**
* Read a date value
* @param integer $length The length (in bytes) of the integer value, coded as „set bit $length to 1”
* @return CFDate The date value
* @throws PListException if date val is invalid
* @throws IOException if read error occurs
*/
protected function readBinaryDate($length) {
if($length > 3) throw new PListException("Date greater than 8 bytes: $length");
$nbytes = 1 << $length;
$val = null;
if(strlen($buff = substr($this->content, $this->pos, $nbytes)) != $nbytes) throw IOException::readError("");
$this->pos += $nbytes;
switch($length) {
case 0: // 1 byte CFDate is an error
case 1: // 2 byte CFDate is an error
$x = $length + 1;
throw new PListException("{$x} byte CFdate, error");
case 2:
$val = unpack("f", strrev($buff));
$val = $val[1];
break;
case 3:
$val = unpack("d", strrev($buff));
$val = $val[1];
break;
}
return new CFDate($val,CFDate::TIMESTAMP_APPLE);
}
/**
* Read a data value
* @param integer $length The length (in bytes) of the integer value, coded as „set bit $length to 1”
* @return CFData The data value
* @throws IOException if read error occurs
*/
protected function readBinaryData($length) {
if($length == 0) $buff = "";
else {
$buff = substr($this->content, $this->pos, $length);
if(strlen($buff) != $length) throw IOException::readError("");
$this->pos += $length;
}
return new CFData($buff,false);
}
/**
* Read a string value, usually coded as utf8
* @param integer $length The length (in bytes) of the string value
* @return CFString The string value, utf8 encoded
* @throws IOException if read error occurs
*/
protected function readBinaryString($length) {
if($length == 0) $buff = "";
else {
if(strlen($buff = substr($this->content, $this->pos, $length)) != $length) throw IOException::readError("");
$this->pos += $length;
}
if(!isset($this->uniqueTable[$buff])) $this->uniqueTable[$buff] = true;
return new CFString($buff);
}
/**
* Convert the given string from one charset to another.
* Trying to use MBString, Iconv, Recode - in that particular order.
* @param string $string the string to convert
* @param string $fromCharset the charset the given string is currently encoded in
* @param string $toCharset the charset to convert to, defaults to UTF-8
* @return string the converted string
* @throws PListException on neither MBString, Iconv, Recode being available
*/
public static function convertCharset($string, $fromCharset, $toCharset='UTF-8') {
if(function_exists('mb_convert_encoding')) return mb_convert_encoding($string, $toCharset, $fromCharset);
if(function_exists('iconv')) return iconv($fromCharset, $toCharset, $string);
if(function_exists('recode_string')) return recode_string($fromCharset .'..'. $toCharset, $string);
throw new PListException('neither iconv nor mbstring supported. how are we supposed to work on strings here?');
}
/**
* Count characters considering character set
* Trying to use MBString, Iconv - in that particular order.
* @param string $string the string to convert
* @param string $charset the charset the given string is currently encoded in
* @return integer The number of characters in that string
* @throws PListException on neither MBString, Iconv being available
*/
public static function charsetStrlen($string,$charset="UTF-8") {
if(function_exists('mb_strlen')) return mb_strlen($string, $charset);
if(function_exists('iconv_strlen')) return iconv_strlen($string,$charset);
throw new PListException('neither iconv nor mbstring supported. how are we supposed to work on strings here?');
}
/**
* Read a unicode string value, coded as UTF-16BE
* @param integer $length The length (in bytes) of the string value
* @return CFString The string value, utf8 encoded
* @throws IOException if read error occurs
*/
protected function readBinaryUnicodeString($length) {
/* The problem is: we get the length of the string IN CHARACTERS;
since a char in UTF-16 can be 16 or 32 bit long, we don't really know
how long the string is in bytes */
if(strlen($buff = substr($this->content, $this->pos, 2*$length)) != 2*$length) throw IOException::readError("");
$this->pos += 2 * $length;
if(!isset($this->uniqueTable[$buff])) $this->uniqueTable[$buff] = true;
return new CFString(self::convertCharset($buff, "UTF-16BE", "UTF-8"));
}
/**
* Read an array value, including contained objects
* @param integer $length The number of contained objects
* @return CFArray The array value, including the objects
* @throws IOException if read error occurs
*/
protected function readBinaryArray($length) {
$ary = new CFArray();
// first: read object refs
if($length != 0) {
if(strlen($buff = substr($this->content, $this->pos, $length * $this->objectRefSize)) != $length * $this->objectRefSize) throw IOException::readError("");
$this->pos += $length * $this->objectRefSize;
$objects = unpack($this->objectRefSize == 1 ? "C*" : "n*", $buff);
// now: read objects
for($i=0;$i<$length;++$i) {
$object = $this->readBinaryObjectAt($objects[$i+1]+1,$this->objectRefSize);
$ary->add($object);
}
}
return $ary;
}
/**
* Read a dictionary value, including contained objects
* @param integer $length The number of contained objects
* @return CFDictionary The dictionary value, including the objects
* @throws IOException if read error occurs
*/
protected function readBinaryDict($length) {
$dict = new CFDictionary();
// first: read keys
if($length != 0) {
if(strlen($buff = substr($this->content, $this->pos, $length * $this->objectRefSize)) != $length * $this->objectRefSize) throw IOException::readError("");
$this->pos += $length * $this->objectRefSize;
$keys = unpack(($this->objectRefSize == 1 ? "C*" : "n*"), $buff);
// second: read object refs
if(strlen($buff = substr($this->content, $this->pos, $length * $this->objectRefSize)) != $length * $this->objectRefSize) throw IOException::readError("");
$this->pos += $length * $this->objectRefSize;
$objects = unpack(($this->objectRefSize == 1 ? "C*" : "n*"), $buff);
// read real keys and objects
for($i=0;$i<$length;++$i) {
$key = $this->readBinaryObjectAt($keys[$i+1]+1);
$object = $this->readBinaryObjectAt($objects[$i+1]+1);
$dict->add($key->getValue(),$object);
}
}
return $dict;
}
/**
* Read an object type byte, decode it and delegate to the correct reader function
* @return mixed The value of the delegate reader, so any of the CFType subclasses
* @throws IOException if read error occurs
*/
function readBinaryObject() {
// first: read the marker byte
if(strlen($buff = substr($this->content,$this->pos,1)) != 1) throw IOException::readError("");
$this->pos++;
$object_length = unpack("C*", $buff);
$object_length = $object_length[1] & 0xF;
$buff = unpack("H*", $buff);
$buff = $buff[1];
$object_type = substr($buff, 0, 1);
if($object_type != "0" && $object_length == 15) {
$object_length = $this->readBinaryObject($this->objectRefSize);
$object_length = $object_length->getValue();
}
$retval = null;
switch($object_type) {
case '0': // null, false, true, fillbyte
$retval = $this->readBinaryNullType($object_length);
break;
case '1': // integer
$retval = $this->readBinaryInt($object_length);
break;
case '2': // real
$retval = $this->readBinaryReal($object_length);
break;
case '3': // date
$retval = $this->readBinaryDate($object_length);
break;
case '4': // data
$retval = $this->readBinaryData($object_length);
break;
case '5': // byte string, usually utf8 encoded
$retval = $this->readBinaryString($object_length);
break;
case '6': // unicode string (utf16be)
$retval = $this->readBinaryUnicodeString($object_length);
break;
case 'a': // array