excelbulkexport.class.inc.php 9.2 KB

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