spreadsheetbulkexport.class.inc.php 9.7 KB

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