export.lib.inc.php 12 KB

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