excelbulkexport.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 if ($value instanceOf ormDocument)
  167. {
  168. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  169. $sRet = $oAttDef->GetAsCSV($value, '', '', $oObj);
  170. }
  171. else
  172. {
  173. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  174. if ($oAttDef instanceof AttributeDateTime)
  175. {
  176. // Date and times are formatted using the ISO encoding, not the localized format
  177. if ($oAttDef->IsNull($value))
  178. {
  179. // NOt a valid date
  180. $sRet = '';
  181. }
  182. else
  183. {
  184. $sRet = $value;
  185. }
  186. }
  187. else if (array_key_exists('formatted_text', $this->aStatusInfo) && $this->aStatusInfo['formatted_text'])
  188. {
  189. $sRet = $oAttDef->GetEditValue($value, $oObj);
  190. }
  191. else
  192. {
  193. $sRet = $oAttDef->GetAsPlainText($value, $oObj);
  194. }
  195. }
  196. }
  197. return $sRet;
  198. }
  199. public function GetHeader()
  200. {
  201. $oSet = new DBObjectSet($this->oSearch);
  202. $this->aStatusInfo['status'] = 'retrieving';
  203. $this->aStatusInfo['tmp_file'] = $this->MakeTmpFile('data');
  204. $this->aStatusInfo['position'] = 0;
  205. $this->aStatusInfo['total'] = $oSet->Count();
  206. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  207. {
  208. $sExtendedAttCode = $aFieldSpec['sFieldSpec'];
  209. $sAttCode = $aFieldSpec['sAttCode'];
  210. $sColLabel = $aFieldSpec['sColLabel'];
  211. switch($sAttCode)
  212. {
  213. case 'id':
  214. $sType = '0';
  215. break;
  216. default:
  217. $oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
  218. $sType = 'string';
  219. if($oAttDef instanceof AttributeDate)
  220. {
  221. $sType = 'date';
  222. }
  223. else if($oAttDef instanceof AttributeDateTime)
  224. {
  225. $sType = 'datetime';
  226. }
  227. }
  228. $aTableHeaders[] = array('label' => $sColLabel, 'type' => $sType);
  229. }
  230. $sRow = json_encode($aTableHeaders);
  231. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
  232. if ($hFile === false)
  233. {
  234. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
  235. }
  236. fwrite($hFile, $sRow."\n");
  237. fclose($hFile);
  238. return '';
  239. }
  240. public function GetNextChunk(&$aStatus)
  241. {
  242. $sRetCode = 'run';
  243. $iPercentage = 0;
  244. $hFile = fopen($this->aStatusInfo['tmp_file'], 'ab');
  245. $oSet = new DBObjectSet($this->oSearch);
  246. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  247. $this->OptimizeColumnLoad($oSet);
  248. $iCount = 0;
  249. $iPreviousTimeLimit = ini_get('max_execution_time');
  250. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  251. while($aRow = $oSet->FetchAssoc())
  252. {
  253. set_time_limit($iLoopTimeLimit);
  254. $aData = array();
  255. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  256. {
  257. $sAlias = $aFieldSpec['sAlias'];
  258. $sAttCode = $aFieldSpec['sAttCode'];
  259. $oObj = $aRow[$sAlias];
  260. $sField = '';
  261. if ($oObj)
  262. {
  263. $sField = $this->GetValue($oObj, $sAttCode);
  264. }
  265. $aData[] = $sField;
  266. }
  267. fwrite($hFile, json_encode($aData)."\n");
  268. $iCount++;
  269. }
  270. set_time_limit($iPreviousTimeLimit);
  271. $this->aStatusInfo['position'] += $this->iChunkSize;
  272. if ($this->aStatusInfo['total'] == 0)
  273. {
  274. $iPercentage = 100;
  275. $sRetCode = 'done'; // Next phase (GetFooter) will be to build the xlsx file
  276. }
  277. else
  278. {
  279. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  280. }
  281. if ($iCount < $this->iChunkSize)
  282. {
  283. $sRetCode = 'done';
  284. }
  285. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  286. return ''; // The actual XLSX file is built in GetFooter();
  287. }
  288. public function GetFooter()
  289. {
  290. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'rb');
  291. if ($hFile === false)
  292. {
  293. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for reading.');
  294. }
  295. $sHeaders = fgets($hFile);
  296. $aHeaders = json_decode($sHeaders, true);
  297. $aData = array();
  298. while($sLine = fgets($hFile))
  299. {
  300. $aRow = json_decode($sLine);
  301. $aData[] = $aRow;
  302. }
  303. fclose($hFile);
  304. $fStartExcel = microtime(true);
  305. $writer = new XLSXWriter();
  306. $oDateTimeFormat = new DateTimeFormat($this->aStatusInfo['date_format']);
  307. $writer->setDateTimeFormat($oDateTimeFormat->ToExcel());
  308. $oDateFormat = new DateTimeFormat($oDateTimeFormat->ToDateFormat());
  309. $writer->setDateFormat($oDateFormat->ToExcel());
  310. $writer->setAuthor(UserRights::GetUserFriendlyName());
  311. $aHeaderTypes = array();
  312. $aHeaderNames = array();
  313. foreach($aHeaders as $Header)
  314. {
  315. $aHeaderNames[] = $Header['label'];
  316. $aHeaderTypes[] = $Header['type'];
  317. }
  318. $writer->writeSheet($aData,'Sheet1', $aHeaderTypes, $aHeaderNames);
  319. $fExcelTime = microtime(true) - $fStartExcel;
  320. //$this->aStatistics['excel_build_duration'] = $fExcelTime;
  321. $fTime = microtime(true);
  322. $data = $writer->writeToString();
  323. $fExcelSaveTime = microtime(true) - $fTime;
  324. //$this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
  325. @unlink($this->aStatusInfo['tmp_file']);
  326. return $data;
  327. }
  328. public function GetMimeType()
  329. {
  330. return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  331. }
  332. public function GetFileExtension()
  333. {
  334. return 'xlsx';
  335. }
  336. public function GetSupportedFormats()
  337. {
  338. return array('xlsx' => Dict::S('Core:BulkExport:XLSXFormat'));
  339. }
  340. }