spreadsheetbulkexport.class.inc.php 11 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. $oP->p(" *\tdate_format: the format to use when exporting date and time fields (default = the SQL format). e.g. 'Y-m-d H:i:s'");
  32. }
  33. public function EnumFormParts()
  34. {
  35. return array_merge(parent::EnumFormParts(), array('spreadsheet_options' => array('no-localize') ,'interactive_fields_spreadsheet' => array('interactive_fields_spreadsheet')));
  36. }
  37. public function DisplayFormPart(WebPage $oP, $sPartId)
  38. {
  39. switch($sPartId)
  40. {
  41. case 'interactive_fields_spreadsheet':
  42. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_spreadsheet');
  43. break;
  44. case 'spreadsheet_options':
  45. $sChecked = (utils::ReadParam('no_localize', 0) == 1) ? ' checked ' : '';
  46. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:SpreadsheetOptions').'</legend>');
  47. $oP->add('<table>');
  48. $oP->add('<tr>');
  49. $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>');
  50. $sDateTimeFormat = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
  51. $sDefaultChecked = ($sDateTimeFormat == (string)AttributeDateTime::GetFormat()) ? ' checked' : '';
  52. $sCustomChecked = ($sDateTimeFormat !== (string)AttributeDateTime::GetFormat()) ? ' checked' : '';
  53. $oP->add('<td>');
  54. $oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
  55. $sDefaultFormat = htmlentities((string)AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
  56. $sExample = htmlentities(date((string)AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
  57. $oP->add('<input type="radio" id="spreadsheet_date_time_format_default" name="date_format_radio" value="default"'.$sDefaultChecked.'><label for="spreadsheet_date_time_format_default"> '.Dict::Format('Core:BulkExport:DateTimeFormatDefault_Example', $sDefaultFormat, $sExample).'</label><br/>');
  58. $sFormatInput = '<input type="text" size="15" name="date_format" id="spreadsheet_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
  59. $oP->add('<input type="radio" id="spreadsheet_date_time_format_custom" name="date_format_radio" value="custom"'.$sCustomChecked.'><label for="spreadsheet_date_time_format_custom"> '.Dict::Format('Core:BulkExport:DateTimeFormatCustom_Format', $sFormatInput).'</label>');
  60. $oP->add('</td>');
  61. $oP->add('</tr>');
  62. $oP->add('</table>');
  63. $oP->add('</fieldset>');
  64. $sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
  65. $oP->add_ready_script(
  66. <<<EOF
  67. $('#spreadsheet_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
  68. $('#spreadsheet_custom_date_time_format').on('click', function() { $('#spreadsheet_date_time_format_custom').prop('checked', true); });
  69. EOF
  70. );
  71. break;
  72. default:
  73. return parent:: DisplayFormPart($oP, $sPartId);
  74. }
  75. }
  76. public function ReadParameters()
  77. {
  78. parent::ReadParameters();
  79. $sDateFormatRadio = utils::ReadParam('date_format_radio', '');
  80. switch($sDateFormatRadio)
  81. {
  82. case 'default':
  83. // Export from the UI => format = same as is the UI
  84. $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
  85. break;
  86. case 'custom':
  87. // Custom format specified from the UI
  88. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
  89. break;
  90. default:
  91. // Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
  92. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
  93. }
  94. }
  95. protected function GetSampleData($oObj, $sAttCode)
  96. {
  97. return $this->GetValue($oObj, $sAttCode);
  98. }
  99. protected function GetValue($oObj, $sAttCode)
  100. {
  101. switch($sAttCode)
  102. {
  103. case 'id':
  104. $sRet = $oObj->GetKey();
  105. break;
  106. default:
  107. $value = $oObj->Get($sAttCode);
  108. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  109. if ($value instanceof ormCaseLog)
  110. {
  111. $sRet = str_replace("\n", "<br/>", htmlentities($value->__toString(), ENT_QUOTES, 'UTF-8'));
  112. }
  113. elseif ($value instanceof ormStopWatch)
  114. {
  115. $sRet = $value->GetTimeSpent();
  116. }
  117. elseif ($oAttDef instanceof AttributeString)
  118. {
  119. $sRet = $oObj->GetAsHTML($sAttCode);
  120. }
  121. elseif ($oAttDef instanceof AttributeCustomFields)
  122. {
  123. $sRet = $oObj->GetAsHTML($sAttCode);
  124. }
  125. else
  126. {
  127. if ($this->bLocalizeOutput)
  128. {
  129. $sRet = htmlentities($oObj->GetEditValue(), ENT_QUOTES, 'UTF-8');
  130. }
  131. else
  132. {
  133. $sRet = htmlentities((string)$value, ENT_QUOTES, 'UTF-8');
  134. }
  135. }
  136. }
  137. return $sRet;
  138. }
  139. public function SetHttpHeaders(WebPage $oPage)
  140. {
  141. // Integration within MS-Excel web queries + HTTPS + IIS:
  142. // MS-IIS set these header values with no-cache... while Excel fails to do the job if using HTTPS
  143. // Then the fix is to force the reset of header values Pragma and Cache-control
  144. $oPage->add_header("Pragma:", true);
  145. $oPage->add_header("Cache-control:", true);
  146. }
  147. public function GetHeader()
  148. {
  149. $oSet = new DBObjectSet($this->oSearch);
  150. $this->aStatusInfo['status'] = 'running';
  151. $this->aStatusInfo['position'] = 0;
  152. $this->aStatusInfo['total'] = $oSet->Count();
  153. $aData = array();
  154. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  155. {
  156. $sColLabel = $aFieldSpec['sColLabel'];
  157. if ($aFieldSpec['sAttCode'] != 'id')
  158. {
  159. $oAttDef = MetaModel::GetAttributeDef($aFieldSpec['sClass'], $aFieldSpec['sAttCode']);
  160. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  161. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  162. {
  163. $aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  164. $aData[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  165. }
  166. else
  167. {
  168. $aData[] = $sColLabel;
  169. }
  170. }
  171. else
  172. {
  173. $aData[] = $sColLabel;
  174. }
  175. }
  176. $sData = '';
  177. $sData .= '<style>table br {mso-data-placement:same-cell;}</style>'; // Trick for Excel: keep line breaks inside the same cell !
  178. $sData .= "<table border=\"1\">\n";
  179. $sData .= "<tr>\n";
  180. foreach($aData as $sLabel)
  181. {
  182. $sData .= "<td>".$sLabel."</td>\n";
  183. }
  184. $sData .= "</tr>\n";
  185. return $sData;
  186. }
  187. public function GetNextChunk(&$aStatus)
  188. {
  189. $sRetCode = 'run';
  190. $iPercentage = 0;
  191. $oSet = new DBObjectSet($this->oSearch);
  192. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  193. $this->OptimizeColumnLoad($oSet);
  194. $sExportDateTimeFormat = $this->aStatusInfo['date_format'];
  195. // Date & time formats
  196. $oDateTimeFormat = new DateTimeFormat($sExportDateTimeFormat);
  197. $oDateFormat = new DateTimeFormat($oDateTimeFormat->ToDateFormat());
  198. $oTimeFormat = new DateTimeFormat($oDateTimeFormat->ToTimeFormat());
  199. $iCount = 0;
  200. $sData = '';
  201. $iPreviousTimeLimit = ini_get('max_execution_time');
  202. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  203. while($aRow = $oSet->FetchAssoc())
  204. {
  205. set_time_limit($iLoopTimeLimit);
  206. $sData .= "<tr>";
  207. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  208. {
  209. $sAlias = $aFieldSpec['sAlias'];
  210. $sAttCode = $aFieldSpec['sAttCode'];
  211. $sField = '';
  212. $oObj = $aRow[$sAlias];
  213. if ($oObj == null)
  214. {
  215. $sData .= "<td x:str></td>";
  216. continue;
  217. }
  218. switch($sAttCode)
  219. {
  220. case 'id':
  221. $sField = $oObj->GetKey();
  222. $sData .= "<td>$sField</td>";
  223. break;
  224. default:
  225. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  226. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  227. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  228. {
  229. // Split the date and time in two columns
  230. $sDate = $oDateFormat->Format($oObj->Get($sAttCode));
  231. $sTime = $oTimeFormat->Format($oObj->Get($sAttCode));
  232. $sData .= "<td>$sDate</td>";
  233. $sData .= "<td>$sTime</td>";
  234. }
  235. else if (get_class($oFinalAttDef) == 'AttributeDate')
  236. {
  237. $sDate = $oDateFormat->Format($oObj->Get($sAttCode));
  238. $sData .= "<td>$sDate</td>";
  239. }
  240. else if($oAttDef instanceof AttributeCaseLog)
  241. {
  242. $rawValue = $oObj->Get($sAttCode);
  243. $sField = str_replace("\n", "<br/>", htmlentities($rawValue->__toString(), ENT_QUOTES, 'UTF-8'));
  244. // Trick for Excel: treat the content as text even if it begins with an equal sign
  245. $sData .= "<td x:str>$sField</td>";
  246. }
  247. else if($oAttDef instanceof AttributeString)
  248. {
  249. $sField = $oObj->GetAsHTML($sAttCode, $this->bLocalizeOutput);
  250. $sData .= "<td x:str>$sField</td>";
  251. }
  252. else
  253. {
  254. $rawValue = $oObj->Get($sAttCode);
  255. if ($this->bLocalizeOutput)
  256. {
  257. $sField = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8');
  258. }
  259. else
  260. {
  261. $sField = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  262. }
  263. $sData .= "<td>$sField</td>";
  264. }
  265. }
  266. }
  267. $sData .= "</tr>";
  268. $iCount++;
  269. }
  270. set_time_limit($iPreviousTimeLimit);
  271. $this->aStatusInfo['position'] += $this->iChunkSize;
  272. if ($this->aStatusInfo['total'] == 0)
  273. {
  274. $iPercentage = 100;
  275. }
  276. else
  277. {
  278. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  279. }
  280. if ($iCount < $this->iChunkSize)
  281. {
  282. $sRetCode = 'done';
  283. }
  284. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  285. return $sData;
  286. }
  287. public function GetFooter()
  288. {
  289. $sData = "</table>\n";
  290. return $sData;
  291. }
  292. public function GetSupportedFormats()
  293. {
  294. return array('spreadsheet' => Dict::S('Core:BulkExport:SpreadsheetFormat'));
  295. }
  296. public function GetMimeType()
  297. {
  298. return 'text/html';
  299. }
  300. public function GetFileExtension()
  301. {
  302. return 'html';
  303. }
  304. }