excelbulkexport.class.inc.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. <?php
  2. // Copyright (C) 2015 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 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. }
  44. public function EnumFormParts()
  45. {
  46. return array_merge(parent::EnumFormParts(), array('interactive_fields_xlsx' => array('interactive_fields_xlsx')));
  47. }
  48. public function DisplayFormPart(WebPage $oP, $sPartId)
  49. {
  50. switch($sPartId)
  51. {
  52. case 'interactive_fields_xlsx':
  53. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_xlsx');
  54. break;
  55. default:
  56. return parent:: DisplayFormPart($oP, $sPartId);
  57. }
  58. }
  59. protected function SuggestField($aAliases, $sClass, $sAlias, $sAttCode)
  60. {
  61. switch($sAttCode)
  62. {
  63. case 'id': // replace 'id' by 'friendlyname'
  64. $sAttCode = 'friendlyname';
  65. break;
  66. default:
  67. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  68. if ($oAttDef instanceof AttributeExternalKey)
  69. {
  70. $sAttCode .= '_friendlyname';
  71. }
  72. }
  73. return parent::SuggestField($aAliases, $sClass, $sAlias, $sAttCode);
  74. }
  75. public function GetHeader()
  76. {
  77. $oSet = new DBObjectSet($this->oSearch);
  78. $this->aStatusInfo['status'] = 'retrieving';
  79. $this->aStatusInfo['tmp_file'] = $this->MakeTmpFile('data');
  80. $this->aStatusInfo['position'] = 0;
  81. $this->aStatusInfo['total'] = $oSet->Count();
  82. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  83. {
  84. $sExtendedAttCode = $aFieldSpec['sFieldSpec'];
  85. $sAttCode = $aFieldSpec['sAttCode'];
  86. $sColLabel = $aFieldSpec['sColLabel'];
  87. switch($sAttCode)
  88. {
  89. case 'id':
  90. $sType = '0';
  91. break;
  92. default:
  93. $oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
  94. $sType = 'string';
  95. if($oAttDef instanceof AttributeDateTime)
  96. {
  97. $sType = 'datetime';
  98. }
  99. }
  100. $aTableHeaders[] = array('label' => $sColLabel, 'type' => $sType);
  101. }
  102. $sRow = json_encode($aTableHeaders);
  103. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
  104. if ($hFile === false)
  105. {
  106. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
  107. }
  108. fwrite($hFile, $sRow."\n");
  109. fclose($hFile);
  110. return '';
  111. }
  112. public function GetNextChunk(&$aStatus)
  113. {
  114. $sRetCode = 'run';
  115. $iPercentage = 0;
  116. $hFile = fopen($this->aStatusInfo['tmp_file'], 'ab');
  117. $oSet = new DBObjectSet($this->oSearch);
  118. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  119. $this->OptimizeColumnLoad($oSet);
  120. $iCount = 0;
  121. $iPreviousTimeLimit = ini_get('max_execution_time');
  122. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  123. while($aRow = $oSet->FetchAssoc())
  124. {
  125. set_time_limit($iLoopTimeLimit);
  126. $aData = array();
  127. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  128. {
  129. $sAlias = $aFieldSpec['sAlias'];
  130. $sAttCode = $aFieldSpec['sAttCode'];
  131. $oObj = $aRow[$sAlias];
  132. $sField = '';
  133. if ($oObj)
  134. {
  135. switch($sAttCode)
  136. {
  137. case 'id':
  138. $sField = $oObj->GetKey();
  139. break;
  140. default:
  141. $value = $oObj->Get($sAttCode);
  142. if ($value instanceOf ormCaseLog)
  143. {
  144. // 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!
  145. $sField = trim(preg_replace('/========== ([^=]+) ============/', '********** $1 ************', $value->GetText()));
  146. }
  147. else if ($value instanceOf DBObjectSet)
  148. {
  149. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  150. $sField = $oAttDef->GetAsCSV($value, '', '', $oObj);
  151. }
  152. else
  153. {
  154. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  155. $sField = $oAttDef->GetEditValue($value, $oObj);
  156. }
  157. }
  158. }
  159. $aData[] = $sField;
  160. }
  161. fwrite($hFile, json_encode($aData)."\n");
  162. $iCount++;
  163. }
  164. set_time_limit($iPreviousTimeLimit);
  165. $this->aStatusInfo['position'] += $this->iChunkSize;
  166. if ($this->aStatusInfo['total'] == 0)
  167. {
  168. $iPercentage = 100;
  169. $sRetCode = 'done'; // Next phase (GetFooter) will be to build the xlsx file
  170. }
  171. else
  172. {
  173. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  174. }
  175. if ($iCount < $this->iChunkSize)
  176. {
  177. $sRetCode = 'done';
  178. }
  179. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  180. return ''; // The actual XLSX file is built in GetFooter();
  181. }
  182. public function GetFooter()
  183. {
  184. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'rb');
  185. if ($hFile === false)
  186. {
  187. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for reading.');
  188. }
  189. $sHeaders = fgets($hFile);
  190. $aHeaders = json_decode($sHeaders, true);
  191. $aData = array();
  192. while($sLine = fgets($hFile))
  193. {
  194. $aRow = json_decode($sLine);
  195. $aData[] = $aRow;
  196. }
  197. fclose($hFile);
  198. $fStartExcel = microtime(true);
  199. $writer = new XLSXWriter();
  200. $writer->setAuthor(UserRights::GetUserFriendlyName());
  201. $aHeaderTypes = array();
  202. $aHeaderNames = array();
  203. foreach($aHeaders as $Header)
  204. {
  205. $aHeaderNames[] = $Header['label'];
  206. $aHeaderTypes[] = $Header['type'];
  207. }
  208. $writer->writeSheet($aData,'Sheet1', $aHeaderTypes, $aHeaderNames);
  209. $fExcelTime = microtime(true) - $fStartExcel;
  210. //$this->aStatistics['excel_build_duration'] = $fExcelTime;
  211. $fTime = microtime(true);
  212. $data = $writer->writeToString();
  213. $fExcelSaveTime = microtime(true) - $fTime;
  214. //$this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
  215. @unlink($this->aStatusInfo['tmp_file']);
  216. return $data;
  217. }
  218. public function GetMimeType()
  219. {
  220. return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  221. }
  222. public function GetFileExtension()
  223. {
  224. return 'xlsx';
  225. }
  226. public function GetSupportedFormats()
  227. {
  228. return array('xlsx' => Dict::S('Core:BulkExport:XLSXFormat'));
  229. }
  230. }