excelbulkexport.class.inc.php 9.8 KB

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