forked from deathlyfrantic/php-idml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IDMLPackage.php
767 lines (715 loc) · 24 KB
/
IDMLPackage.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
<?php
namespace IDMLPackage;
/**
* An object that handles all of the individual files in an IDML package.
* This is a very simple class that was developed as part of a much larger
* project. It basically only serves as a file manager/server for the component
* XML files of an IDML package.
*
* Any methods that aren't specifically getters should return $this to facilitate
* method chaining.
*/
class IDMLPackage
{
protected $designMap;
protected $masterSpreads = [];
protected $graphic;
protected $fonts;
protected $styles;
protected $preferences;
protected $spreads = [];
protected $stories = [];
protected $backingStory;
protected $tags;
protected $mapping;
protected $directory;
protected $zip;
/**
* Return the full complete paths of the entire contents of a directory including all subdirectories.
* @param string $path The path of the directory whose contents you want.
* @return array An array of the full paths of those contents.
*/
// this is included here to make this class standalone but ideally you'd factor it out
// see my gist of recursive utils @ https://gist.github.com/zandrmartin/086bba7b2a25ec8e57cc
public function getDirectoryContents($path)
{
$results = [];
try {
$iterator = new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS);
foreach($iterator as $i) {
$results[] = $i;
if($i->isDir()) {
$results = array_merge($results, $this->getDirectoryContents($i));
}
}
} catch(\UnexpectedValueException $e) {
// $results is already an empty array so nothing to do here, we'll just return it as is.
}
return $results;
}
/**
* This is an array used to map package elements to their respective load methods.
* See $this->load(). I am lazy and hate typing.
*/
protected $packageElements = [
"Graphic" => "set",
"Fonts" => "set",
"Styles" => "set",
"Preferences" => "set",
"Tags" => "set",
"MasterSpread" => "add",
"Spread" => "add",
"BackingStory" => "set",
"Story" => "add",
"Mapping" => "set"
];
/**
* If the parameter is an IDML file - and there is not a ton of checking that goes into that -
* pass it to setZip() which unzips it and loads up stuff. Otherwise, if it's a directory,
* load it from that.
* The project I developed this for uses IDML packages that live in an unzipped form
* so they can be easily-modified before zipping up for processing.
*/
public function __construct($val = "")
{
if(mb_strpos($val, ".idml") !== false && file_exists($val)) {
$this->setZip($val)->load();
} elseif(is_dir($val)) {
$this->setDirectory($val)->load();
}
return $this;
}
/**
* Basically if this package was loaded from an IDML file, we're assuming we unzipped it,
* so delete all the temp directory and files we created by unzipping it.
*/
public function __destruct()
{
if($this->isZip() && is_dir($this->getDirectory())) {
$pathObjects = $this->getDirectoryContents($this->getDirectory());
$contents = array_map(
function ($pathObject) {
return $pathObject->getRealPath();
},
array_reverse($pathObjects)
);
foreach($contents as $content) {
if(is_dir($content)) {
rmdir($content);
} else {
unlink($content);
}
}
rmdir($this->getDirectory());
}
}
/**
* Get the design map of the IDML.
* @return DOMDocument The designmap.xml of the IDML package.
*/
public function getDesignMap()
{
return $this->designMap;
}
/**
* Set the design map of the IDML.
* @param \DOMDocument $val
* The DOMDocument object loaded with the designmap.xml file.
*/
public function setDesignMap(\DOMDocument $val)
{
$this->designMap = $val;
return $this;
}
/**
* Get either a single master spread or an array of master spreads.
* @param string $which [optional]
* The self id of the master spread you wish to return.
* @return [mixed] Without $which parameter, returns an array of all master spreads.
* With $which parameter, returns a single DOMDocument of the specified master spread.
*/
public function getMasterSpreads($which = "")
{
if(array_key_exists($which, $this->masterSpreads)) {
return $this->masterSpreads[$which];
}
return $this->masterSpreads;
}
/**
* Master spreads setter. If you only have one, wrap it in [] before passing.
* @param array $val The array of master spreads.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setMasterSpreads(array $val)
{
$this->designMap = $val;
return $this;
}
/**
* Returns the DOMDocument object of the Graphic.xml file.
*/
public function getGraphic()
{
return $this->graphic;
}
/**
* Graphic setter.
* @param \DOMDocument $val The Graphic.xml file's DOMDocument.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setGraphic(\DOMDocument $val)
{
$this->graphic = $val;
return $this;
}
/**
* Returns the DOMDocument object of the Fonts.xml file.
*/
public function getFonts()
{
return $this->fonts;
}
/**
* Fonts setter.
* @param \DOMDocument $val The Fonts.xml file's DOMDocument.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setFonts(\DOMDocument $val)
{
$this->fonts = $val;
return $this;
}
/**
* Returns the DOMDocument object of the Styles.xml file.
*/
public function getStyles()
{
return $this->styles;
}
/**
* Styles setter.
* @param \DOMDocument $val The Styles.xml file's DOMDocument.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setStyles(\DOMDocument $val)
{
$this->styles = $val;
return $this;
}
/**
* Returns the DOMDocument object of the Preferences.xml file.
*/
public function getPreferences()
{
return $this->preferences;
}
/**
* Preferences setter.
* @param \DOMDocument $val The Preferences.xml file's DOMDocument.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setPreferences(\DOMDocument $val)
{
$this->preferences = $val;
return $this;
}
/**
* Get either a single spread or an array of spreads.
* @param string $which [optional]
* The self id of the spread you wish to return.
* @return [mixed] Without $which parameter, returns an array of all spreads.
* With $which parameter, returns a single DOMDocument of the specified spread.
*/
public function getSpreads($which = "")
{
if(array_key_exists($which, $this->spreads)) {
return $this->spreads[$which];
}
return $this->spreads;
}
/**
* Spreads setter. If you only have one, wrap it in [] before passing.
* @param array $val The array of spreads.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setSpreads(array $val)
{
$this->spreads = $val;
return $this;
}
public function getStories($which = "")
{
if(array_key_exists($which, $this->stories)) {
return $this->stories[$which];
}
return $this->stories;
}
/**
* Stories setter. If you only have one, wrap it in [] before passing.
* @param array $val The array of stories.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setStories(array $val)
{
$this->stories = $val;
return $this;
}
/**
* Returns the DOMDocument object of the BackingStory.xml file.
*/
public function getBackingStory()
{
return $this->backingStory;
}
/**
* Backing story setter.
* @param \DOMDocument $val The BackingStory.xml file's DOMDocument.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setBackingStory(\DOMDocument $val)
{
$this->backingStory = $val;
return $this;
}
/**
* Returns the DOMDocument object of the Tags.xml file.
*/
public function getTags()
{
return $this->tags;
}
/**
* Tags setter.
* @param \DOMDocument $val The Tags.xml file's DOMDocument.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setTags(\DOMDocument $val)
{
$this->tags = $val;
return $this;
}
/**
* Returns the DOMDocument object of the Mapping.xml file.
*/
public function getMapping()
{
return $this->mapping;
}
/**
* Mapping setter.
* @param \DOMDocument $val The Mapping.xml file's DOMDocument.
* @return IDMLPackage\IDMLPackage This object for method chaining.
*/
public function setMapping(\DOMDocument $val)
{
$this->mapping = $val;
return $this;
}
/**
* Returns a string containing the directory name of this IDML.
*/
public function getDirectory()
{
return $this->directory;
}
/**
* Set the directory for this IDML package. Basically if you have /directory/idmlfile.idml
* and unzipped it, you'd setDirectory("/directory/").
*/
public function setDirectory($val)
{
if(is_dir($val) || is_null($val)) {
$this->directory = $val;
if(is_null($val) === false && mb_substr($val, -1) !== "/") {
$this->directory .= "/";
}
}
return $this;
}
/**
* Returns a string containing the zip file name of this IDML.
*/
public function getZip()
{
return $this->zip;
}
/**
* Set the zip file for this package. If you have /directory/idmlfile.idml, you'd
* setZip("/directory/idmlfile.idml"). This would then unzip that file to /directory/.idmlfile.idml/
* and load all the stuff.
* The __destruct() method ensures this temporary directory will be deleted upon object destruction.
*/
public function setZip($val)
{
$this->zip = realpath($val);
if(empty($this->getDirectory()) && $this->getDirectory() !== 0) {
// gotta love empty() and PHP's automatic type-conversion :/
$directoryName = dirname($val) . DIRECTORY_SEPARATOR . "." . basename($val);
mkdir($directoryName, 0775);
$this->setDirectory($directoryName);
$zip = new \ZipArchive();
$zip->open($val);
$zip->extractTo($directoryName);
$zip->close();
}
return $this;
}
/**
* Set all array properties to empty arrays.
*/
public function unsetArrays()
{
$this->setSpreads([])
->setMasterSpreads([])
->setStories([]);
return $this;
}
/**
* Special method to load the designmap.xml of this IDML which is required to get all of the other components.
*/
public function loadDesignMap()
{
$designmap = $this->createDom($this->getDirectory() . "designmap.xml");
$this->setDesignMap($designmap);
return $this;
}
/**
* This is the master load method that will create populate the object with
* DOMDocuments of the component XML files. You need to set the location of
* the IDML before this method is called - either by passing it with the
* instantiation (new IDMLPackage\IDMLPackage("idmlfile.idml")) or by calling
* the setZip() or setDirectory() methods.
*/
public function load()
{
// since some files are appended to arrays, let's unset those arrays when we load just to be safe
$this->unsetArrays();
if($this->getDesignMap() instanceof \DOMDocument == false) {
$this->loadDesignMap();
}
$xpath = new \DOMXPath($this->getDesignMap());
$xpath->registerNamespace("idPkg", "http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging");
// I just didn't want to type all the loading logic out so I did a complicated loop
foreach($this->packageElements as $packageElement => $setPrefix) {
$elements = $xpath->query("//idPkg:$packageElement");
if($elements->length > 0) {
foreach($elements as $element) {
$filename = $element->getAttribute("src");
if(file_exists($this->getDirectory() . $filename)) {
$file = $this->createDom($filename);
$setter = "$setPrefix$packageElement";
$this->$setter($file);
}
}
}
}
return $this;
}
/**
* Save the designmap.xml file to disk.
*/
public function saveDesignMap()
{
$this->getDesignMap()->save($this->getDesignMap()->documentURI);
return $this;
}
/**
* Save the stories files to disk.
*/
public function saveStories()
{
$this->saveArrayOfDoms($this->getStories());
return $this;
}
/**
* Save the master spreads files to disk.
*/
public function saveMasterSpreads()
{
$this->saveArrayOfDoms($this->getMasterSpreads());
return $this;
}
/**
* Save the spreads files to disk.
*/
public function saveSpreads()
{
$this->saveArrayOfDoms($this->getSpreads());
return $this;
}
/**
* Saves all of the individual documents in the IDML package to their documentURI locations.
*/
public function saveAll()
{
$this->saveDesignMap()
->saveStories()
->saveMasterSpreads()
->saveSpreads();
foreach($this->packageElements as $element => $setPrefix) {
if($setPrefix == "set") {
$getter = "get$element";
$file = $this->$getter();
if($file instanceof \DOMDocument) {
$file->save($file->documentURI);
}
}
}
if($this->isZip()) {
$this->zipPackage($this->getZip());
}
return $this;
}
/**
* Zip this package into an IDML file from its component parts.
* @param string $name [optional] If supplied, this is the filename of the zipped package. If not supplied,
* this defaults to the name of the directory of this IDML package with a ".idml" extension.
*/
public function zipPackage($name = "")
{
$currentDirectory = getcwd();
chdir($this->getDirectory());
if($name == "") {
if(empty($this->getZip()) == false) {
$name = basename($this->getZip());
} else {
$name = basename($this->getDirectory()) . ".idml";
}
}
$zip = new \ZipArchive();
$zip->open($name, \ZipArchive::CREATE);
$dir = new \SplFileInfo(".");
// this chunk is from my ZipFile class that extends PHP's ZipArchive.
// https://github.com/zandrmartin/php-zipfile
// it is included here to make this class standalone but ideally you'd factor this out
if($dir->isDir()) {
$contents = $this->getDirectoryContents($this->getDirectory());
$baseDir = $dir->getPathInfo()->getRealPath();
} else {
$contents = [];
}
if(count($contents) === 0) {
$zip->addEmptyDir($dir->getBasename());
} else {
foreach($contents as $c) {
if(is_dir($c)) {
// safe to do because directories will always come before their contents
// in the array returned by getDirectoryContents()
$zip->addEmptyDir($dir->getBasename());
} else {
$zip->addFile($c, str_replace($baseDir . DIRECTORY_SEPARATOR, "", $c));
}
}
}
$zip->close();
$this->setZip($name);
chdir($currentDirectory);
return $this;
}
/**
* Adds a story to the story array of this IDML package.
* @param \DOMDocument $val The story to add.
*/
public function addStory(\DOMDocument $val)
{
$key = str_replace(["Story_", ".xml"], "", basename($val->documentURI));
$this->stories[$key] = $val;
return $this;
}
/**
* Adds a story to the designmap of the IDML package so InDesign knows it is there.
* @param \DOMDocument $val The story to add to the designmap.
*/
public function addStoryToDesignMap(\DOMDocument $val)
{
$this->addStory($val);
$node = $this->getDesignMap()->createElement("idPkg:Story");
$this->getDesignMap()->documentElement->appendChild($node);
$source = str_replace($this->getDirectory(), "", $val->documentURI);
$node->setAttribute("src", $source);
return $this;
}
/**
* Add a spread to the spreads property of this package.
* Does NOT do anything other than this - no file creation/saving/etc.
*/
public function addSpread(\DOMDocument $val)
{
$this->spreads[$this->getSelfAttributeOfDom($val)] = $val;
return $this;
}
/**
* Adds an element to the spread of this IDML package.
* See the notes on the getSpread() method - you'll have to adjust this if your IDML
* files have more than one spread.
* @param \DOMNode $val The element to be added to the spread.
* @param \DOMDocument $spread The spread you want to which you want to add the element. If not provided, defaults
* to whatever getSpread() returns.
*/
public function addElementToSpread(\DOMNode $val, $spread = "")
{
if($spread instanceof \DOMDocument === false) {
$spread = $this->getSpread();
}
$spreadNodelist = $spread->getElementsByTagName("Spread");
$spreadElement = $spreadNodelist->item($spreadNodelist->length - 1);
$spreadElement->appendChild($spread->importNode($val, true));
return $this;
}
/**
* Add a master spread to the master spreads property of this package.
* Does NOT do anything other than this - no file creation/saving/etc.
*/
public function addMasterSpread(\DOMDocument $val)
{
$this->masterSpreads[$this->getSelfAttributeOfDom($val)] = $val;
return $this;
}
/**
* This is a convenience method for the project that spawned this class. All of the IDML
* files used in that project have only one spread so this was easier than typing it out
* in a thousand different places. Don't use if your IDML files have multiple spreads.
* @return \DOMDocument The spread.
*/
public function getSpread()
{
return array_values($this->getSpreads())[0];
}
/**
* Get layers from the designmap.xml of this IDML package.
* @param bool $selfsOnly If true, returns only the self attributes of the layers. If false,
* returns the layer elements.
* @param bool $visibleOnly If true, returns only visible layers. If false, returns all layers.
* @return mixed If $selfsOnly is true, this is an array of strings. Otherwise, it is a
* \DOMNodeList of the layer elements.
*/
public function getLayers($selfsOnly = false, $visibleOnly = true)
{
$xpath = new \DOMXPath($this->getDesignMap);
if($visibleOnly) {
$query = "//Layer[@Visible='true']";
} else {
$query = "//Layer";
}
$layers = $xpath->query($query);
if($selfsOnly) {
$names = [];
foreach($layers as $layer) {
$names[] = $layer->getAttribute("Self");
}
sort($names);
return array_unique($names);
}
return $layers;
}
/**
* Returns the specified DOM element if it can be found within the package.
* @param string $self The self attibute of the requested DOM element. Generally something like "u12f".
* @return mixed A \DOMNode of the requested element if it is found, or false if it is not.
*/
public function getElementBySelfAttribute($self = "")
{
if($self !== "") {
$doms = array_merge(
$this->getSpreads(),
$this->getMasterSpreads(),
$this->getStories(),
[$this->getBackingStory()]
);
foreach($doms as $dom) {
$xpath = new \DOMXPath($dom);
$elements = $xpath->query("//node()[@Self='$self']");
if($elements->length > 0) {
return $elements->item(0);
}
}
}
return false;
}
/**
* Determine whether this IDML package was loaded from a zipped .idml package, or from an unzipped directory.
* @return bool True means it was created from a zip. False means it was created from a directory.
*/
protected function isZip()
{
if(empty($this->getZip()) == false && basename($this->getDirectory())[0] == ".") {
return true;
}
return false;
}
/**
* Create a \DOMDocument and load it with the supplied file.
* @param string $filename [optional] The name of the file to be loaded.
* @return \DOMDocument The object that was created.
*/
protected function createDom($filename = "")
{
$dom = new \DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$tryFiles = [$filename, $this->getDirectory() . $filename];
if($filename != "") {
foreach($tryFiles as $file) {
if(file_exists($file)) {
$dom->load($file);
}
}
}
return $dom;
}
/**
* Saves each \DOMDocument in an array to disk, using its documentURI property as the file location.
* @param array $array An array of \DOMDocuments.
*/
protected function saveArrayOfDoms(array $array)
{
foreach($array as $dom) {
$dom->save($dom->documentURI);
}
return $this;
}
/**
* A convenience method to get the self attribute of the main element of a component.
* e.g. for a story, this returns u123 from <Story Self="u123">
*/
protected function getSelfAttributeOfDom(\DOMDocument $dom)
{
$elementName = str_replace("idPkg:", "", $dom->documentElement->nodeName);
$element = $dom->documentElement->getElementsByTagName($elementName)->item(0);
return $element->getAttribute("Self");
}
/**
* Get the tag of an element from the XML\BackingStory.xml file.
* @param \DOMElement $node The element for which we want the tag.
* @return mixed The tag if one is found, or false if one is not found.
*/
public function getMarkupTag(\DOMElement $node)
{
$tag = false;
$selfs = [$node->getAttribute("Self")];
$xpath = Build::DOMXPath($this->getBackingStory());
if($node->nodeName == "TextFrame") {
$selfs[] = $node->getAttribute("ParentStory");
}
foreach($selfs as $self) {
$xmlElement = false;
while($node->parentNode) {
$node = $node->parentNode;
if("XMLElement" == $node->nodeName) {
$xmlElement = $node;
break;
}
}
if($xmlElement == false) {
$xmlElements = $xpath->query("//XMLElement[@XMLContent='$self']");
if($xmlElements->length > 0) {
$xmlElement = $xmlElements->item(0);
}
}
if($xmlElement && empty($xmlElement->getAttribute("MarkupTag")) == false) {
$tag = str_replace("XMLTag/", "", $xmlElement->getAttribute("MarkupTag"));
}
}
return urldecode($tag);
}
}