excelbulkexport.class.inc.php 13 KB

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