excelbulkexport.class.inc.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. public function ReadParameters()
  60. {
  61. parent::ReadParameters();
  62. $this->aStatusInfo['localize'] = !((bool)utils::ReadParam('no_localize', 0, true, 'integer'));
  63. }
  64. protected function SuggestField($aAliases, $sClass, $sAlias, $sAttCode)
  65. {
  66. switch($sAttCode)
  67. {
  68. case 'id': // replace 'id' by 'friendlyname'
  69. $sAttCode = 'friendlyname';
  70. break;
  71. default:
  72. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  73. if ($oAttDef instanceof AttributeExternalKey)
  74. {
  75. $sAttCode .= '_friendlyname';
  76. }
  77. }
  78. return parent::SuggestField($aAliases, $sClass, $sAlias, $sAttCode);
  79. }
  80. public function GetHeader()
  81. {
  82. $oSet = new DBObjectSet($this->oSearch);
  83. $this->aStatusInfo['status'] = 'retrieving';
  84. $this->aStatusInfo['tmp_file'] = $this->MakeTmpFile('data');
  85. $this->aStatusInfo['position'] = 0;
  86. $this->aStatusInfo['total'] = $oSet->Count();
  87. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  88. $aTableHeaders = array();
  89. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  90. {
  91. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  92. {
  93. $sAlias = $aMatches[1];
  94. $sAttCode = $aMatches[2];
  95. }
  96. else
  97. {
  98. $sAlias = reset($aSelectedClasses);
  99. $sAttCode = $sExtendedAttCode;
  100. }
  101. if (!array_key_exists($sAlias, $aSelectedClasses))
  102. {
  103. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", array_keys($aSelectedClasses))."'");
  104. }
  105. $sClass = $aSelectedClasses[$sAlias];
  106. $sFullAlias = '';
  107. if (count($aSelectedClasses) > 1)
  108. {
  109. $sFullAlias = $sAlias.'.';
  110. }
  111. switch($sAttCode)
  112. {
  113. case 'id':
  114. $aTableHeaders[] = array('label' => $sFullAlias.'id', 'type' => '0');
  115. break;
  116. default:
  117. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  118. $sType = 'string';
  119. if($oAttDef instanceof AttributeDateTime)
  120. {
  121. $sType = 'datetime';
  122. }
  123. $sLabel = $sAttCode;
  124. if ($this->aStatusInfo['localize'])
  125. {
  126. $sLabel = $oAttDef->GetLabel();
  127. }
  128. $aTableHeaders[] = array('label' => $sFullAlias.$sLabel, 'type' => $sType);
  129. }
  130. }
  131. $sRow = json_encode($aTableHeaders);
  132. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'ab');
  133. if ($hFile === false)
  134. {
  135. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for writing.');
  136. }
  137. fwrite($hFile, $sRow."\n");
  138. fclose($hFile);
  139. return '';
  140. }
  141. public function GetNextChunk(&$aStatus)
  142. {
  143. $sRetCode = 'run';
  144. $iPercentage = 0;
  145. $hFile = fopen($this->aStatusInfo['tmp_file'], 'ab');
  146. $oSet = new DBObjectSet($this->oSearch);
  147. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  148. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  149. $aAliasByField = array();
  150. $aColumnsToLoad = array();
  151. // Prepare the list of aliases / columns to load
  152. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  153. {
  154. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  155. {
  156. $sAlias = $aMatches[1];
  157. $sAttCode = $aMatches[2];
  158. }
  159. else
  160. {
  161. $sAlias = reset($aSelectedClasses);
  162. $sAttCode = $sExtendedAttCode;
  163. }
  164. if (!array_key_exists($sAlias, $aSelectedClasses))
  165. {
  166. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", array_keys($aSelectedClasses))."'");
  167. }
  168. if (!array_key_exists($sAlias, $aColumnsToLoad))
  169. {
  170. $aColumnsToLoad[$sAlias] = array();
  171. }
  172. if ($sAttCode != 'id')
  173. {
  174. // id is not a real attribute code and, moreover, is always loaded
  175. $aColumnsToLoad[$sAlias][] = $sAttCode;
  176. }
  177. $aAliasByField[$sExtendedAttCode] = array('alias' => $sAlias, 'attcode' => $sAttCode);
  178. }
  179. $iCount = 0;
  180. $oSet->OptimizeColumnLoad($aColumnsToLoad);
  181. $iPreviousTimeLimit = ini_get('max_execution_time');
  182. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  183. while($aRow = $oSet->FetchAssoc())
  184. {
  185. set_time_limit($iLoopTimeLimit);
  186. $aData = array();
  187. foreach($aAliasByField as $aAttCode)
  188. {
  189. $sField = '';
  190. switch($aAttCode['attcode'])
  191. {
  192. case 'id':
  193. $sField = $aRow[$aAttCode['alias']]->GetKey();
  194. break;
  195. default:
  196. $sField = $aRow[$aAttCode['alias']]->Get($aAttCode['attcode']);
  197. }
  198. $aData[] = $sField;
  199. }
  200. fwrite($hFile, json_encode($aData)."\n");
  201. $iCount++;
  202. }
  203. set_time_limit($iPreviousTimeLimit);
  204. $this->aStatusInfo['position'] += $this->iChunkSize;
  205. if ($this->aStatusInfo['total'] == 0)
  206. {
  207. $iPercentage = 100;
  208. $sRetCode = 'done'; // Next phase (GetFooter) will be to build the xlsx file
  209. }
  210. else
  211. {
  212. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  213. }
  214. if ($iCount < $this->iChunkSize)
  215. {
  216. $sRetCode = 'done';
  217. }
  218. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  219. return ''; // The actual XLSX file is built in GetFooter();
  220. }
  221. public function GetFooter()
  222. {
  223. $hFile = @fopen($this->aStatusInfo['tmp_file'], 'rb');
  224. if ($hFile === false)
  225. {
  226. throw new Exception('ExcelBulkExport: Failed to open temporary data file: "'.$this->aStatusInfo['tmp_file'].'" for reading.');
  227. }
  228. $sHeaders = fgets($hFile);
  229. $aHeaders = json_decode($sHeaders, true);
  230. $aData = array();
  231. while($sLine = fgets($hFile))
  232. {
  233. $aRow = json_decode($sLine);
  234. $aData[] = $aRow;
  235. }
  236. fclose($hFile);
  237. $fStartExcel = microtime(true);
  238. $writer = new XLSXWriter();
  239. $writer->setAuthor(UserRights::GetUserFriendlyName());
  240. $aHeaderTypes = array();
  241. $aHeaderNames = array();
  242. foreach($aHeaders as $Header)
  243. {
  244. $aHeaderNames[] = $Header['label'];
  245. $aHeaderTypes[] = $Header['type'];
  246. }
  247. $writer->writeSheet($aData,'Sheet1', $aHeaderTypes, $aHeaderNames);
  248. $fExcelTime = microtime(true) - $fStartExcel;
  249. //$this->aStatistics['excel_build_duration'] = $fExcelTime;
  250. $fTime = microtime(true);
  251. $data = $writer->writeToString();
  252. $fExcelSaveTime = microtime(true) - $fTime;
  253. //$this->aStatistics['excel_write_duration'] = $fExcelSaveTime;
  254. @unlink($this->aStatusInfo['tmp_file']);
  255. return $data;
  256. }
  257. public function GetMimeType()
  258. {
  259. return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  260. }
  261. public function GetFileExtension()
  262. {
  263. return 'xlsx';
  264. }
  265. public function GetSupportedFormats()
  266. {
  267. return array('xlsx' => Dict::S('Core:BulkExport:XLSXFormat'));
  268. }
  269. }