AbstractWriter.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. /**
  3. * This file is part of PHPWord - A pure PHP library for reading and writing
  4. * word processing documents.
  5. *
  6. * PHPWord is free software distributed under the terms of the GNU Lesser
  7. * General Public License version 3 as published by the Free Software Foundation.
  8. *
  9. * For the full copyright and license information, please read the LICENSE
  10. * file that was distributed with this source code. For the full list of
  11. * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
  12. *
  13. * @see https://github.com/PHPOffice/PHPWord
  14. * @copyright 2010-2018 PHPWord contributors
  15. * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
  16. */
  17. namespace PhpOffice\PhpWord\Writer;
  18. use PhpOffice\PhpWord\Exception\CopyFileException;
  19. use PhpOffice\PhpWord\Exception\Exception;
  20. use PhpOffice\PhpWord\PhpWord;
  21. use PhpOffice\PhpWord\Settings;
  22. use PhpOffice\PhpWord\Shared\ZipArchive;
  23. /**
  24. * Abstract writer class
  25. *
  26. * @since 0.10.0
  27. */
  28. abstract class AbstractWriter implements WriterInterface
  29. {
  30. /**
  31. * PHPWord object
  32. *
  33. * @var \PhpOffice\PhpWord\PhpWord
  34. */
  35. protected $phpWord = null;
  36. /**
  37. * Part name and file name pairs
  38. *
  39. * @var array
  40. */
  41. protected $parts = array();
  42. /**
  43. * Individual writers
  44. *
  45. * @var array
  46. */
  47. protected $writerParts = array();
  48. /**
  49. * Paths to store media files
  50. *
  51. * @var array
  52. */
  53. protected $mediaPaths = array('image' => '', 'object' => '');
  54. /**
  55. * Use disk caching
  56. *
  57. * @var bool
  58. */
  59. private $useDiskCaching = false;
  60. /**
  61. * Disk caching directory
  62. *
  63. * @var string
  64. */
  65. private $diskCachingDirectory = './';
  66. /**
  67. * Temporary directory
  68. *
  69. * @var string
  70. */
  71. private $tempDir = '';
  72. /**
  73. * Original file name
  74. *
  75. * @var string
  76. */
  77. private $originalFilename;
  78. /**
  79. * Temporary file name
  80. *
  81. * @var string
  82. */
  83. private $tempFilename;
  84. /**
  85. * Get PhpWord object
  86. *
  87. * @throws \PhpOffice\PhpWord\Exception\Exception
  88. * @return \PhpOffice\PhpWord\PhpWord
  89. */
  90. public function getPhpWord()
  91. {
  92. if (!is_null($this->phpWord)) {
  93. return $this->phpWord;
  94. }
  95. throw new Exception('No PhpWord assigned.');
  96. }
  97. /**
  98. * Set PhpWord object
  99. *
  100. * @param \PhpOffice\PhpWord\PhpWord
  101. * @return self
  102. */
  103. public function setPhpWord(PhpWord $phpWord = null)
  104. {
  105. $this->phpWord = $phpWord;
  106. return $this;
  107. }
  108. /**
  109. * Get writer part
  110. *
  111. * @param string $partName Writer part name
  112. * @return mixed
  113. */
  114. public function getWriterPart($partName = '')
  115. {
  116. if ($partName != '' && isset($this->writerParts[strtolower($partName)])) {
  117. return $this->writerParts[strtolower($partName)];
  118. }
  119. return null;
  120. }
  121. /**
  122. * Get use disk caching status
  123. *
  124. * @return bool
  125. */
  126. public function isUseDiskCaching()
  127. {
  128. return $this->useDiskCaching;
  129. }
  130. /**
  131. * Set use disk caching status
  132. *
  133. * @param bool $value
  134. * @param string $directory
  135. *
  136. * @throws \PhpOffice\PhpWord\Exception\Exception
  137. * @return self
  138. */
  139. public function setUseDiskCaching($value = false, $directory = null)
  140. {
  141. $this->useDiskCaching = $value;
  142. if (!is_null($directory)) {
  143. if (is_dir($directory)) {
  144. $this->diskCachingDirectory = $directory;
  145. } else {
  146. throw new Exception("Directory does not exist: $directory");
  147. }
  148. }
  149. return $this;
  150. }
  151. /**
  152. * Get disk caching directory
  153. *
  154. * @return string
  155. */
  156. public function getDiskCachingDirectory()
  157. {
  158. return $this->diskCachingDirectory;
  159. }
  160. /**
  161. * Get temporary directory
  162. *
  163. * @return string
  164. */
  165. public function getTempDir()
  166. {
  167. return $this->tempDir;
  168. }
  169. /**
  170. * Set temporary directory
  171. *
  172. * @param string $value
  173. * @return self
  174. */
  175. public function setTempDir($value)
  176. {
  177. if (!is_dir($value)) {
  178. mkdir($value);
  179. }
  180. $this->tempDir = $value;
  181. return $this;
  182. }
  183. /**
  184. * Get temporary file name
  185. *
  186. * If $filename is php://output or php://stdout, make it a temporary file
  187. *
  188. * @param string $filename
  189. * @return string
  190. */
  191. protected function getTempFile($filename)
  192. {
  193. // Temporary directory
  194. $this->setTempDir(Settings::getTempDir() . uniqid('/PHPWordWriter_', true) . '/');
  195. // Temporary file
  196. $this->originalFilename = $filename;
  197. if (strpos(strtolower($filename), 'php://') === 0) {
  198. $filename = tempnam(Settings::getTempDir(), 'PhpWord');
  199. if (false === $filename) {
  200. $filename = $this->originalFilename; // @codeCoverageIgnore
  201. } // @codeCoverageIgnore
  202. }
  203. $this->tempFilename = $filename;
  204. return $this->tempFilename;
  205. }
  206. /**
  207. * Cleanup temporary file.
  208. *
  209. * @throws \PhpOffice\PhpWord\Exception\CopyFileException
  210. */
  211. protected function cleanupTempFile()
  212. {
  213. if ($this->originalFilename != $this->tempFilename) {
  214. // @codeCoverageIgnoreStart
  215. // Can't find any test case. Uncomment when found.
  216. if (false === copy($this->tempFilename, $this->originalFilename)) {
  217. throw new CopyFileException($this->tempFilename, $this->originalFilename);
  218. }
  219. // @codeCoverageIgnoreEnd
  220. @unlink($this->tempFilename);
  221. }
  222. $this->clearTempDir();
  223. }
  224. /**
  225. * Clear temporary directory.
  226. */
  227. protected function clearTempDir()
  228. {
  229. if (is_dir($this->tempDir)) {
  230. $this->deleteDir($this->tempDir);
  231. }
  232. }
  233. /**
  234. * Get ZipArchive object
  235. *
  236. * @param string $filename
  237. *
  238. * @throws \Exception
  239. *
  240. * @return \PhpOffice\PhpWord\Shared\ZipArchive
  241. */
  242. protected function getZipArchive($filename)
  243. {
  244. // Remove any existing file
  245. if (file_exists($filename)) {
  246. unlink($filename);
  247. }
  248. // Try opening the ZIP file
  249. $zip = new ZipArchive();
  250. // @codeCoverageIgnoreStart
  251. // Can't find any test case. Uncomment when found.
  252. if ($zip->open($filename, ZipArchive::OVERWRITE) !== true) {
  253. if ($zip->open($filename, ZipArchive::CREATE) !== true) {
  254. throw new \Exception("Could not open '{$filename}' for writing.");
  255. }
  256. }
  257. // @codeCoverageIgnoreEnd
  258. return $zip;
  259. }
  260. /**
  261. * Open file for writing
  262. *
  263. * @since 0.11.0
  264. *
  265. * @param string $filename
  266. *
  267. * @throws \Exception
  268. *
  269. * @return resource
  270. */
  271. protected function openFile($filename)
  272. {
  273. $filename = $this->getTempFile($filename);
  274. $fileHandle = fopen($filename, 'w');
  275. // @codeCoverageIgnoreStart
  276. // Can't find any test case. Uncomment when found.
  277. if ($fileHandle === false) {
  278. throw new \Exception("Could not open '{$filename}' for writing.");
  279. }
  280. // @codeCoverageIgnoreEnd
  281. return $fileHandle;
  282. }
  283. /**
  284. * Write content to file.
  285. *
  286. * @since 0.11.0
  287. *
  288. * @param resource $fileHandle
  289. * @param string $content
  290. */
  291. protected function writeFile($fileHandle, $content)
  292. {
  293. fwrite($fileHandle, $content);
  294. fclose($fileHandle);
  295. $this->cleanupTempFile();
  296. }
  297. /**
  298. * Add files to package.
  299. *
  300. * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip
  301. * @param mixed $elements
  302. */
  303. protected function addFilesToPackage(ZipArchive $zip, $elements)
  304. {
  305. foreach ($elements as $element) {
  306. $type = $element['type']; // image|object|link
  307. // Skip nonregistered types and set target
  308. if (!isset($this->mediaPaths[$type])) {
  309. continue;
  310. }
  311. $target = $this->mediaPaths[$type] . $element['target'];
  312. // Retrive GD image content or get local media
  313. if (isset($element['isMemImage']) && $element['isMemImage']) {
  314. $image = call_user_func($element['createFunction'], $element['source']);
  315. if ($element['imageType'] === 'image/png') {
  316. // PNG images need to preserve alpha channel information
  317. imagesavealpha($image, true);
  318. }
  319. ob_start();
  320. call_user_func($element['imageFunction'], $image);
  321. $imageContents = ob_get_contents();
  322. ob_end_clean();
  323. $zip->addFromString($target, $imageContents);
  324. imagedestroy($image);
  325. } else {
  326. $this->addFileToPackage($zip, $element['source'], $target);
  327. }
  328. }
  329. }
  330. /**
  331. * Add file to package.
  332. *
  333. * Get the actual source from an archive image.
  334. *
  335. * @param \PhpOffice\PhpWord\Shared\ZipArchive $zipPackage
  336. * @param string $source
  337. * @param string $target
  338. */
  339. protected function addFileToPackage($zipPackage, $source, $target)
  340. {
  341. $isArchive = strpos($source, 'zip://') !== false;
  342. $actualSource = null;
  343. if ($isArchive) {
  344. $source = substr($source, 6);
  345. list($zipFilename, $imageFilename) = explode('#', $source);
  346. $zip = new ZipArchive();
  347. if ($zip->open($zipFilename) !== false) {
  348. if ($zip->locateName($imageFilename)) {
  349. $zip->extractTo($this->getTempDir(), $imageFilename);
  350. $actualSource = $this->getTempDir() . DIRECTORY_SEPARATOR . $imageFilename;
  351. }
  352. }
  353. $zip->close();
  354. } else {
  355. $actualSource = $source;
  356. }
  357. if (!is_null($actualSource)) {
  358. $zipPackage->addFile($actualSource, $target);
  359. }
  360. }
  361. /**
  362. * Delete directory.
  363. *
  364. * @param string $dir
  365. */
  366. private function deleteDir($dir)
  367. {
  368. foreach (scandir($dir) as $file) {
  369. if ($file === '.' || $file === '..') {
  370. continue;
  371. } elseif (is_file($dir . '/' . $file)) {
  372. unlink($dir . '/' . $file);
  373. } elseif (is_dir($dir . '/' . $file)) {
  374. $this->deleteDir($dir . '/' . $file);
  375. }
  376. }
  377. rmdir($dir);
  378. }
  379. /**
  380. * Get use disk caching status
  381. *
  382. * @deprecated 0.10.0
  383. *
  384. * @codeCoverageIgnore
  385. */
  386. public function getUseDiskCaching()
  387. {
  388. return $this->isUseDiskCaching();
  389. }
  390. }