spreadsheetbulkexport.class.inc.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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: "spreadsheet" export: a simplified HTML export in which the date/time columns are split in two column: date AND time
  20. *
  21. * @copyright Copyright (C) 2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class SpreadsheetBulkExport extends TabularBulkExport
  25. {
  26. public function DisplayUsage(Page $oP)
  27. {
  28. $oP->p(" * spreadsheet format options:");
  29. $oP->p(" *\tfields: (mandatory) the comma separated list of field codes to export (e.g: name,org_id,service_name...).");
  30. $oP->p(" *\tno_localize: (optional) pass 1 to retrieve the raw (untranslated) values for enumerated fields. Default: 0.");
  31. }
  32. public function EnumFormParts()
  33. {
  34. return array_merge(parent::EnumFormParts(), array('spreadsheet_options' => array('no-localize') ,'interactive_fields_spreadsheet' => array('interactive_fields_spreadsheet')));
  35. }
  36. public function DisplayFormPart(WebPage $oP, $sPartId)
  37. {
  38. switch($sPartId)
  39. {
  40. case 'interactive_fields_spreadsheet':
  41. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_spreadsheet');
  42. break;
  43. case 'spreadsheet_options':
  44. $sChecked = (utils::ReadParam('no_localize', 0) == 1) ? ' checked ' : '';
  45. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:SpreadsheetOptions').'</legend>');
  46. $oP->add('<table>');
  47. $oP->add('<tr>');
  48. $oP->add('<td><input type="checkbox" id="spreadsheet_no_localize" name="no_localize" value="1"'.$sChecked.'><label for="spreadsheet_no_localize"> '.Dict::S('Core:BulkExport:OptionNoLocalize').'</label></td>');
  49. $oP->add('</tr>');
  50. $oP->add('</table>');
  51. $oP->add('</fieldset>');
  52. break;
  53. default:
  54. return parent:: DisplayFormPart($oP, $sPartId);
  55. }
  56. }
  57. public function ReadParameters()
  58. {
  59. parent::ReadParameters();
  60. $this->aStatusInfo['localize'] = (utils::ReadParam('no_localize', 0) != 1);
  61. }
  62. protected function GetSampleData(DBObject $oObj, $sAttCode)
  63. {
  64. return $oObj->GetAsHTML($sAttCode);
  65. }
  66. public function GetHeader()
  67. {
  68. $oSet = new DBObjectSet($this->oSearch);
  69. $this->aStatusInfo['status'] = 'running';
  70. $this->aStatusInfo['position'] = 0;
  71. $this->aStatusInfo['total'] = $oSet->Count();
  72. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  73. $aData = array();
  74. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  75. {
  76. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  77. {
  78. $sAlias = $aMatches[1];
  79. $sAttCode = $aMatches[2];
  80. }
  81. else
  82. {
  83. $sAlias = reset($aSelectedClasses);
  84. $sAttCode = $sExtendedAttCode;
  85. }
  86. if (!array_key_exists($sAlias, $aSelectedClasses))
  87. {
  88. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", array_keys($aSelectedClasses))."'");
  89. }
  90. $sClass = $aSelectedClasses[$sAlias];
  91. switch($sAttCode)
  92. {
  93. case 'id':
  94. if (count($aSelectedClasses) > 1)
  95. {
  96. $aData[] = $sAlias.'.id'; //@@@
  97. }
  98. else
  99. {
  100. $aData[] = 'id'; //@@@
  101. }
  102. break;
  103. default:
  104. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  105. $sColLabel = $this->aStatusInfo['localize'] ? MetaModel::GetLabel($sClass, $sAttCode) : $sAttCode;
  106. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  107. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  108. {
  109. if (count($aSelectedClasses) > 1)
  110. {
  111. $aData[] = $sAlias.'.'.$sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  112. $aData[] = $sAlias.'.'.$sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  113. }
  114. else
  115. {
  116. $aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  117. $aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  118. }
  119. }
  120. else
  121. {
  122. if (count($aSelectedClasses) > 1)
  123. {
  124. $aData[] = $sAlias.'.'.$sColLabel;
  125. }
  126. else
  127. {
  128. $aData[] = $sColLabel;
  129. }
  130. }
  131. }
  132. }
  133. $sData = "<table border=\"1\">\n";
  134. $sData .= "<tr>\n";
  135. foreach($aData as $sLabel)
  136. {
  137. $sData .= "<td>".$sLabel."</td>\n";
  138. }
  139. $sData .= "</tr>\n";
  140. return $sData;
  141. }
  142. public function GetNextChunk(&$aStatus)
  143. {
  144. $sRetCode = 'run';
  145. $iPercentage = 0;
  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. $sData = '';
  181. $oSet->OptimizeColumnLoad($aColumnsToLoad);
  182. $iPreviousTimeLimit = ini_get('max_execution_time');
  183. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  184. while($aRow = $oSet->FetchAssoc())
  185. {
  186. set_time_limit($iLoopTimeLimit);
  187. $sData .= "<tr>";
  188. foreach($aAliasByField as $aAttCode)
  189. {
  190. $sField = '';
  191. $oObj = $aRow[$aAttCode['alias']];
  192. if ($oObj == null)
  193. {
  194. $sData .= "<td x:str>$sField</td>";
  195. continue;
  196. }
  197. switch($aAttCode['attcode'])
  198. {
  199. case 'id':
  200. $sField = $oObj->GetName();
  201. $sData .= "<td>$sField</td>";
  202. break;
  203. default:
  204. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $aAttCode['attcode']);
  205. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  206. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  207. {
  208. $iDate = AttributeDateTime::GetAsUnixSeconds($oObj->Get($aAttCode['attcode']));
  209. $sData .= '<td>'.date('Y-m-d', $iDate).'</td>'; // Add the first column directly
  210. $sField = date('H:i:s', $iDate); // Will add the second column below
  211. $sData .= "<td>$sField</td>";
  212. }
  213. else if($oAttDef instanceof AttributeCaseLog)
  214. {
  215. $rawValue = $oObj->Get($aAttCode['attcode']);
  216. $sField = str_replace("\n", "<br/>", htmlentities($rawValue->__toString(), ENT_QUOTES, 'UTF-8'));
  217. // Trick for Excel: treat the content as text even if it begins with an equal sign
  218. $sData .= "<td x:str>$sField</td>";
  219. }
  220. else
  221. {
  222. $rawValue = $oObj->Get($aAttCode['attcode']);
  223. // Due to custom formatting rules, empty friendlynames may be rendered as non-empty strings
  224. // let's fix this and make sure we render an empty string if the key == 0
  225. if ($oAttDef instanceof AttributeFriendlyName)
  226. {
  227. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  228. if ($sKeyAttCode != 'id')
  229. {
  230. if ($oObj->Get($sKeyAttCode) == 0)
  231. {
  232. $sValue = '';
  233. }
  234. }
  235. }
  236. if ($this->aStatusInfo['localize'])
  237. {
  238. $sField = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8');
  239. }
  240. else
  241. {
  242. $sField = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  243. }
  244. $sData .= "<td>$sField</td>";
  245. }
  246. }
  247. }
  248. $sData .= "</tr>";
  249. $iCount++;
  250. }
  251. set_time_limit($iPreviousTimeLimit);
  252. $this->aStatusInfo['position'] += $this->iChunkSize;
  253. if ($this->aStatusInfo['total'] == 0)
  254. {
  255. $iPercentage = 100;
  256. }
  257. else
  258. {
  259. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  260. }
  261. if ($iCount < $this->iChunkSize)
  262. {
  263. $sRetCode = 'done';
  264. }
  265. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  266. return $sData;
  267. }
  268. public function GetFooter()
  269. {
  270. $sData = "</table>\n";
  271. return $sData;
  272. }
  273. public function GetSupportedFormats()
  274. {
  275. return array('spreadsheet' => Dict::S('Core:BulkExport:SpreadsheetFormat'));
  276. }
  277. public function GetMimeType()
  278. {
  279. return 'text/html';
  280. }
  281. public function GetFileExtension()
  282. {
  283. return 'html';
  284. }
  285. }