export.lib.inc.php 12 KB

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