spreadsheetbulkexport.class.inc.php 12 KB

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