odf.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. <?php
  2. require 'zip/PclZipProxy.php';
  3. require 'zip/PhpZipProxy.php';
  4. require 'Segment.php';
  5. class OdfException extends Exception
  6. {}
  7. /**
  8. * Templating class for odt file
  9. * You need PHP 5.2 at least
  10. * You need Zip Extension or PclZip library
  11. * Encoding : ISO-8859-1
  12. * Last commit by $Author: neveldo $
  13. * Date - $Date: 2009-06-17 11:11:57 +0200 (mer., 17 juin 2009) $
  14. * SVN Revision - $Rev: 42 $
  15. * Id : $Id: odf.php 42 2009-06-17 09:11:57Z neveldo $
  16. *
  17. * @copyright GPL License 2008 - Julien Pauli - Cyril PIERRE de GEYER - Anaska (http://www.anaska.com)
  18. * @license http://www.gnu.org/copyleft/gpl.html GPL License
  19. * @version 1.3
  20. */
  21. class Odf
  22. {
  23. protected $config = array(
  24. 'ZIP_PROXY' => 'PclZipProxy',
  25. 'DELIMITER_LEFT' => '{',
  26. 'DELIMITER_RIGHT' => '}',
  27. 'PATH_TO_TMP' => null
  28. );
  29. protected $file;
  30. protected $contentXml;
  31. protected $tmpfile;
  32. protected $images = array();
  33. protected $vars = array();
  34. protected $segments = array();
  35. // MODIF YC : fix 'corrupt odt file in OpenOffice 3.2' when inserting images.
  36. // http://www.odtphp.com/forum/viewtopic.php?f=5&t=147
  37. protected $manifestXml;
  38. // /MODIF
  39. const PIXEL_TO_CM = 0.026458333;
  40. /**
  41. * Class constructor
  42. *
  43. * @param string $filename the name of the odt file
  44. * @throws OdfException
  45. */
  46. public function __construct($filename, $config = array())
  47. {
  48. if (! is_array($config)) {
  49. throw new OdfException('Configuration data must be provided as array');
  50. }
  51. foreach ($config as $configKey => $configValue) {
  52. if (array_key_exists($configKey, $this->config)) {
  53. $this->config[$configKey] = $configValue;
  54. }
  55. }
  56. if (! class_exists($this->config['ZIP_PROXY'])) {
  57. throw new OdfException($this->config['ZIP_PROXY'] . ' class not found - check your php settings');
  58. }
  59. $zipHandler = $this->config['ZIP_PROXY'];
  60. $this->file = new $zipHandler();
  61. if ($this->file->open($filename) !== true) {
  62. throw new OdfException("Error while Opening the file '$filename' - Check your odt file");
  63. }
  64. if (($this->contentXml = $this->file->getFromName('content.xml')) === false) {
  65. throw new OdfException("Nothing to parse - check that the content.xml file is correctly formed");
  66. }
  67. // MODIF YC : fix 'corrupt odt file in OpenOffice 3.2' when inserting images
  68. if (($this->manifestXml = $this->file->getFromName('META-INF/manifest.xml')) === false) {
  69. throw new OdfException("Something is wrong with META-INF/manifest.xml");
  70. }
  71. // /MODIF
  72. $this->file->close();
  73. $tmp = tempnam($this->config['PATH_TO_TMP'], md5(uniqid()));
  74. copy($filename, $tmp);
  75. $this->tmpfile = $tmp;
  76. $this->_moveRowSegments();
  77. }
  78. /**
  79. * Assing a template variable
  80. *
  81. * @param string $key name of the variable within the template
  82. * @param string $value replacement value
  83. * @param bool $encode if true, special XML characters are encoded
  84. * @throws OdfException
  85. * @return odf
  86. */
  87. public function setVars($key, $value, $encode = true, $charset = 'ISO-8859')
  88. {
  89. if (strpos($this->contentXml, $this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']) === false) {
  90. throw new OdfException("var $key not found in the document");
  91. }
  92. $value = $encode ? htmlspecialchars($value) : $value;
  93. $value = ($charset == 'ISO-8859') ? utf8_encode($value) : $value;
  94. $this->vars[$this->config['DELIMITER_LEFT'] . $key . $this->config['DELIMITER_RIGHT']] = str_replace("\n", "<text:line-break/>", $value);
  95. return $this;
  96. }
  97. /**
  98. * Assign a template variable as a picture
  99. *
  100. * @param string $key name of the variable within the template
  101. * @param string $value path to the picture
  102. * @throws OdfException
  103. * @return odf
  104. */
  105. public function setImage($key, $value)
  106. {
  107. $filename = strtok(strrchr($value, '/'), '/.');
  108. $file = substr(strrchr($value, '/'), 1);
  109. $size = @getimagesize($value);
  110. if ($size === false) {
  111. throw new OdfException("Invalid image");
  112. }
  113. list ($width, $height) = $size;
  114. $width *= self::PIXEL_TO_CM;
  115. $height *= self::PIXEL_TO_CM;
  116. $xml = <<<IMG
  117. <draw:frame draw:style-name="fr1" draw:name="$filename" text:anchor-type="char" svg:width="{$width}cm" svg:height="{$height}cm" draw:z-index="3"><draw:image xlink:href="Pictures/$file" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/></draw:frame>
  118. IMG;
  119. $this->images[$value] = $file;
  120. $this->setVars($key, $xml, false);
  121. return $this;
  122. }
  123. /**
  124. * Move segment tags for lines of tables
  125. * Called automatically within the constructor
  126. *
  127. * @return void
  128. */
  129. private function _moveRowSegments()
  130. {
  131. // Search all possible rows in the document
  132. $reg1 = "#<table:table-row[^>]*>(.*)</table:table-row>#smU";
  133. preg_match_all($reg1, $this->contentXml, $matches);
  134. for ($i = 0, $size = count($matches[0]); $i < $size; $i++) {
  135. // Check if the current row contains a segment row.*
  136. $reg2 = '#\[!--\sBEGIN\s(row.[\S]*)\s--\](.*)\[!--\sEND\s\\1\s--\]#sm';
  137. if (preg_match($reg2, $matches[0][$i], $matches2)) {
  138. $balise = str_replace('row.', '', $matches2[1]);
  139. // Move segment tags around the row
  140. $replace = array(
  141. '[!-- BEGIN ' . $matches2[1] . ' --]' => '',
  142. '[!-- END ' . $matches2[1] . ' --]' => '',
  143. '<table:table-row' => '[!-- BEGIN ' . $balise . ' --]<table:table-row',
  144. '</table:table-row>' => '</table:table-row>[!-- END ' . $balise . ' --]'
  145. );
  146. $replacedXML = str_replace(array_keys($replace), array_values($replace), $matches[0][$i]);
  147. $this->contentXml = str_replace($matches[0][$i], $replacedXML, $this->contentXml);
  148. }
  149. }
  150. }
  151. /**
  152. * Merge template variables
  153. * Called automatically for a save
  154. *
  155. * @return void
  156. */
  157. private function _parse()
  158. {
  159. $this->contentXml = str_replace(array_keys($this->vars), array_values($this->vars), $this->contentXml);
  160. }
  161. /**
  162. * Add the merged segment to the document
  163. *
  164. * @param Segment $segment
  165. * @throws OdfException
  166. * @return odf
  167. */
  168. public function mergeSegment(Segment $segment)
  169. {
  170. if (! array_key_exists($segment->getName(), $this->segments)) {
  171. throw new OdfException($segment->getName() . 'cannot be parsed, has it been set yet ?');
  172. }
  173. $string = $segment->getName();
  174. // $reg = '@<text:p[^>]*>\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]<\/text:p>@smU';
  175. $reg = '@\[!--\sBEGIN\s' . $string . '\s--\](.*)\[!--.+END\s' . $string . '\s--\]@smU';
  176. $this->contentXml = preg_replace($reg, $segment->getXmlParsed(), $this->contentXml);
  177. return $this;
  178. }
  179. /**
  180. * Display all the current template variables
  181. *
  182. * @return string
  183. */
  184. public function printVars()
  185. {
  186. return print_r('<pre>' . print_r($this->vars, true) . '</pre>', true);
  187. }
  188. /**
  189. * Display the XML content of the file from odt document
  190. * as it is at the moment
  191. *
  192. * @return string
  193. */
  194. public function __toString()
  195. {
  196. return $this->contentXml;
  197. }
  198. /**
  199. * Display loop segments declared with setSegment()
  200. *
  201. * @return string
  202. */
  203. public function printDeclaredSegments()
  204. {
  205. return '<pre>' . print_r(implode(' ', array_keys($this->segments)), true) . '</pre>';
  206. }
  207. /**
  208. * Declare a segment in order to use it in a loop
  209. *
  210. * @param string $segment
  211. * @throws OdfException
  212. * @return Segment
  213. */
  214. public function setSegment($segment)
  215. {
  216. if (array_key_exists($segment, $this->segments)) {
  217. return $this->segments[$segment];
  218. }
  219. // $reg = "#\[!--\sBEGIN\s$segment\s--\]<\/text:p>(.*)<text:p\s.*>\[!--\sEND\s$segment\s--\]#sm";
  220. $reg = "#\[!--\sBEGIN\s$segment\s--\](.*)\[!--\sEND\s$segment\s--\]#sm";
  221. if (preg_match($reg, html_entity_decode($this->contentXml), $m) == 0) {
  222. throw new OdfException("'$segment' segment not found in the document");
  223. }
  224. $this->segments[$segment] = new Segment($segment, $m[1], $this);
  225. return $this->segments[$segment];
  226. }
  227. /**
  228. * Save the odt file on the disk
  229. *
  230. * @param string $file name of the desired file
  231. * @throws OdfException
  232. * @return void
  233. */
  234. public function saveToDisk($file = null)
  235. {
  236. if ($file !== null && is_string($file)) {
  237. if (file_exists($file) && !(is_file($file) && is_writable($file))) {
  238. throw new OdfException('Permission denied : can\'t create ' . $file);
  239. }
  240. $this->_save();
  241. copy($this->tmpfile, $file);
  242. } else {
  243. $this->_save();
  244. }
  245. }
  246. /**
  247. * Internal save
  248. *
  249. * @throws OdfException
  250. * @return void
  251. */
  252. private function _save()
  253. {
  254. $this->file->open($this->tmpfile);
  255. $this->_parse();
  256. if (! $this->file->addFromString('content.xml', $this->contentXml)) {
  257. throw new OdfException('Error during file export');
  258. }
  259. foreach ($this->images as $imageKey => $imageValue) {
  260. $this->file->addFile($imageKey, 'Pictures/' . $imageValue);
  261. // MODIF YC : fix 'corrupt odt file in OpenOffice 3.2' when inserting images.
  262. $this->addImageToManifest($imageValue);
  263. // /MODIF
  264. }
  265. // MODIF YC : fix 'corrupt odt file in OpenOffice 3.2' when inserting images.
  266. if (! $this->file->addFromString('./META-INF/manifest.xml', $this->manifestXml)) {
  267. throw new OdfException('Error during file export: manifest.xml');
  268. }
  269. // /MODIF
  270. $this->file->close(); // seems to bug on windows CLI sometimes
  271. }
  272. // MODIF YC : fix 'corrupt odt file in OpenOffice 3.2' when inserting images.
  273. public function addImageToManifest($file)
  274. {
  275. $extension = explode('.', $file);
  276. $replace = '<manifest:file-entry manifest:media-type="image/'.$extension[1].'" manifest:full-path="Pictures/'.$file.'"/></manifest:manifest>';
  277. $this->manifestXml = str_replace('</manifest:manifest>', $replace, $this->manifestXml);
  278. }
  279. // /MODIF
  280. /**
  281. * Export the file as attached file by HTTP
  282. *
  283. * @param string $name (optionnal)
  284. * @throws OdfException
  285. * @return void
  286. */
  287. public function exportAsAttachedFile($name="")
  288. {
  289. $this->_save();
  290. if (headers_sent($filename, $linenum)) {
  291. throw new OdfException("headers already sent ($filename at $linenum)");
  292. }
  293. if( $name == "" )
  294. {
  295. $name = md5(uniqid()) . ".odt";
  296. }
  297. header('Content-type: application/vnd.oasis.opendocument.text');
  298. header('Content-Disposition: attachment; filename="'.$name.'"');
  299. readfile($this->tmpfile);
  300. }
  301. /**
  302. * Returns a variable of configuration
  303. *
  304. * @return string The requested variable of configuration
  305. */
  306. public function getConfig($configKey)
  307. {
  308. if (array_key_exists($configKey, $this->config)) {
  309. return $this->config[$configKey];
  310. }
  311. return false;
  312. }
  313. /**
  314. * Returns the temporary working file
  315. *
  316. * @return string le chemin vers le fichier temporaire de travail
  317. */
  318. public function getTmpfile()
  319. {
  320. return $this->tmpfile;
  321. }
  322. /**
  323. * Delete the temporary file when the object is destroyed
  324. */
  325. public function __destruct() {
  326. if (file_exists($this->tmpfile)) {
  327. unlink($this->tmpfile);
  328. }
  329. }
  330. }
  331. ?>