excelbulkexport.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. <?php
  2. // Copyright (C) 2015-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Bulk export: Excel (xlsx) export
  20. *
  21. * @copyright Copyright (C) 2015-2016 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once(APPROOT.'application/xlsxwriter.class.php');
  25. class ExcelBulkExport extends TabularBulkExport
  26. {
  27. protected $sData;
  28. public function __construct()
  29. {
  30. parent::__construct();
  31. $this->aStatusInfo['status'] = 'not_started';
  32. $this->aStatusInfo['position'] = 0;
  33. }
  34. public function Cleanup()
  35. {
  36. @unlink($this->aStatusInfo['tmp_file']);
  37. parent::Cleanup();
  38. }
  39. public function DisplayUsage(Page $oP)
  40. {
  41. $oP->p(" * xlsx format options:");
  42. $oP->p(" *\tfields: the comma separated list of field codes to export (e.g: name,org_id,service_name...).");
  43. $oP->p(" *\tformatted_text: set to 1 to export case logs and formatted text fields with their HTML markup. Default is 0 (= plain text)");
  44. $oP->p(" *\tdate_format: the format to use when exporting date and time fields (default = the SQL format). e.g. 'Y-m-d H:i:s'");
  45. }
  46. public function ReadParameters()
  47. {
  48. parent::ReadParameters();
  49. $this->aStatusInfo['formatted_text'] = (bool)utils::ReadParam('formatted_text', 0, true);
  50. $sDateFormatRadio = utils::ReadParam('excel_date_format_radio', '');
  51. switch($sDateFormatRadio)
  52. {
  53. case 'default':
  54. // Export from the UI => format = same as is the UI
  55. $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
  56. break;
  57. case 'custom':
  58. // Custom format specified from the UI
  59. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
  60. break;
  61. default:
  62. // Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
  63. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
  64. }
  65. }
  66. public function EnumFormParts()
  67. {
  68. return array_merge(parent::EnumFormParts(), array('xlsx_options' => array('formatted_text') ,'interactive_fields_xlsx' => array('interactive_fields_xlsx')));
  69. }
  70. public function DisplayFormPart(WebPage $oP, $sPartId)
  71. {
  72. switch($sPartId)
  73. {
  74. case 'interactive_fields_xlsx':
  75. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_xlsx');
  76. break;
  77. case 'xlsx_options':
  78. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:XLSXOptions').'</legend>');
  79. $oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">');
  80. $sChecked = (utils::ReadParam('formatted_text', 0) == 1) ? ' checked ' : '';
  81. $oP->add('<h3>'.Dict::S('Core:BulkExport:TextFormat').'</h3>');
  82. $oP->add('<input type="checkbox" id="xlsx_formatted_text" name="formatted_text" value="1"'.$sChecked.'><label for="xlsx_formatted_text"> '.Dict::S('Core:BulkExport:OptionFormattedText').'</label>');
  83. $oP->add('</td><td style="vertical-align:top">');
  84. $sDateTimeFormat = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
  85. $sDefaultChecked = ($sDateTimeFormat == (string)AttributeDateTime::GetFormat()) ? ' checked' : '';
  86. $sCustomChecked = ($sDateTimeFormat !== (string)AttributeDateTime::GetFormat()) ? ' checked' : '';
  87. $oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
  88. $sDefaultFormat = htmlentities((string)AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
  89. $sExample = htmlentities(date((string)AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
  90. $oP->add('<input type="radio" id="excel_date_time_format_default" name="excel_date_format_radio" value="default"'.$sDefaultChecked.'><label for="excel_date_time_format_default"> '.Dict::Format('Core:BulkExport:DateTimeFormatDefault_Example', $sDefaultFormat, $sExample).'</label><br/>');
  91. $sFormatInput = '<input type="text" size="15" name="date_format" id="excel_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
  92. $oP->add('<input type="radio" id="excel_date_time_format_custom" name="excel_date_format_radio" value="custom"'.$sCustomChecked.'><label for="excel_date_time_format_custom"> '.Dict::Format('Core:BulkExport:DateTimeFormatCustom_Format', $sFormatInput).'</label>');
  93. $oP->add('</td></tr></table>');
  94. $oP->add('</fieldset>');
  95. $sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
  96. $oP->add_ready_script(
  97. <<<EOF
  98. $('#excel_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
  99. $('#form_part_xlsx_options').on('preview_updated', function() { FormatDatesInPreview('excel', 'xlsx'); });
  100. $('#excel_custom_date_time_format').on('click', function() { $('#excel_date_time_format_custom').prop('checked', true); FormatDatesInPreview('excel', 'xlsx'); }).on('keyup', function() { FormatDatesInPreview('excel', 'xlsx'); });
  101. EOF
  102. );
  103. break;
  104. default:
  105. return parent:: DisplayFormPart($oP, $sPartId);
  106. }
  107. }
  108. protected function SuggestField($sClass, $sAttCode)
  109. {
  110. switch($sAttCode)
  111. {
  112. case 'id': // replace 'id' by 'friendlyname'
  113. $sAttCode = 'friendlyname';
  114. break;
  115. default:
  116. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  117. if ($oAttDef instanceof AttributeExternalKey)
  118. {
  119. $sAttCode .= '_friendlyname';
  120. }
  121. }
  122. return parent::SuggestField($sClass, $sAttCode);
  123. }
  124. protected function GetSampleData($oObj, $sAttCode)
  125. {
  126. if ($sAttCode != 'id')
  127. {
  128. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  129. if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
  130. {
  131. $sClass = (get_class($oAttDef) == 'AttributeDateTime') ? 'user-formatted-date-time' : 'user-formatted-date';
  132. return '<div class="'.$sClass.'" data-date="'.$oObj->Get($sAttCode).'">'.htmlentities($oAttDef->GetEditValue($oObj->Get($sAttCode), $oObj), ENT_QUOTES, 'UTF-8').'</div>';
  133. }
  134. }
  135. return '<div class="text-preview">'.htmlentities($this->GetValue($oObj, $sAttCode), ENT_QUOTES, 'UTF-8').'</div>';
  136. }
  137. protected function GetValue($oObj, $sAttCode)
  138. {
  139. switch($sAttCode)
  140. {
  141. case 'id':
  142. $sRet = $oObj->GetKey();
  143. break;
  144. default:
  145. $value = $oObj->Get($sAttCode);
  146. if ($value instanceOf ormCaseLog)
  147. {
  148. if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
  149. {
  150. $sText = $value->GetText();
  151. }
  152. else
  153. {
  154. $sText = $value->GetAsPlainText();
  155. }
  156. // Extract the case log as text and remove the "===" which make Excel think that the cell contains a formula the next time you edit it!
  157. $sRet = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $sText));
  158. }
  159. else if ($value instanceOf DBObjectSet)
  160. {
  161. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  162. $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
  163. }
  164. else
  165. {
  166. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  167. if ($oAttDef instanceof AttributeDateTime)
  168. {
  169. // Date and times are formatted using the ISO encoding, not the localized format
  170. if ($oAttDef->IsNull($value))
  171. {
  172. // NOt a valid date
  173. $sRet = '';
  174. }
  175. else
  176. {
  177. $sRet = $value;
  178. }
  179. }
  180. else if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
  181. {
  182. $sRet = $oAttDef->GetEditValue($value, $oObj);
  183. }
  184. else
  185. {
  186. $sRet = $oAttDef->GetAsPlainText($value, $oObj);
  187. }
  188. }
  189. }
  190. return $sRet;
  191. }
  192. public function GetHeader()
  193. {
  194. $oSet = new DBObjectSet($this->oSearch);
  195. $this->aStatusInfo['status'] = 'retrieving';
  196. $this->aStatusInfo['tmp_file'] = $this->MakeTmpFile('data');
  197. $this->aStatusInfo['position'] = 0;
  198. $this->aStatusInfo['total'] = $oSet->Count();
  199. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  200. {
  201. $sExtendedAttCode = $aFieldSpec['sFieldSpec'];
  202. $sAttCode = $aFieldSpec['sAttCode'];
  203. $sColLabel = $aFieldSpec['sColLabel'];
  204. switch($sAttCode)
  205. {
  206. case 'id':
  207. $sType = '0';
  208. break;
  209. default:
  210. $oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
  211. $sType = 'string';
  212. if($oAttDef instanceof AttributeDate)
  213. {
  214. $sType = 'date';
  215. }
  216. else if($oAttDef instanceof AttributeDateTime)
  217. {
  218. $sType = 'datetime';
  219. }
  220. }
  221. $aTableHeaders[] = array('label' => $sColLabel, 'type' => $sType);
  222. }
  223. $sRow = json_encode($aTableHeaders);
  224. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
  225. if ($hFile === false)
  226. {
  227. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
  228. }
  229. fwrite($hFile, $sRow."\n");
  230. fclose($hFile);
  231. return '';
  232. }
  233. public function GetNextChunk(&$aStatus)
  234. {
  235. $sRetCode = 'run';
  236. $iPercentage = 0;
  237. $hFile = fopen($this->aStatusInfo['tmp_file'], 'ab');
  238. $oSet = new DBObjectSet($this->oSearch);
  239. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  240. $this->OptimizeColumnLoad($oSet);
  241. $iCount = 0;
  242. $iPreviousTimeLimit = ini_get('max_execution_time');
  243. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  244. while($aRow = $oSet->FetchAssoc())
  245. {
  246. set_time_limit($iLoopTimeLimit);
  247. $aData = array();
  248. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  249. {
  250. $sAlias = $aFieldSpec['sAlias'];
  251. $sAttCode = $aFieldSpec['sAttCode'];
  252. $oObj = $aRow[$sAlias];
  253. $sField = '';
  254. if ($oObj)
  255. {
  256. $sField = $this->GetValue($oObj, $sAttCode);
  257. }
  258. $aData[] = $sField;
  259. }
  260. fwrite($hFile, json_encode($aData)."\n");
  261. $iCount++;
  262. }
  263. set_time_limit($iPreviousTimeLimit);
  264. $this->aStatusInfo['position'] += $this->iChunkSize;
  265. if ($this->aStatusInfo['total'] == 0)
  266. {
  267. $iPercentage = 100;
  268. $sRetCode = 'done'; // Next phase (GetFooter) will be to build the xlsx file
  269. }
  270. else
  271. {
  272. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  273. }
  274. if ($iCount < $this->iChunkSize)
  275. {
  276. $sRetCode = 'done';
  277. }
  278. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  279. return ''; // The actual XLSX file is built in GetFooter();
  280. }
  281. public function GetFooter()
  282. {
  283. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'rb');
  284. if ($hFile === false)
  285. {
  286. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for reading.');
  287. }
  288. $sHeaders = fgets($hFile);
  289. $aHeaders = json_decode($sHeaders, true);
  290. $aData = array();
  291. while($sLine = fgets($hFile))
  292. {
  293. $aRow = json_decode($sLine);
  294. $aData[] = $aRow;
  295. }
  296. fclose($hFile);
  297. $fStartExcel = microtime(true);
  298. $writer = new XLSXWriter();
  299. $oDateTimeFormat = new DateTimeFormat($this->aStatusInfo['date_format']);
  300. $writer->setDateTimeFormat($oDateTimeFormat->ToExcel());
  301. $oDateFormat = new DateTimeFormat($oDateTimeFormat->ToDateFormat());
  302. $writer->setDateFormat($oDateFormat->ToExcel());
  303. $writer->setAuthor(UserRights::GetUserFriendlyName());
  304. $aHeaderTypes = array();
  305. $aHeaderNames = array();
  306. foreach($aHeaders as $Header)
  307. {
  308. $aHeaderNames[] = $Header['label'];
  309. $aHeaderTypes[] = $Header['type'];
  310. }
  311. $writer->writeSheet($aData,'Sheet1', $aHeaderTypes, $aHeaderNames);
  312. $fExcelTime = microtime(true) - $fStartExcel;
  313. //$this->aStatistics['excel_build_duration'] = $fExcelTime;
  314. $fTime = microtime(true);
  315. $data = $writer->writeToString();
  316. $fExcelSaveTime = microtime(true) - $fTime;
  317. //$this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
  318. @unlink($this->aStatusInfo['tmp_file']);
  319. return $data;
  320. }
  321. public function GetMimeType()
  322. {
  323. return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  324. }
  325. public function GetFileExtension()
  326. {
  327. return 'xlsx';
  328. }
  329. public function GetSupportedFormats()
  330. {
  331. return array('xlsx' => Dict::S('Core:BulkExport:XLSXFormat'));
  332. }
  333. }