CFPropertyList.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. <?php
  2. /**
  3. * CFPropertyList
  4. * {@link http://developer.apple.com/documentation/Darwin/Reference/ManPages/man5/plist.5.html Property Lists}
  5. * @author Rodney Rehm <[email protected]>
  6. * @author Christian Kruse <[email protected]>
  7. * @package plist
  8. * @version $Id$
  9. * @example example-read-01.php Read an XML PropertyList
  10. * @example example-read-02.php Read a Binary PropertyList
  11. * @example example-read-03.php Read a PropertyList without knowing the type
  12. * @example example-create-01.php Using the CFPropertyList API
  13. * @example example-create-02.php Using CFPropertyList::guess()
  14. * @example example-create-03.php Using CFPropertyList::guess() with {@link CFDate} and {@link CFData}
  15. */
  16. /**
  17. * Require IOException, PListException, CFType and CFBinaryPropertyList
  18. */
  19. $plistDirectory = dirname(__FILE__);
  20. require_once($plistDirectory.'/IOException.php');
  21. require_once($plistDirectory.'/PListException.php');
  22. require_once($plistDirectory.'/CFType.php');
  23. require_once($plistDirectory.'/CFBinaryPropertyList.php');
  24. /**
  25. * Property List
  26. * Interface for handling reading, editing and saving Property Lists as defined by Apple.
  27. * @author Rodney Rehm <[email protected]>
  28. * @author Christian Kruse <[email protected]>
  29. * @package plist
  30. * @example example-read-01.php Read an XML PropertyList
  31. * @example example-read-02.php Read a Binary PropertyList
  32. * @example example-read-03.php Read a PropertyList without knowing the type
  33. * @example example-create-01.php Using the CFPropertyList API
  34. * @example example-create-02.php Using CFPropertyList::guess()
  35. * @example example-create-03.php Using CFPropertyList::guess() with {@link CFDate} and {@link CFData}
  36. */
  37. class CFPropertyList extends CFBinaryPropertyList implements Iterator {
  38. /**
  39. * Format constant for binary format
  40. * @var integer
  41. */
  42. const FORMAT_BINARY = 1;
  43. /**
  44. * Format constant for xml format
  45. * @var integer
  46. */
  47. const FORMAT_XML = 2;
  48. /**
  49. * Format constant for automatic format recognizing
  50. * @var integer
  51. */
  52. const FORMAT_AUTO = 0;
  53. /**
  54. * Path of PropertyList
  55. * @var string
  56. */
  57. protected $file = null;
  58. /**
  59. * Path of PropertyList
  60. * @var integer
  61. */
  62. protected $format = null;
  63. /**
  64. * CFType nodes
  65. * @var array
  66. */
  67. protected $value = array();
  68. /**
  69. * Position of iterator {@link http://php.net/manual/en/class.iterator.php}
  70. * @var integer
  71. */
  72. protected $iteratorPosition = 0;
  73. /**
  74. * List of Keys for numerical iterator access {@link http://php.net/manual/en/class.iterator.php}
  75. * @var array
  76. */
  77. protected $iteratorKeys = null;
  78. /**
  79. * List of NodeNames to ClassNames for resolving plist-files
  80. * @var array
  81. */
  82. protected static $types = array(
  83. 'string' => 'CFString',
  84. 'real' => 'CFNumber',
  85. 'integer' => 'CFNumber',
  86. 'date' => 'CFDate',
  87. 'true' => 'CFBoolean',
  88. 'false' => 'CFBoolean',
  89. 'data' => 'CFData',
  90. 'array' => 'CFArray',
  91. 'dict' => 'CFDictionary'
  92. );
  93. /**
  94. * Create new CFPropertyList.
  95. * If a path to a PropertyList is specified, it is loaded automatically.
  96. * @param string $file Path of PropertyList
  97. * @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}
  98. * @throws IOException if file could not be read by {@link load()}
  99. * @uses $file for storing the current file, if specified
  100. * @uses load() for loading the plist-file
  101. */
  102. public function __construct($file=null,$format=self::FORMAT_AUTO) {
  103. $this->file = $file;
  104. $this->format = $format;
  105. if($this->file) $this->load();
  106. }
  107. /**
  108. * Load an XML PropertyList.
  109. * @param string $file Path of PropertyList, defaults to {@link $file}
  110. * @return void
  111. * @throws IOException if file could not be read
  112. * @throws DOMException if XML-file could not be read properly
  113. * @uses load() to actually load the file
  114. */
  115. public function loadXML($file=null) {
  116. $this->load($file,CFPropertyList::FORMAT_XML);
  117. }
  118. /**
  119. * Load an binary PropertyList.
  120. * @param string $file Path of PropertyList, defaults to {@link $file}
  121. * @return void
  122. * @throws IOException if file could not be read
  123. * @throws PListException if binary plist-file could not be read properly
  124. * @uses load() to actually load the file
  125. */
  126. public function loadBinary($file=null) {
  127. $this->load($file,CFPropertyList::FORMAT_BINARY);
  128. }
  129. /**
  130. * Load a plist file.
  131. * Load and import a plist file.
  132. * @param string $file Path of PropertyList, defaults to {@link $file}
  133. * @param integer $format The format of the property list, see {@link FORMAT_XML}, {@link FORMAT_BINARY} and {@link FORMAT_AUTO}, defaults to {@link $format}
  134. * @return void
  135. * @throws PListException if file format version is not 00
  136. * @throws IOException if file could not be read
  137. * @throws DOMException if plist file could not be parsed properly
  138. * @uses $file if argument $file was not specified
  139. * @uses $value reset to empty array
  140. * @uses import() for importing the values
  141. */
  142. public function load($file=null,$format=null) {
  143. $file = $file ? $file : $this->file;
  144. $format = $format !== null ? $format : $this->format;
  145. $this->value = array();
  146. if(!is_readable($file)) throw IOException::notReadable($file);
  147. switch($format) {
  148. case CFPropertyList::FORMAT_BINARY:
  149. $this->readBinary($file);
  150. break;
  151. case CFPropertyList::FORMAT_AUTO: // what we now do is ugly, but neccessary to recognize the file format
  152. $fd = fopen($file,"rb");
  153. if(($magic_number = fread($fd,8)) === false) throw IOException::notReadable($file);
  154. fclose($fd);
  155. $filetype = substr($magic_number,0,6);
  156. $version = substr($magic_number,-2);
  157. if($filetype == "bplist") {
  158. if($version != "00") throw new PListException("Wrong file format version! Expected 00, got $version!");
  159. $this->readBinary($file);
  160. break;
  161. }
  162. // else: xml format, break not neccessary
  163. case CFPropertyList::FORMAT_XML:
  164. $doc = new DOMDocument();
  165. if(!$doc->load($file)) throw new DOMException();
  166. $this->import($doc->documentElement, $this);
  167. break;
  168. }
  169. }
  170. /**
  171. * Convert a DOMNode into a CFType.
  172. * @param DOMNode $node Node to import children of
  173. * @param CFDictionary|CFArray|CFPropertyList $parent
  174. * @return void
  175. */
  176. protected function import(DOMNode $node, $parent) {
  177. // abort if there are no children
  178. if(!$node->childNodes->length) return;
  179. foreach($node->childNodes as $n) {
  180. // skip if we can't handle the element
  181. if(!isset(self::$types[$n->nodeName])) continue;
  182. $class = self::$types[$n->nodeName];
  183. $key = null;
  184. // find previous <key> if possible
  185. $ps = $n->previousSibling;
  186. while($ps && $ps->nodeName == '#text' && $ps->previousSibling) $ps = $ps->previousSibling;
  187. // read <key> if possible
  188. if($ps && $ps->nodeName == 'key') $key = $ps->firstChild->nodeValue;
  189. switch($n->nodeName) {
  190. case 'date':
  191. $value = new $class(CFDate::dateValue($n->nodeValue));
  192. break;
  193. case 'data':
  194. $value = new $class($n->nodeValue,true);
  195. break;
  196. case 'string':
  197. $value = new $class($n->nodeValue);
  198. break;
  199. case 'real':
  200. case 'integer':
  201. $value = new $class($n->nodeName == 'real' ? floatval($n->nodeValue) : intval($n->nodeValue));
  202. break;
  203. case 'true':
  204. case 'false':
  205. $value = new $class($n->nodeName == 'true');
  206. break;
  207. case 'array':
  208. case 'dict':
  209. $value = new $class();
  210. $this->import($n, $value);
  211. break;
  212. }
  213. // Dictionaries need a key
  214. if($parent instanceof CFDictionary) $parent->add($key, $value);
  215. // others don't
  216. else $parent->add($value);
  217. }
  218. }
  219. /**
  220. * Convert CFPropertyList to XML and save to file.
  221. * @param string $file Path of PropertyList, defaults to {@link $file}
  222. * @return void
  223. * @throws IOException if file could not be read
  224. * @uses $file if $file was not specified
  225. */
  226. public function saveXML($file) {
  227. $this->save($file,CFPropertyList::FORMAT_XML);
  228. }
  229. /**
  230. * Convert CFPropertyList to binary format (bplist00) and save to file.
  231. * @param string $file Path of PropertyList, defaults to {@link $file}
  232. * @return void
  233. * @throws IOException if file could not be read
  234. * @uses $file if $file was not specified
  235. */
  236. public function saveBinary($file) {
  237. $this->save($file,CFPropertyList::FORMAT_BINARY);
  238. }
  239. /**
  240. * Convert CFPropertyList to XML or binary and save to file.
  241. * @param string $file Path of PropertyList, defaults to {@link $file}
  242. * @param string $format Format of PropertyList, defaults to {@link $format}
  243. * @return void
  244. * @throws IOException if file could not be read
  245. * @throws PListException if evaluated $format is neither {@link FORMAT_XML} nor {@link FORMAL_BINARY}
  246. * @uses $file if $file was not specified
  247. * @uses $format if $format was not specified
  248. */
  249. public function save($file=null,$format=null) {
  250. $file = $file ? $file : $this->file;
  251. $format = $format ? $format : $this->format;
  252. if( !in_array( $format, array( self::FORMAT_BINARY, self::FORMAT_XML ) ) )
  253. throw new PListException( "format {$format} is not supported, use CFPropertyList::FORMAT_BINARY or CFPropertyList::FORMAT_XML" );
  254. if(!file_exists($file)) {
  255. // dirname("file.xml") == "" and is treated as the current working directory
  256. if(!is_writable(dirname($file))) throw IOException::notWritable($file);
  257. }
  258. else if(!is_writable($file)) throw IOException::notWritable($file);
  259. $content = $format == self::FORMAT_BINARY ? $this->toBinary() : $this->toXML();
  260. $fh = fopen($file, 'wb');
  261. fwrite($fh,$content);
  262. fclose($fh);
  263. }
  264. /**
  265. * Convert CFPropertyList to XML
  266. * @param bool $formatted Print plist formatted (i.e. with newlines and whitespace indention) if true; defaults to false
  267. * @return string The XML content
  268. */
  269. public function toXML($formatted=false) {
  270. $domimpl = new DOMImplementation();
  271. // <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  272. $dtd = $domimpl->createDocumentType('plist', '-//Apple Computer//DTD PLIST 1.0//EN', 'http://www.apple.com/DTDs/PropertyList-1.0.dtd');
  273. $doc = $domimpl->createDocument(null, "plist", $dtd);
  274. $doc->encoding = "UTF-8";
  275. // format output
  276. if($formatted) {
  277. $doc->formatOutput = true;
  278. $doc->preserveWhiteSpace = true;
  279. }
  280. // get documentElement and set attribs
  281. $plist = $doc->documentElement;
  282. $plist->setAttribute('version', '1.0');
  283. // add PropertyList's children
  284. $plist->appendChild($this->getValue()->toXML($doc));
  285. return $doc->saveXML();
  286. }
  287. /************************************************************************************************
  288. * M A N I P U L A T I O N
  289. ************************************************************************************************/
  290. /**
  291. * Add CFType to collection.
  292. * @param CFType $value CFType to add to collection
  293. * @return void
  294. * @uses $value for adding $value
  295. */
  296. public function add($value) {
  297. $this->value[] = $value;
  298. }
  299. /**
  300. * Get CFType from collection.
  301. * @param integer $key Key of CFType to retrieve from collection
  302. * @return CFType CFType found at $key, null else
  303. * @uses $value for retrieving CFType of $key
  304. */
  305. public function get($key) {
  306. if(isset($this->value[$key])) return $this->value[$key];
  307. return null;
  308. }
  309. /**
  310. * Remove CFType from collection.
  311. * @param integer $key Key of CFType to removes from collection
  312. * @return CFType removed CFType, null else
  313. * @uses $value for removing CFType of $key
  314. */
  315. public function del($key) {
  316. if(isset($this->value[$key])) {
  317. $t = $this->value[$key];
  318. unset($this->value[$key]);
  319. return $t;
  320. }
  321. return null;
  322. }
  323. /**
  324. * Get first (and only) child, or complete collection.
  325. * @return CFType|array CFType or list of CFTypes known to the PropertyList
  326. * @uses $value for retrieving CFTypes
  327. */
  328. public function getValue() {
  329. if(count($this->value) === 1) return $this->value[0];
  330. return $this->value;
  331. }
  332. /**
  333. * Create CFType-structure from guessing the data-types.
  334. * {@link CFArray}, {@link CFDictionary}, {@link CFBoolean}, {@link CFNumber} and {@link CFString} can be created, {@link CFDate} and {@link CFData} cannot.
  335. * <br /><b>Note:</b>Distinguishing between {@link CFArray} and {@link CFDictionary} is done by examining the keys.
  336. * Keys must be strictly incrementing integers to evaluate to a {@link CFArray}.
  337. * Since PHP does not offer a function to test for associative arrays,
  338. * this test causes the input array to be walked twice and thus work rather slow on large collections.
  339. * If you work with large arrays and can live with all arrays evaluating to {@link CFDictionary},
  340. * feel free to set the appropriate flag.
  341. * <br /><b>Note:</b> If $value is an instance of CFType it is simply returned.
  342. * <br /><b>Note:</b> If $value is neither a CFType, array, numeric, boolean nor string, it is omitted.
  343. * @param mixed $value Value to convert to CFType
  344. * @param boolean $autoDictionary if true {@link CFArray}-detection is bypassed and arrays will be returned as {@link CFDictionary}.
  345. * @return CFType CFType based on guessed type
  346. */
  347. public static function guess($value, $autoDictionary=false) {
  348. switch(true) {
  349. case $value instanceof CFType:
  350. return $value;
  351. break;
  352. case is_array($value):
  353. // test if $value is simple or associative array
  354. if(!$autoDictionary) {
  355. $numericKeys = true;
  356. $previousKey = null;
  357. foreach($value as $key => $v) {
  358. if(!is_numeric($key) || ($previousKey !== null && $previousKey != $key-1)) {
  359. $numericKeys = false;
  360. break;
  361. }
  362. $previousKey = $key;
  363. }
  364. if($numericKeys) {
  365. $t = new CFArray();
  366. foreach($value as $v) $t->add(self::guess($v, $autoDictionary));
  367. return $t;
  368. }
  369. }
  370. $t = new CFDictionary();
  371. foreach($value as $k => $v) $t->add($k, self::guess($v, $autoDictionary));
  372. return $t;
  373. break;
  374. case is_numeric($value):
  375. return new CFNumber($value);
  376. break;
  377. case is_bool($value):
  378. return new CFBoolean($value);
  379. break;
  380. case is_string($value):
  381. return new CFString($value);
  382. break;
  383. }
  384. }
  385. /************************************************************************************************
  386. * S E R I A L I Z I N G
  387. ************************************************************************************************/
  388. /**
  389. * Get PropertyList as array.
  390. * @return mixed primitive value of first (and only) CFType, or array of primitive values of collection
  391. * @uses $value for retrieving CFTypes
  392. */
  393. public function toArray() {
  394. $a = array();
  395. foreach($this->value as $value) $a[] = $value->toArray();
  396. if(count($a) === 1) return $a[0];
  397. return $a;
  398. }
  399. /************************************************************************************************
  400. * I T E R A T O R I N T E R F A C E
  401. ************************************************************************************************/
  402. /**
  403. * Rewind {@link $iteratorPosition} to first position (being 0)
  404. * @link http://php.net/manual/en/iterator.rewind.php
  405. * @return void
  406. * @uses $iteratorPosition set to 0
  407. * @uses $iteratorKeys store keys of {@link $value}
  408. */
  409. public function rewind() {
  410. $this->iteratorPosition = 0;
  411. $this->iteratorKeys = array_keys($this->value);
  412. }
  413. /**
  414. * Get Iterator's current {@link CFType} identified by {@link $iteratorPosition}
  415. * @link http://php.net/manual/en/iterator.current.php
  416. * @return CFType current Item
  417. * @uses $iteratorPosition identify current key
  418. * @uses $iteratorKeys identify current value
  419. */
  420. public function current() {
  421. return $this->value[$this->iteratorKeys[$this->iteratorPosition]];
  422. }
  423. /**
  424. * Get Iterator's current key identified by {@link $iteratorPosition}
  425. * @link http://php.net/manual/en/iterator.key.php
  426. * @return string key of the current Item
  427. * @uses $iteratorPosition identify current key
  428. * @uses $iteratorKeys identify current value
  429. */
  430. public function key() {
  431. return $this->iteratorKeys[$this->iteratorPosition];
  432. }
  433. /**
  434. * Increment {@link $iteratorPosition} to address next {@see CFType}
  435. * @link http://php.net/manual/en/iterator.next.php
  436. * @return void
  437. * @uses $iteratorPosition increment by 1
  438. */
  439. public function next() {
  440. $this->iteratorPosition++;
  441. }
  442. /**
  443. * Test if {@link $iteratorPosition} addresses a valid element of {@link $value}
  444. * @link http://php.net/manual/en/iterator.valid.php
  445. * @return boolean true if current position is valid, false else
  446. * @uses $iteratorPosition test if within {@link $iteratorKeys}
  447. * @uses $iteratorPosition test if within {@link $value}
  448. */
  449. public function valid() {
  450. return isset($this->iteratorKeys[$this->iteratorPosition]) && isset($this->value[$this->iteratorKeys[$this->iteratorPosition]]);
  451. }
  452. }
  453. ?>