excelbulkexport.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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('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="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="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. $('#excel_custom_date_time_format').on('click', function() { $('#excel_date_time_format_custom').prop('checked', true); });
  100. EOF
  101. );
  102. break;
  103. default:
  104. return parent:: DisplayFormPart($oP, $sPartId);
  105. }
  106. }
  107. protected function SuggestField($sClass, $sAttCode)
  108. {
  109. switch($sAttCode)
  110. {
  111. case 'id': // replace 'id' by 'friendlyname'
  112. $sAttCode = 'friendlyname';
  113. break;
  114. default:
  115. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  116. if ($oAttDef instanceof AttributeExternalKey)
  117. {
  118. $sAttCode .= '_friendlyname';
  119. }
  120. }
  121. return parent::SuggestField($sClass, $sAttCode);
  122. }
  123. protected function GetSampleData($oObj, $sAttCode)
  124. {
  125. return '<div class="text-preview">'.htmlentities($this->GetValue($oObj, $sAttCode), ENT_QUOTES, 'UTF-8').'</div>';
  126. }
  127. protected function GetValue($oObj, $sAttCode)
  128. {
  129. switch($sAttCode)
  130. {
  131. case 'id':
  132. $sRet = $oObj->GetKey();
  133. break;
  134. default:
  135. $value = $oObj->Get($sAttCode);
  136. if ($value instanceOf ormCaseLog)
  137. {
  138. if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
  139. {
  140. $sText = $value->GetText();
  141. }
  142. else
  143. {
  144. $sText = $value->GetAsPlainText();
  145. }
  146. // 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!
  147. $sRet = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $sText));
  148. }
  149. else if ($value instanceOf DBObjectSet)
  150. {
  151. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  152. $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
  153. }
  154. else
  155. {
  156. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  157. if ($oAttDef instanceof AttributeDateTime)
  158. {
  159. // Date and times are formatted using the ISO encoding, not the localized format
  160. $sRet = $value;
  161. }
  162. else if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
  163. {
  164. $sRet = $oAttDef->GetEditValue($value, $oObj);
  165. }
  166. else
  167. {
  168. $sRet = $oAttDef->GetAsPlainText($value, $oObj);
  169. }
  170. }
  171. }
  172. return $sRet;
  173. }
  174. public function GetHeader()
  175. {
  176. $oSet = new DBObjectSet($this->oSearch);
  177. $this->aStatusInfo['status'] = 'retrieving';
  178. $this->aStatusInfo['tmp_file'] = $this->MakeTmpFile('data');
  179. $this->aStatusInfo['position'] = 0;
  180. $this->aStatusInfo['total'] = $oSet->Count();
  181. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  182. {
  183. $sExtendedAttCode = $aFieldSpec['sFieldSpec'];
  184. $sAttCode = $aFieldSpec['sAttCode'];
  185. $sColLabel = $aFieldSpec['sColLabel'];
  186. switch($sAttCode)
  187. {
  188. case 'id':
  189. $sType = '0';
  190. break;
  191. default:
  192. $oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
  193. $sType = 'string';
  194. if($oAttDef instanceof AttributeDateTime)
  195. {
  196. $sType = 'datetime';
  197. }
  198. }
  199. $aTableHeaders[] = array('label' => $sColLabel, 'type' => $sType);
  200. }
  201. $sRow = json_encode($aTableHeaders);
  202. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
  203. if ($hFile === false)
  204. {
  205. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
  206. }
  207. fwrite($hFile, $sRow."\n");
  208. fclose($hFile);
  209. return '';
  210. }
  211. public function GetNextChunk(&$aStatus)
  212. {
  213. $sRetCode = 'run';
  214. $iPercentage = 0;
  215. $hFile = fopen($this->aStatusInfo['tmp_file'], 'ab');
  216. $oSet = new DBObjectSet($this->oSearch);
  217. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  218. $this->OptimizeColumnLoad($oSet);
  219. $iCount = 0;
  220. $iPreviousTimeLimit = ini_get('max_execution_time');
  221. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  222. while($aRow = $oSet->FetchAssoc())
  223. {
  224. set_time_limit($iLoopTimeLimit);
  225. $aData = array();
  226. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  227. {
  228. $sAlias = $aFieldSpec['sAlias'];
  229. $sAttCode = $aFieldSpec['sAttCode'];
  230. $oObj = $aRow[$sAlias];
  231. $sField = '';
  232. if ($oObj)
  233. {
  234. $sField = $this->GetValue($oObj, $sAttCode);
  235. }
  236. $aData[] = $sField;
  237. }
  238. fwrite($hFile, json_encode($aData)."\n");
  239. $iCount++;
  240. }
  241. set_time_limit($iPreviousTimeLimit);
  242. $this->aStatusInfo['position'] += $this->iChunkSize;
  243. if ($this->aStatusInfo['total'] == 0)
  244. {
  245. $iPercentage = 100;
  246. $sRetCode = 'done'; // Next phase (GetFooter) will be to build the xlsx file
  247. }
  248. else
  249. {
  250. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  251. }
  252. if ($iCount < $this->iChunkSize)
  253. {
  254. $sRetCode = 'done';
  255. }
  256. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  257. return ''; // The actual XLSX file is built in GetFooter();
  258. }
  259. public function GetFooter()
  260. {
  261. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'rb');
  262. if ($hFile === false)
  263. {
  264. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for reading.');
  265. }
  266. $sHeaders = fgets($hFile);
  267. $aHeaders = json_decode($sHeaders, true);
  268. $aData = array();
  269. while($sLine = fgets($hFile))
  270. {
  271. $aRow = json_decode($sLine);
  272. $aData[] = $aRow;
  273. }
  274. fclose($hFile);
  275. $fStartExcel = microtime(true);
  276. $writer = new XLSXWriter();
  277. $oDateTimeFormat = new DateTimeFormat($this->aStatusInfo['date_format']);
  278. $writer->setDateTimeFormat($oDateTimeFormat->ToExcel());
  279. $writer->setAuthor(UserRights::GetUserFriendlyName());
  280. $aHeaderTypes = array();
  281. $aHeaderNames = array();
  282. foreach($aHeaders as $Header)
  283. {
  284. $aHeaderNames[] = $Header['label'];
  285. $aHeaderTypes[] = $Header['type'];
  286. }
  287. $writer->writeSheet($aData,'Sheet1', $aHeaderTypes, $aHeaderNames);
  288. $fExcelTime = microtime(true) - $fStartExcel;
  289. //$this->aStatistics['excel_build_duration'] = $fExcelTime;
  290. $fTime = microtime(true);
  291. $data = $writer->writeToString();
  292. $fExcelSaveTime = microtime(true) - $fTime;
  293. //$this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
  294. @unlink($this->aStatusInfo['tmp_file']);
  295. return $data;
  296. }
  297. public function GetMimeType()
  298. {
  299. return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  300. }
  301. public function GetFileExtension()
  302. {
  303. return 'xlsx';
  304. }
  305. public function GetSupportedFormats()
  306. {
  307. return array('xlsx' => Dict::S('Core:BulkExport:XLSXFormat'));
  308. }
  309. }