export.lib.inc.php 12 KB

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