excelbulkexport.class.inc.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 format used in the user interface). Example: 'm/d/Y 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('date_format_radio', 'custom');
  51. if ($sDateFormatRadio == 'default')
  52. {
  53. $this->aStatusInfo['date_format'] = AttributeDateTime::GetFormat();
  54. }
  55. else
  56. {
  57. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
  58. }
  59. }
  60. public function EnumFormParts()
  61. {
  62. return array_merge(parent::EnumFormParts(), array('xlsx_options' => array('formatted_text') ,'interactive_fields_xlsx' => array('interactive_fields_xlsx')));
  63. }
  64. public function DisplayFormPart(WebPage $oP, $sPartId)
  65. {
  66. switch($sPartId)
  67. {
  68. case 'interactive_fields_xlsx':
  69. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_xlsx');
  70. break;
  71. case 'xlsx_options':
  72. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:XLSXOptions').'</legend>');
  73. $oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">');
  74. $sChecked = (utils::ReadParam('formatted_text', 0) == 1) ? ' checked ' : '';
  75. $oP->add('<h3>'.Dict::S('Core:BulkExport:TextFormat').'</h3>');
  76. $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>');
  77. $oP->add('</td><td style="vertical-align:top">');
  78. $sDateTimeFormat = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
  79. $sDefaultChecked = ($sDateTimeFormat == AttributeDateTime::GetFormat()) ? ' checked' : '';
  80. $sCustomChecked = ($sDateTimeFormat !== AttributeDateTime::GetFormat()) ? ' checked' : '';
  81. $oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
  82. $sDefaultFormat = htmlentities(AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
  83. $sExample = htmlentities(date(AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
  84. $oP->add('<input type="radio" id="excel_date_time_format_default" name="date_format_radio" value="default"'.$sDefaultChecked.'><label for="excel_date_time_format_default"> '.Dict::Format('Core:BulkExport:DateTimeFormatDefault_Example', $sDefaultFormat, $sExample).'</label><br/>');
  85. $sFormatInput = '<input type="text" size="15" name="date_format" id="excel_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
  86. $oP->add('<input type="radio" id="excel_date_time_format_custom" name="date_format_radio" value="custom"'.$sCustomChecked.'><label for="excel_date_time_format_custom"> '.Dict::Format('Core:BulkExport:DateTimeFormatCustom_Format', $sFormatInput).'</label>');
  87. $oP->add('</td></tr></table>');
  88. $oP->add('</fieldset>');
  89. $sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
  90. $oP->add_ready_script(
  91. <<<EOF
  92. $('#excel_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
  93. $('#excel_custom_date_time_format').on('click', function() { $('#excel_date_time_format_custom').prop('checked', true); });
  94. EOF
  95. );
  96. break;
  97. default:
  98. return parent:: DisplayFormPart($oP, $sPartId);
  99. }
  100. }
  101. protected function SuggestField($sClass, $sAttCode)
  102. {
  103. switch($sAttCode)
  104. {
  105. case 'id': // replace 'id' by 'friendlyname'
  106. $sAttCode = 'friendlyname';
  107. break;
  108. default:
  109. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  110. if ($oAttDef instanceof AttributeExternalKey)
  111. {
  112. $sAttCode .= '_friendlyname';
  113. }
  114. }
  115. return parent::SuggestField($sClass, $sAttCode);
  116. }
  117. protected function GetSampleData($oObj, $sAttCode)
  118. {
  119. return '<div class="text-preview">'.htmlentities($this->GetValue($oObj, $sAttCode), ENT_QUOTES, 'UTF-8').'</div>';
  120. }
  121. protected function GetValue($oObj, $sAttCode)
  122. {
  123. switch($sAttCode)
  124. {
  125. case 'id':
  126. $sRet = $oObj->GetKey();
  127. break;
  128. default:
  129. $value = $oObj->Get($sAttCode);
  130. if ($value instanceOf ormCaseLog)
  131. {
  132. if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
  133. {
  134. $sText = $value->GetText();
  135. }
  136. else
  137. {
  138. $sText = $value->GetAsPlainText();
  139. }
  140. // 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!
  141. $sRet = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $sText));
  142. }
  143. else if ($value instanceOf DBObjectSet)
  144. {
  145. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  146. $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
  147. }
  148. else
  149. {
  150. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  151. if ($oAttDef instanceof AttributeDateTime)
  152. {
  153. // Date and times are formatted using the ISO encoding, not the localized format
  154. $sRet = $value;
  155. }
  156. else if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
  157. {
  158. $sRet = $oAttDef->GetEditValue($value, $oObj);
  159. }
  160. else
  161. {
  162. $sRet = $oAttDef->GetAsPlainText($value, $oObj);
  163. }
  164. }
  165. }
  166. return $sRet;
  167. }
  168. public function GetHeader()
  169. {
  170. $oSet = new DBObjectSet($this->oSearch);
  171. $this->aStatusInfo['status'] = 'retrieving';
  172. $this->aStatusInfo['tmp_file'] = $this->MakeTmpFile('data');
  173. $this->aStatusInfo['position'] = 0;
  174. $this->aStatusInfo['total'] = $oSet->Count();
  175. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  176. {
  177. $sExtendedAttCode = $aFieldSpec['sFieldSpec'];
  178. $sAttCode = $aFieldSpec['sAttCode'];
  179. $sColLabel = $aFieldSpec['sColLabel'];
  180. switch($sAttCode)
  181. {
  182. case 'id':
  183. $sType = '0';
  184. break;
  185. default:
  186. $oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
  187. $sType = 'string';
  188. if($oAttDef instanceof AttributeDateTime)
  189. {
  190. $sType = 'datetime';
  191. }
  192. }
  193. $aTableHeaders[] = array('label' => $sColLabel, 'type' => $sType);
  194. }
  195. $sRow = json_encode($aTableHeaders);
  196. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
  197. if ($hFile === false)
  198. {
  199. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
  200. }
  201. fwrite($hFile, $sRow."\n");
  202. fclose($hFile);
  203. return '';
  204. }
  205. public function GetNextChunk(&$aStatus)
  206. {
  207. $sRetCode = 'run';
  208. $iPercentage = 0;
  209. $hFile = fopen($this->aStatusInfo['tmp_file'], 'ab');
  210. $oSet = new DBObjectSet($this->oSearch);
  211. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  212. $this->OptimizeColumnLoad($oSet);
  213. $iCount = 0;
  214. $iPreviousTimeLimit = ini_get('max_execution_time');
  215. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  216. while($aRow = $oSet->FetchAssoc())
  217. {
  218. set_time_limit($iLoopTimeLimit);
  219. $aData = array();
  220. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  221. {
  222. $sAlias = $aFieldSpec['sAlias'];
  223. $sAttCode = $aFieldSpec['sAttCode'];
  224. $oObj = $aRow[$sAlias];
  225. $sField = '';
  226. if ($oObj)
  227. {
  228. $sField = $this->GetValue($oObj, $sAttCode);
  229. }
  230. $aData[] = $sField;
  231. }
  232. fwrite($hFile, json_encode($aData)."\n");
  233. $iCount++;
  234. }
  235. set_time_limit($iPreviousTimeLimit);
  236. $this->aStatusInfo['position'] += $this->iChunkSize;
  237. if ($this->aStatusInfo['total'] == 0)
  238. {
  239. $iPercentage = 100;
  240. $sRetCode = 'done'; // Next phase (GetFooter) will be to build the xlsx file
  241. }
  242. else
  243. {
  244. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  245. }
  246. if ($iCount < $this->iChunkSize)
  247. {
  248. $sRetCode = 'done';
  249. }
  250. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  251. return ''; // The actual XLSX file is built in GetFooter();
  252. }
  253. public function GetFooter()
  254. {
  255. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'rb');
  256. if ($hFile === false)
  257. {
  258. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for reading.');
  259. }
  260. $sHeaders = fgets($hFile);
  261. $aHeaders = json_decode($sHeaders, true);
  262. $aData = array();
  263. while($sLine = fgets($hFile))
  264. {
  265. $aRow = json_decode($sLine);
  266. $aData[] = $aRow;
  267. }
  268. fclose($hFile);
  269. $fStartExcel = microtime(true);
  270. $writer = new XLSXWriter();
  271. $writer->setDateTimeFormat(AttributeDateTime::GetExcelFormat($this->aStatusInfo['date_format']));
  272. $writer->setAuthor(UserRights::GetUserFriendlyName());
  273. $aHeaderTypes = array();
  274. $aHeaderNames = array();
  275. foreach($aHeaders as $Header)
  276. {
  277. $aHeaderNames[] = $Header['label'];
  278. $aHeaderTypes[] = $Header['type'];
  279. }
  280. $writer->writeSheet($aData,'Sheet1', $aHeaderTypes, $aHeaderNames);
  281. $fExcelTime = microtime(true) - $fStartExcel;
  282. //$this->aStatistics['excel_build_duration'] = $fExcelTime;
  283. $fTime = microtime(true);
  284. $data = $writer->writeToString();
  285. $fExcelSaveTime = microtime(true) - $fTime;
  286. //$this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
  287. @unlink($this->aStatusInfo['tmp_file']);
  288. return $data;
  289. }
  290. public function GetMimeType()
  291. {
  292. return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  293. }
  294. public function GetFileExtension()
  295. {
  296. return 'xlsx';
  297. }
  298. public function GetSupportedFormats()
  299. {
  300. return array('xlsx' => Dict::S('Core:BulkExport:XLSXFormat'));
  301. }
  302. }