No Description

AbstractWriter.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. * @link https://github.com/PHPOffice/PHPWord
  14. * @copyright 2010-2014 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. * @return \PhpOffice\PhpWord\PhpWord
  88. * @throws \PhpOffice\PhpWord\Exception\Exception
  89. */
  90. public function getPhpWord()
  91. {
  92. if (!is_null($this->phpWord)) {
  93. return $this->phpWord;
  94. } else {
  95. throw new Exception("No PhpWord assigned.");
  96. }
  97. }
  98. /**
  99. * Set PhpWord object
  100. *
  101. * @param \PhpOffice\PhpWord\PhpWord
  102. * @return self
  103. */
  104. public function setPhpWord(PhpWord $phpWord = null)
  105. {
  106. $this->phpWord = $phpWord;
  107. return $this;
  108. }
  109. /**
  110. * Get writer part
  111. *
  112. * @param string $partName Writer part name
  113. * @return mixed
  114. */
  115. public function getWriterPart($partName = '')
  116. {
  117. if ($partName != '' && isset($this->writerParts[strtolower($partName)])) {
  118. return $this->writerParts[strtolower($partName)];
  119. } else {
  120. return null;
  121. }
  122. }
  123. /**
  124. * Get use disk caching status
  125. *
  126. * @return bool
  127. */
  128. public function isUseDiskCaching()
  129. {
  130. return $this->useDiskCaching;
  131. }
  132. /**
  133. * Set use disk caching status
  134. *
  135. * @param bool $value
  136. * @param string $directory
  137. * @return self
  138. * @throws \PhpOffice\PhpWord\Exception\Exception
  139. */
  140. public function setUseDiskCaching($value = false, $directory = null)
  141. {
  142. $this->useDiskCaching = $value;
  143. if (!is_null($directory)) {
  144. if (is_dir($directory)) {
  145. $this->diskCachingDirectory = $directory;
  146. } else {
  147. throw new Exception("Directory does not exist: $directory");
  148. }
  149. }
  150. return $this;
  151. }
  152. /**
  153. * Get disk caching directory
  154. *
  155. * @return string
  156. */
  157. public function getDiskCachingDirectory()
  158. {
  159. return $this->diskCachingDirectory;
  160. }
  161. /**
  162. * Get temporary directory
  163. *
  164. * @return string
  165. */
  166. public function getTempDir()
  167. {
  168. return $this->tempDir;
  169. }
  170. /**
  171. * Set temporary directory
  172. *
  173. * @param string $value
  174. * @return self
  175. */
  176. public function setTempDir($value)
  177. {
  178. if (!is_dir($value)) {
  179. mkdir($value);
  180. }
  181. $this->tempDir = $value;
  182. return $this;
  183. }
  184. /**
  185. * Get temporary file name
  186. *
  187. * If $filename is php://output or php://stdout, make it a temporary file
  188. *
  189. * @param string $filename
  190. * @return string
  191. */
  192. protected function getTempFile($filename)
  193. {
  194. // Temporary directory
  195. $this->setTempDir(Settings::getTempDir() . '/PHPWordWriter/');
  196. // Temporary file
  197. $this->originalFilename = $filename;
  198. if (strtolower($filename) == 'php://output' || strtolower($filename) == 'php://stdout') {
  199. $filename = tempnam(Settings::getTempDir(), 'PhpWord');
  200. if (false === $filename) {
  201. $filename = $this->originalFilename;
  202. }
  203. }
  204. $this->tempFilename = $filename;
  205. return $this->tempFilename;
  206. }
  207. /**
  208. * Cleanup temporary file.
  209. *
  210. * @return void
  211. * @throws \PhpOffice\PhpWord\Exception\CopyFileException
  212. */
  213. protected function cleanupTempFile()
  214. {
  215. if ($this->originalFilename != $this->tempFilename) {
  216. // @codeCoverageIgnoreStart
  217. // Can't find any test case. Uncomment when found.
  218. if (false === copy($this->tempFilename, $this->originalFilename)) {
  219. throw new CopyFileException($this->tempFilename, $this->originalFilename);
  220. }
  221. // @codeCoverageIgnoreEnd
  222. @unlink($this->tempFilename);
  223. }
  224. $this->clearTempDir();
  225. }
  226. /**
  227. * Clear temporary directory.
  228. *
  229. * @return void
  230. */
  231. protected function clearTempDir()
  232. {
  233. if (is_dir($this->tempDir)) {
  234. $this->deleteDir($this->tempDir);
  235. }
  236. }
  237. /**
  238. * Get ZipArchive object
  239. *
  240. * @param string $filename
  241. * @return \PhpOffice\PhpWord\Shared\ZipArchive
  242. * @throws \Exception
  243. */
  244. protected function getZipArchive($filename)
  245. {
  246. // Remove any existing file
  247. if (file_exists($filename)) {
  248. unlink($filename);
  249. }
  250. // Try opening the ZIP file
  251. $zip = new ZipArchive();
  252. // @codeCoverageIgnoreStart
  253. // Can't find any test case. Uncomment when found.
  254. if ($zip->open($filename, ZipArchive::OVERWRITE) !== true) {
  255. if ($zip->open($filename, ZipArchive::CREATE) !== true) {
  256. throw new \Exception("Could not open '{$filename}' for writing.");
  257. }
  258. }
  259. // @codeCoverageIgnoreEnd
  260. return $zip;
  261. }
  262. /**
  263. * Open file for writing
  264. *
  265. * @param string $filename
  266. * @return resource
  267. * @throws \Exception
  268. * @since 0.11.0
  269. */
  270. protected function openFile($filename)
  271. {
  272. $filename = $this->getTempFile($filename);
  273. $fileHandle = fopen($filename, 'w');
  274. // @codeCoverageIgnoreStart
  275. // Can't find any test case. Uncomment when found.
  276. if ($fileHandle === false) {
  277. throw new \Exception("Could not open '{$filename}' for writing.");
  278. }
  279. // @codeCoverageIgnoreEnd
  280. return $fileHandle;
  281. }
  282. /**
  283. * Write content to file.
  284. *
  285. * @since 0.11.0
  286. *
  287. * @param resource $fileHandle
  288. * @param string $content
  289. * @return void
  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. * @return void
  303. */
  304. protected function addFilesToPackage(ZipArchive $zip, $elements)
  305. {
  306. foreach ($elements as $element) {
  307. $type = $element['type']; // image|object|link
  308. // Skip nonregistered types and set target
  309. if (!isset($this->mediaPaths[$type])) {
  310. continue;
  311. }
  312. $target = $this->mediaPaths[$type] . $element['target'];
  313. // Retrive GD image content or get local media
  314. if (isset($element['isMemImage']) && $element['isMemImage']) {
  315. $image = call_user_func($element['createFunction'], $element['source']);
  316. ob_start();
  317. call_user_func($element['imageFunction'], $image);
  318. $imageContents = ob_get_contents();
  319. ob_end_clean();
  320. $zip->addFromString($target, $imageContents);
  321. imagedestroy($image);
  322. } else {
  323. $this->addFileToPackage($zip, $element['source'], $target);
  324. }
  325. }
  326. }
  327. /**
  328. * Add file to package.
  329. *
  330. * Get the actual source from an archive image.
  331. *
  332. * @param \PhpOffice\PhpWord\Shared\ZipArchive $zipPackage
  333. * @param string $source
  334. * @param string $target
  335. * @return void
  336. */
  337. protected function addFileToPackage($zipPackage, $source, $target)
  338. {
  339. $isArchive = strpos($source, 'zip://') !== false;
  340. $actualSource = null;
  341. if ($isArchive) {
  342. $source = substr($source, 6);
  343. list($zipFilename, $imageFilename) = explode('#', $source);
  344. $zip = new ZipArchive;
  345. if ($zip->open($zipFilename) !== false) {
  346. if ($zip->locateName($imageFilename)) {
  347. $zip->extractTo($this->getTempDir(), $imageFilename);
  348. $actualSource = $this->getTempDir() . DIRECTORY_SEPARATOR . $imageFilename;
  349. }
  350. }
  351. $zip->close();
  352. } else {
  353. $actualSource = $source;
  354. }
  355. if (!is_null($actualSource)) {
  356. $zipPackage->addFile($actualSource, $target);
  357. }
  358. }
  359. /**
  360. * Delete directory.
  361. *
  362. * @param string $dir
  363. * @return void
  364. */
  365. private function deleteDir($dir)
  366. {
  367. foreach (scandir($dir) as $file) {
  368. if ($file === '.' || $file === '..') {
  369. continue;
  370. } elseif (is_file($dir . "/" . $file)) {
  371. unlink($dir . "/" . $file);
  372. } elseif (is_dir($dir . "/" . $file)) {
  373. $this->deleteDir($dir . "/" . $file);
  374. }
  375. }
  376. rmdir($dir);
  377. }
  378. /**
  379. * Get use disk caching status
  380. *
  381. * @deprecated 0.10.0
  382. * @codeCoverageIgnore
  383. */
  384. public function getUseDiskCaching()
  385. {
  386. return $this->isUseDiskCaching();
  387. }
  388. }