export.lib.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. /* See license terms in /license.txt */
  3. use Chamilo\CoreBundle\Component\Editor\Connector;
  4. use Chamilo\CoreBundle\Component\Filesystem\Data;
  5. use Ddeboer\DataImport\Writer\CsvWriter;
  6. use Ddeboer\DataImport\Writer\ExcelWriter;
  7. use MediaAlchemyst\Alchemyst;
  8. use MediaAlchemyst\DriversContainer;
  9. use Neutron\TemporaryFilesystem\Manager;
  10. use Neutron\TemporaryFilesystem\TemporaryFilesystem;
  11. use Symfony\Component\Filesystem\Filesystem;
  12. /**
  13. * This is the export library for Chamilo.
  14. * Include/require it in your code to use its functionality.
  15. * Several functions below are adaptations from functions distributed by www.nexen.net.
  16. *
  17. * @package chamilo.library
  18. */
  19. class Export
  20. {
  21. /**
  22. * Constructor.
  23. */
  24. public function __construct()
  25. {
  26. }
  27. /**
  28. * Export tabular data to CSV-file.
  29. *
  30. * @param array $data
  31. * @param string $filename
  32. * @param bool $writeOnly Whether to only write on disk or also send for download
  33. * @param string $enclosure
  34. *
  35. * @return mixed csv raw data | false if no data to export | string file path if success in $writeOnly mode
  36. */
  37. public static function arrayToCsv($data, $filename = 'export', $writeOnly = false, $enclosure = '"')
  38. {
  39. if (empty($data)) {
  40. return false;
  41. }
  42. $enclosure = !empty($enclosure) ? $enclosure : '"';
  43. $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.csv';
  44. $stream = fopen($filePath, 'w');
  45. $writer = new CsvWriter(';', $enclosure, $stream, true);
  46. $writer->prepare();
  47. foreach ($data as $item) {
  48. if (empty($item)) {
  49. $writer->writeItem([]);
  50. continue;
  51. }
  52. $item = array_map('trim', $item);
  53. $writer->writeItem($item);
  54. }
  55. $writer->finish();
  56. if (!$writeOnly) {
  57. DocumentManager::file_send_for_download($filePath, true, $filename.'.csv');
  58. exit;
  59. }
  60. return $filePath;
  61. }
  62. /**
  63. * Export tabular data to XLS-file.
  64. *
  65. * @param array $data
  66. * @param string $filename
  67. */
  68. public static function arrayToXls($data, $filename = 'export', $encoding = 'utf-8')
  69. {
  70. $filePath = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.xlsx';
  71. $file = new \SplFileObject($filePath, 'w');
  72. $writer = new ExcelWriter($file);
  73. $writer->prepare();
  74. foreach ($data as $row) {
  75. $writer->writeItem($row);
  76. }
  77. $writer->finish();
  78. DocumentManager::file_send_for_download($filePath, true, $filename.'.xlsx');
  79. exit;
  80. }
  81. /**
  82. * Export tabular data to XLS-file (as html table).
  83. *
  84. * @param array $data
  85. * @param string $filename
  86. */
  87. public static function export_table_xls_html($data, $filename = 'export', $encoding = 'utf-8')
  88. {
  89. $file = api_get_path(SYS_ARCHIVE_PATH).uniqid('').'.xls';
  90. $handle = fopen($file, 'a+');
  91. $systemEncoding = api_get_system_encoding();
  92. fwrite($handle, '<!DOCTYPE html><html><meta http-equiv="Content-Type" content="text/html" charset="'.$encoding.'" /><body><table>');
  93. foreach ($data as $id => $row) {
  94. foreach ($row as $id2 => $row2) {
  95. $data[$id][$id2] = api_htmlentities($row2);
  96. }
  97. }
  98. foreach ($data as $row) {
  99. $string = implode("</td><td>", $row);
  100. $string = '<tr><td>'.$string.'</td></tr>';
  101. if ($encoding != 'utf-8') {
  102. $string = api_convert_encoding($string, $encoding, $systemEncoding);
  103. }
  104. fwrite($handle, $string."\n");
  105. }
  106. fwrite($handle, '</table></body></html>');
  107. fclose($handle);
  108. DocumentManager::file_send_for_download($file, true, $filename.'.xls');
  109. exit;
  110. }
  111. /**
  112. * Export tabular data to XML-file.
  113. *
  114. * @param array Simple array of data to put in XML
  115. * @param string Name of file to be given to the user
  116. * @param string Name of common tag to place each line in
  117. * @param string Name of the root element. A root element should always be given.
  118. * @param string Encoding in which the data is provided
  119. */
  120. public static function arrayToXml(
  121. $data,
  122. $filename = 'export',
  123. $item_tagname = 'item',
  124. $wrapper_tagname = null,
  125. $encoding = null
  126. ) {
  127. if (empty($encoding)) {
  128. $encoding = api_get_system_encoding();
  129. }
  130. $file = api_get_path(SYS_ARCHIVE_PATH).'/'.uniqid('').'.xml';
  131. $handle = fopen($file, 'a+');
  132. fwrite($handle, '<?xml version="1.0" encoding="'.$encoding.'"?>'."\n");
  133. if (!is_null($wrapper_tagname)) {
  134. fwrite($handle, "\t".'<'.$wrapper_tagname.'>'."\n");
  135. }
  136. foreach ($data as $row) {
  137. fwrite($handle, '<'.$item_tagname.'>'."\n");
  138. foreach ($row as $key => $value) {
  139. fwrite($handle, "\t\t".'<'.$key.'>'.$value.'</'.$key.'>'."\n");
  140. }
  141. fwrite($handle, "\t".'</'.$item_tagname.'>'."\n");
  142. }
  143. if (!is_null($wrapper_tagname)) {
  144. fwrite($handle, '</'.$wrapper_tagname.'>'."\n");
  145. }
  146. fclose($handle);
  147. DocumentManager::file_send_for_download($file, true, $filename.'.xml');
  148. exit;
  149. }
  150. /**
  151. * Export hierarchical tabular data to XML-file.
  152. *
  153. * @param array Hierarchical array of data to put in XML, each element presenting a 'name' and a 'value' property
  154. * @param string Name of file to be given to the user
  155. * @param string Name of common tag to place each line in
  156. * @param string Name of the root element. A root element should always be given.
  157. * @param string Encoding in which the data is provided
  158. */
  159. public static function export_complex_table_xml(
  160. $data,
  161. $filename = 'export',
  162. $wrapper_tagname,
  163. $encoding = 'ISO-8859-1'
  164. ) {
  165. $file = api_get_path(SYS_ARCHIVE_PATH).'/'.uniqid('').'.xml';
  166. $handle = fopen($file, 'a+');
  167. fwrite($handle, '<?xml version="1.0" encoding="'.$encoding.'"?>'."\n");
  168. if (!is_null($wrapper_tagname)) {
  169. fwrite($handle, '<'.$wrapper_tagname.'>');
  170. }
  171. $s = self::_export_complex_table_xml_helper($data);
  172. fwrite($handle, $s);
  173. if (!is_null($wrapper_tagname)) {
  174. fwrite($handle, '</'.$wrapper_tagname.'>'."\n");
  175. }
  176. fclose($handle);
  177. DocumentManager::file_send_for_download($file, true, $filename.'.xml');
  178. return false;
  179. }
  180. /**
  181. * Helper for the hierarchical XML exporter.
  182. *
  183. * @param array Hierarhical array composed of elements of type ('name'=>'xyz','value'=>'...')
  184. * @param int Level of recursivity. Allows the XML to be finely presented
  185. *
  186. * @return string The XML string to be inserted into the root element
  187. */
  188. public static function _export_complex_table_xml_helper($data, $level = 1)
  189. {
  190. if (count($data) < 1) {
  191. return '';
  192. }
  193. $string = '';
  194. foreach ($data as $row) {
  195. $string .= "\n".str_repeat("\t", $level).'<'.$row['name'].'>';
  196. if (is_array($row['value'])) {
  197. $string .= self::_export_complex_table_xml_helper($row['value'], $level + 1)."\n";
  198. $string .= str_repeat("\t", $level).'</'.$row['name'].'>';
  199. } else {
  200. $string .= $row['value'];
  201. $string .= '</'.$row['name'].'>';
  202. }
  203. }
  204. return $string;
  205. }
  206. /**
  207. * @param array $data table to be read with the HTML_table class
  208. */
  209. public static function export_table_pdf($data, $params = [])
  210. {
  211. $table_html = self::convert_array_to_html($data, $params);
  212. $params['format'] = isset($params['format']) ? $params['format'] : 'A4';
  213. $params['orientation'] = isset($params['orientation']) ? $params['orientation'] : 'P';
  214. $pdf = new PDF($params['format'], $params['orientation'], $params);
  215. $pdf->html_to_pdf_with_template($table_html);
  216. }
  217. /**
  218. * @param string $html
  219. * @param array $params
  220. */
  221. public static function export_html_to_pdf($html, $params = [])
  222. {
  223. $params['format'] = isset($params['format']) ? $params['format'] : 'A4';
  224. $params['orientation'] = isset($params['orientation']) ? $params['orientation'] : 'P';
  225. $pdf = new PDF($params['format'], $params['orientation'], $params);
  226. $pdf->html_to_pdf_with_template($html);
  227. }
  228. /**
  229. * @param array $data
  230. * @param array $params
  231. *
  232. * @return string
  233. */
  234. public static function convert_array_to_html($data, $params = [])
  235. {
  236. $headers = $data[0];
  237. unset($data[0]);
  238. $header_attributes = isset($params['header_attributes']) ? $params['header_attributes'] : [];
  239. $table = new HTML_Table(['class' => 'data_table', 'repeat_header' => '1']);
  240. $row = 0;
  241. $column = 0;
  242. foreach ($headers as $header) {
  243. $table->setHeaderContents($row, $column, $header);
  244. $attributes = [];
  245. if (isset($header_attributes) && isset($header_attributes[$column])) {
  246. $attributes = $header_attributes[$column];
  247. }
  248. if (!empty($attributes)) {
  249. $table->updateCellAttributes($row, $column, $attributes);
  250. }
  251. $column++;
  252. }
  253. $row++;
  254. foreach ($data as &$printable_data_row) {
  255. $column = 0;
  256. foreach ($printable_data_row as &$printable_data_cell) {
  257. $table->setCellContents($row, $column, $printable_data_cell);
  258. //$table->updateCellAttributes($row, $column, $atributes);
  259. $column++;
  260. }
  261. $table->updateRowAttributes($row, $row % 2 ? 'class="row_even"' : 'class="row_odd"', true);
  262. $row++;
  263. }
  264. $table_tp_html = $table->toHtml();
  265. return $table_tp_html;
  266. }
  267. /**
  268. * Export HTML content in a ODF document.
  269. *
  270. * @param string $html
  271. * @param string $name
  272. * @param string $format
  273. *
  274. * @return bool
  275. */
  276. public static function htmlToOdt($html, $name, $format = 'odt')
  277. {
  278. $unoconv = api_get_configuration_value('unoconv.binaries');
  279. if (empty($unoconv)) {
  280. return false;
  281. }
  282. if (!empty($html)) {
  283. $fs = new Filesystem();
  284. $paths = [
  285. 'root_sys' => api_get_path(SYS_PATH),
  286. 'path.temp' => api_get_path(SYS_ARCHIVE_PATH),
  287. ];
  288. $connector = new Connector();
  289. $drivers = new DriversContainer();
  290. $drivers['configuration'] = [
  291. 'unoconv.binaries' => $unoconv,
  292. 'unoconv.timeout' => 60,
  293. ];
  294. $tempFilesystem = TemporaryFilesystem::create();
  295. $manager = new Manager($tempFilesystem, $fs);
  296. $alchemyst = new Alchemyst($drivers, $manager);
  297. $dataFileSystem = new Data($paths, $fs, $connector, $alchemyst);
  298. $content = $dataFileSystem->convertRelativeToAbsoluteUrl($html);
  299. $filePath = $dataFileSystem->putContentInTempFile(
  300. $content,
  301. api_replace_dangerous_char($name),
  302. 'html'
  303. );
  304. $try = true;
  305. while ($try) {
  306. try {
  307. $convertedFile = $dataFileSystem->transcode(
  308. $filePath,
  309. $format
  310. );
  311. $try = false;
  312. DocumentManager::file_send_for_download(
  313. $convertedFile,
  314. false,
  315. $name.'.'.$format
  316. );
  317. } catch (Exception $e) {
  318. // error_log($e->getMessage());
  319. }
  320. }
  321. }
  322. }
  323. }