spreadsheetbulkexport.class.inc.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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($oObj, $sAttCode)
  63. {
  64. if ($oObj)
  65. {
  66. $sRet = $oObj->GetAsHTML($sAttCode);
  67. }
  68. else
  69. {
  70. $sRet = '';
  71. }
  72. return $sRet;
  73. }
  74. public function GetHeader()
  75. {
  76. $oSet = new DBObjectSet($this->oSearch);
  77. $this->aStatusInfo['status'] = 'running';
  78. $this->aStatusInfo['position'] = 0;
  79. $this->aStatusInfo['total'] = $oSet->Count();
  80. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  81. $aData = array();
  82. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  83. {
  84. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  85. {
  86. $sAlias = $aMatches[1];
  87. $sAttCode = $aMatches[2];
  88. }
  89. else
  90. {
  91. $sAlias = $this->oSearch->GetClassAlias();
  92. $sAttCode = $sExtendedAttCode;
  93. }
  94. if (!array_key_exists($sAlias, $aSelectedClasses))
  95. {
  96. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", array_keys($aSelectedClasses))."'");
  97. }
  98. $sClass = $aSelectedClasses[$sAlias];
  99. switch($sAttCode)
  100. {
  101. case 'id':
  102. if (count($aSelectedClasses) > 1)
  103. {
  104. $aData[] = $sAlias.'.id'; //@@@
  105. }
  106. else
  107. {
  108. $aData[] = 'id'; //@@@
  109. }
  110. break;
  111. default:
  112. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  113. $sColLabel = $this->aStatusInfo['localize'] ? MetaModel::GetLabel($sClass, $sAttCode) : $sAttCode;
  114. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  115. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  116. {
  117. if (count($aSelectedClasses) > 1)
  118. {
  119. $aData[] = $sAlias.'.'.$sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  120. $aData[] = $sAlias.'.'.$sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  121. }
  122. else
  123. {
  124. $aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  125. $aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  126. }
  127. }
  128. else
  129. {
  130. if (count($aSelectedClasses) > 1)
  131. {
  132. $aData[] = $sAlias.'.'.$sColLabel;
  133. }
  134. else
  135. {
  136. $aData[] = $sColLabel;
  137. }
  138. }
  139. }
  140. }
  141. $sData = "<table border=\"1\">\n";
  142. $sData .= "<tr>\n";
  143. foreach($aData as $sLabel)
  144. {
  145. $sData .= "<td>".$sLabel."</td>\n";
  146. }
  147. $sData .= "</tr>\n";
  148. return $sData;
  149. }
  150. public function GetNextChunk(&$aStatus)
  151. {
  152. $sRetCode = 'run';
  153. $iPercentage = 0;
  154. $oSet = new DBObjectSet($this->oSearch);
  155. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  156. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  157. $aAliasByField = array();
  158. $aColumnsToLoad = array();
  159. // Prepare the list of aliases / columns to load
  160. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  161. {
  162. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  163. {
  164. $sAlias = $aMatches[1];
  165. $sAttCode = $aMatches[2];
  166. }
  167. else
  168. {
  169. $sAlias = $this->oSearch->GetClassAlias();
  170. $sAttCode = $sExtendedAttCode;
  171. }
  172. if (!array_key_exists($sAlias, $aSelectedClasses))
  173. {
  174. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", array_keys($aSelectedClasses))."'");
  175. }
  176. if (!array_key_exists($sAlias, $aColumnsToLoad))
  177. {
  178. $aColumnsToLoad[$sAlias] = array();
  179. }
  180. if ($sAttCode != 'id')
  181. {
  182. // id is not a real attribute code and, moreover, is always loaded
  183. $aColumnsToLoad[$sAlias][] = $sAttCode;
  184. }
  185. $aAliasByField[$sExtendedAttCode] = array('alias' => $sAlias, 'attcode' => $sAttCode);
  186. }
  187. $iCount = 0;
  188. $sData = '';
  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. $sData .= "<tr>";
  196. foreach($aAliasByField as $aAttCode)
  197. {
  198. $sField = '';
  199. $oObj = $aRow[$aAttCode['alias']];
  200. if ($oObj == null)
  201. {
  202. $sData .= "<td x:str>$sField</td>";
  203. continue;
  204. }
  205. switch($aAttCode['attcode'])
  206. {
  207. case 'id':
  208. $sField = $oObj->GetName();
  209. $sData .= "<td>$sField</td>";
  210. break;
  211. default:
  212. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $aAttCode['attcode']);
  213. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  214. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  215. {
  216. $iDate = AttributeDateTime::GetAsUnixSeconds($oObj->Get($aAttCode['attcode']));
  217. $sData .= '<td>'.date('Y-m-d', $iDate).'</td>'; // Add the first column directly
  218. $sField = date('H:i:s', $iDate); // Will add the second column below
  219. $sData .= "<td>$sField</td>";
  220. }
  221. else if($oAttDef instanceof AttributeCaseLog)
  222. {
  223. $rawValue = $oObj->Get($aAttCode['attcode']);
  224. $sField = str_replace("\n", "<br/>", htmlentities($rawValue->__toString(), ENT_QUOTES, 'UTF-8'));
  225. // Trick for Excel: treat the content as text even if it begins with an equal sign
  226. $sData .= "<td x:str>$sField</td>";
  227. }
  228. else
  229. {
  230. $rawValue = $oObj->Get($aAttCode['attcode']);
  231. // Due to custom formatting rules, empty friendlynames may be rendered as non-empty strings
  232. // let's fix this and make sure we render an empty string if the key == 0
  233. if ($oAttDef instanceof AttributeFriendlyName)
  234. {
  235. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  236. if ($sKeyAttCode != 'id')
  237. {
  238. if ($oObj->Get($sKeyAttCode) == 0)
  239. {
  240. $sValue = '';
  241. }
  242. }
  243. }
  244. if ($this->aStatusInfo['localize'])
  245. {
  246. $sField = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8');
  247. }
  248. else
  249. {
  250. $sField = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  251. }
  252. $sData .= "<td>$sField</td>";
  253. }
  254. }
  255. }
  256. $sData .= "</tr>";
  257. $iCount++;
  258. }
  259. set_time_limit($iPreviousTimeLimit);
  260. $this->aStatusInfo['position'] += $this->iChunkSize;
  261. if ($this->aStatusInfo['total'] == 0)
  262. {
  263. $iPercentage = 100;
  264. }
  265. else
  266. {
  267. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  268. }
  269. if ($iCount < $this->iChunkSize)
  270. {
  271. $sRetCode = 'done';
  272. }
  273. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  274. return $sData;
  275. }
  276. public function GetFooter()
  277. {
  278. $sData = "</table>\n";
  279. return $sData;
  280. }
  281. public function GetSupportedFormats()
  282. {
  283. return array('spreadsheet' => Dict::S('Core:BulkExport:SpreadsheetFormat'));
  284. }
  285. public function GetMimeType()
  286. {
  287. return 'text/html';
  288. }
  289. public function GetFileExtension()
  290. {
  291. return 'html';
  292. }
  293. }