csvbulkexport.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. <?php
  2. // Copyright (C) 2015-2016 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: CSV export
  20. *
  21. * @copyright Copyright (C) 2015-2016 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class CSVBulkExport extends TabularBulkExport
  25. {
  26. public function DisplayUsage(Page $oP)
  27. {
  28. $oP->p(" * csv 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(" *\tseparator: (optional) character to be used as the separator (default is ',').");
  31. $oP->p(" *\tcharset: (optional) character set for encoding the result (default is 'UTF-8').");
  32. $oP->p(" *\ttext-qualifier: (optional) character to be used around text strings (default is '\"').");
  33. $oP->p(" *\tno_localize: set to 1 to retrieve non-localized values (for instance for ENUM values). Default is 0 (= localized values)");
  34. $oP->p(" *\tformatted_text: set to 1 to export case logs and formatted text fields with their HTML markup. Default is 0 (= plain text)");
  35. $oP->p(" *\tdate_format: the format to use when exporting date and time fields (default = the SQL format used in the user interface). e.g. 'Y-m-d H:i:s'");
  36. }
  37. public function ReadParameters()
  38. {
  39. parent::ReadParameters();
  40. $this->aStatusInfo['separator'] = utils::ReadParam('separator', ',', true, 'raw_data');
  41. if (strtolower($this->aStatusInfo['separator']) == 'tab')
  42. {
  43. $this->aStatusInfo['separator'] = "\t";
  44. }
  45. else if (strtolower($this->aStatusInfo['separator']) == 'other')
  46. {
  47. $this->aStatusInfo['separator'] = utils::ReadParam('other-separator', ',', true, 'raw_data');
  48. }
  49. $this->aStatusInfo['text_qualifier'] = utils::ReadParam('text-qualifier', '"', true, 'raw_data');
  50. if (strtolower($this->aStatusInfo['text_qualifier']) == 'other')
  51. {
  52. $this->aStatusInfo['text_qualifier'] = utils::ReadParam('other-text-qualifier', '"', true, 'raw_data');
  53. }
  54. $this->aStatusInfo['charset'] = strtoupper(utils::ReadParam('charset', 'UTF-8', true, 'raw_data'));
  55. $this->aStatusInfo['formatted_text'] = (bool)utils::ReadParam('formatted_text', 0, true);
  56. $sDateFormatRadio = utils::ReadParam('csv_date_format_radio', '');
  57. switch($sDateFormatRadio)
  58. {
  59. case 'default':
  60. // Export from the UI => format = same as is the UI
  61. $this->aStatusInfo['date_format'] = (string)AttributeDateTime::GetFormat();
  62. break;
  63. case 'custom':
  64. // Custom format specified from the UI
  65. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
  66. break;
  67. default:
  68. // Export from the command line (or scripted) => default format is SQL, as in previous versions of iTop, unless specified otherwise
  69. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', (string)AttributeDateTime::GetSQLFormat(), true, 'raw_data');
  70. }
  71. }
  72. protected function SuggestField($sClass, $sAttCode)
  73. {
  74. switch($sAttCode)
  75. {
  76. case 'id': // replace 'id' by 'friendlyname'
  77. $sAttCode = 'friendlyname';
  78. break;
  79. default:
  80. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  81. if ($oAttDef instanceof AttributeExternalKey)
  82. {
  83. $sAttCode .= '_friendlyname';
  84. }
  85. }
  86. return parent::SuggestField($sClass, $sAttCode);
  87. }
  88. public function EnumFormParts()
  89. {
  90. return array_merge(parent::EnumFormParts(), array('csv_options' => array('separator', 'charset', 'text-qualifier', 'no_localize', 'formatted_text') ,'interactive_fields_csv' => array('interactive_fields_csv')));
  91. }
  92. public function DisplayFormPart(WebPage $oP, $sPartId)
  93. {
  94. switch($sPartId)
  95. {
  96. case 'interactive_fields_csv':
  97. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_csv');
  98. break;
  99. case 'csv_options':
  100. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:CSVOptions').'</legend>');
  101. $oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">');
  102. $oP->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  103. $sRawSeparator = utils::ReadParam('separator', ',', true, 'raw_data');
  104. $sCustomDateTimeFormat = utils::ReadParam('', ',', true, 'raw_data');
  105. $aSep = array(
  106. ';' => Dict::S('UI:CSVImport:SeparatorSemicolon+'),
  107. ',' => Dict::S('UI:CSVImport:SeparatorComma+'),
  108. 'tab' => Dict::S('UI:CSVImport:SeparatorTab+'),
  109. );
  110. $sOtherSeparator = '';
  111. if (!array_key_exists($sRawSeparator, $aSep))
  112. {
  113. $sOtherSeparator = $sRawSeparator;
  114. $sRawSeparator = 'other';
  115. }
  116. $aSep['other'] = Dict::S('UI:CSVImport:SeparatorOther').' <input type="text" size="3" name="other-separator" value="'.htmlentities($sOtherSeparator, ENT_QUOTES, 'UTF-8').'"/>';
  117. foreach($aSep as $sVal => $sLabel)
  118. {
  119. $sChecked = ($sVal == $sRawSeparator) ? 'checked' : '';
  120. $oP->add('<input type="radio" name="separator" value="'.htmlentities($sVal, ENT_QUOTES, 'UTF-8').'" '.$sChecked.'/>&nbsp;'.$sLabel.'<br/>');
  121. }
  122. $oP->add('</td><td style="vertical-align:top">');
  123. $oP->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  124. $sRawQualifier = utils::ReadParam('text-qualifier', '"', true, 'raw_data');
  125. $aQualifiers = array(
  126. '"' => Dict::S('UI:CSVImport:QualifierDoubleQuote+'),
  127. '\'' => Dict::S('UI:CSVImport:QualifierSimpleQuote+'),
  128. );
  129. $sOtherQualifier = '';
  130. if (!array_key_exists($sRawQualifier, $aQualifiers))
  131. {
  132. $sOtherQualifier = $sRawQualifier;
  133. $sRawQualifier = 'other';
  134. }
  135. $aQualifiers['other'] = Dict::S('UI:CSVImport:QualifierOther').' <input type="text" size="3" name="other-text-qualifier" value="'.htmlentities($sOtherQualifier, ENT_QUOTES, 'UTF-8').'"/>';
  136. foreach($aQualifiers as $sVal => $sLabel)
  137. {
  138. $sChecked = ($sVal == $sRawQualifier) ? 'checked' : '';
  139. $oP->add('<input type="radio" name="text-qualifier" value="'.htmlentities($sVal, ENT_QUOTES, 'UTF-8').'" '.$sChecked.'/>&nbsp;'.$sLabel.'<br/>');
  140. }
  141. $sChecked = (utils::ReadParam('no_localize', 0) == 1) ? ' checked ' : '';
  142. $oP->add('</td><td style="vertical-align:top">');
  143. $oP->add('<h3>'.Dict::S('Core:BulkExport:CSVLocalization').'</h3>');
  144. $oP->add('<input type="checkbox" id="csv_no_localize" name="no_localize" value="1"'.$sChecked.'><label for="csv_no_localize"> '.Dict::S('Core:BulkExport:OptionNoLocalize').'</label>');
  145. $oP->add('<br/>');
  146. $oP->add('<br/>');
  147. $oP->add(Dict::S('UI:CSVImport:Encoding').': <select name="charset" style="font-family:Arial,Helvetica,Sans-serif">'); // IE 8 has some troubles if the font is different
  148. $aPossibleEncodings = utils::GetPossibleEncodings(MetaModel::GetConfig()->GetCSVImportCharsets());
  149. $sDefaultEncoding = MetaModel::GetConfig()->Get('csv_file_default_charset');
  150. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  151. {
  152. $sSelected = '';
  153. if ($sIconvCode == $sDefaultEncoding)
  154. {
  155. $sSelected = ' selected';
  156. }
  157. $oP->add('<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>');
  158. }
  159. $oP->add('</select>');
  160. $sChecked = (utils::ReadParam('formatted_text', 0) == 1) ? ' checked ' : '';
  161. $oP->add('<h3>'.Dict::S('Core:BulkExport:TextFormat').'</h3>');
  162. $oP->add('<input type="checkbox" id="csv_formatted_text" name="formatted_text" value="1"'.$sChecked.'><label for="csv_formatted_text"> '.Dict::S('Core:BulkExport:OptionFormattedText').'</label>');
  163. $oP->add('</td><td style="vertical-align:top">');
  164. $sDateTimeFormat = utils::ReadParam('date_format', (string)AttributeDateTime::GetFormat(), true, 'raw_data');
  165. $sDefaultChecked = ($sDateTimeFormat == (string)AttributeDateTime::GetFormat()) ? ' checked' : '';
  166. $sCustomChecked = ($sDateTimeFormat !== (string)AttributeDateTime::GetFormat()) ? ' checked' : '';
  167. $oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
  168. $sDefaultFormat = htmlentities((string)AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
  169. $sExample = htmlentities(date((string)AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
  170. $oP->add('<input type="radio" id="csv_date_time_format_default" name="csv_date_format_radio" value="default"'.$sDefaultChecked.'><label for="csv_date_time_format_default"> '.Dict::Format('Core:BulkExport:DateTimeFormatDefault_Example', $sDefaultFormat, $sExample).'</label><br/>');
  171. $sFormatInput = '<input type="text" size="15" name="date_format" id="csv_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
  172. $oP->add('<input type="radio" id="csv_date_time_format_custom" name="csv_date_format_radio" value="custom"'.$sCustomChecked.'><label for="csv_date_time_format_custom"> '.Dict::Format('Core:BulkExport:DateTimeFormatCustom_Format', $sFormatInput).'</label>');
  173. $oP->add('</td></tr></table>');
  174. $oP->add('</fieldset>');
  175. $sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
  176. $oP->add_ready_script(
  177. <<<EOF
  178. $('#csv_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
  179. $('#form_part_csv_options').on('preview_updated', function() { FormatDatesInPreview('csv', 'csv'); });
  180. $('#csv_date_time_format_default').on('click', function() { FormatDatesInPreview('csv', 'csv'); });
  181. $('#csv_date_time_format_custom').on('click', function() { FormatDatesInPreview('csv', 'csv'); });
  182. $('#csv_custom_date_time_format').on('click', function() { $('#csv_date_time_format_custom').prop('checked', true); FormatDatesInPreview('csv', 'csv'); }).on('keyup', function() { FormatDatesInPreview('csv', 'csv'); });
  183. EOF
  184. );
  185. break;
  186. default:
  187. return parent:: DisplayFormPart($oP, $sPartId);
  188. }
  189. }
  190. protected function GetSampleData($oObj, $sAttCode)
  191. {
  192. if ($sAttCode != 'id')
  193. {
  194. $oAttDef = MetaModel::GetAttributeDef(get_class($oObj), $sAttCode);
  195. if ($oAttDef instanceof AttributeDateTime) // AttributeDate is derived from AttributeDateTime
  196. {
  197. $sClass = (get_class($oAttDef) == 'AttributeDateTime') ? 'user-formatted-date-time' : 'user-formatted-date';
  198. return '<div class="'.$sClass.'" data-date="'.$oObj->Get($sAttCode).'">'.htmlentities($oAttDef->GetEditValue($oObj->Get($sAttCode), $oObj), ENT_QUOTES, 'UTF-8').'</div>';
  199. }
  200. }
  201. return '<div class="text-preview">'.htmlentities($this->GetValue($oObj, $sAttCode), ENT_QUOTES, 'UTF-8').'</div>';
  202. }
  203. protected function GetValue($oObj, $sAttCode)
  204. {
  205. switch($sAttCode)
  206. {
  207. case 'id':
  208. $sRet = $oObj->GetKey();
  209. break;
  210. default:
  211. $sRet = trim($oObj->GetAsCSV($sAttCode), '"');
  212. }
  213. return $sRet;
  214. }
  215. public function GetHeader()
  216. {
  217. $oSet = new DBObjectSet($this->oSearch);
  218. $this->aStatusInfo['status'] = 'running';
  219. $this->aStatusInfo['position'] = 0;
  220. $this->aStatusInfo['total'] = $oSet->Count();
  221. $aData = array();
  222. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  223. {
  224. $aData[] = $aFieldSpec['sColLabel'];
  225. }
  226. $sFrom = array("\r\n", $this->aStatusInfo['text_qualifier']);
  227. $sTo = array("\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']);
  228. foreach($aData as $idx => $sData)
  229. {
  230. // Escape and encode (if needed) the headers
  231. $sEscaped = str_replace($sFrom, $sTo, (string)$sData);
  232. $aData[$idx] = $this->aStatusInfo['text_qualifier'].$sEscaped.$this->aStatusInfo['text_qualifier'];
  233. if ($this->aStatusInfo['charset'] != 'UTF-8')
  234. {
  235. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  236. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  237. $aData[$idx] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $aData[$idx]);
  238. }
  239. }
  240. $sData = implode($this->aStatusInfo['separator'], $aData)."\n";
  241. return $sData;
  242. }
  243. public function GetNextChunk(&$aStatus)
  244. {
  245. $sRetCode = 'run';
  246. $iPercentage = 0;
  247. $oSet = new DBObjectSet($this->oSearch);
  248. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  249. $this->OptimizeColumnLoad($oSet);
  250. $iCount = 0;
  251. $sData = '';
  252. $iPreviousTimeLimit = ini_get('max_execution_time');
  253. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  254. $sExportDateTimeFormat = $this->aStatusInfo['date_format'];
  255. $oPrevDateTimeFormat = AttributeDateTime::GetFormat();
  256. $oPrevDateFormat = AttributeDate::GetFormat();
  257. if ($sExportDateTimeFormat !== (string)$oPrevDateTimeFormat)
  258. {
  259. // Change date & time formats
  260. $oDateTimeFormat = new DateTimeFormat($sExportDateTimeFormat);
  261. $oDateFormat = new DateTimeFormat($oDateTimeFormat->ToDateFormat());
  262. AttributeDateTime::SetFormat($oDateTimeFormat);
  263. AttributeDate::SetFormat($oDateFormat);
  264. }
  265. while($aRow = $oSet->FetchAssoc())
  266. {
  267. set_time_limit($iLoopTimeLimit);
  268. $aData = array();
  269. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  270. {
  271. $sAlias = $aFieldSpec['sAlias'];
  272. $sAttCode = $aFieldSpec['sAttCode'];
  273. $sField = '';
  274. $oObj = $aRow[$sAlias];
  275. if ($oObj != null)
  276. {
  277. switch($sAttCode)
  278. {
  279. case 'id':
  280. $sField = $oObj->GetKey();
  281. break;
  282. default:
  283. $sField = $oObj->GetAsCSV($sAttCode, $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->bLocalizeOutput, !$this->aStatusInfo['formatted_text']);
  284. }
  285. }
  286. if ($this->aStatusInfo['charset'] != 'UTF-8')
  287. {
  288. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  289. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  290. $aData[] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $sField);
  291. }
  292. else
  293. {
  294. $aData[] = $sField;
  295. }
  296. }
  297. $sData .= implode($this->aStatusInfo['separator'], $aData)."\n";
  298. $iCount++;
  299. }
  300. // Restore original date & time formats
  301. AttributeDateTime::SetFormat($oPrevDateTimeFormat);
  302. AttributeDate::SetFormat($oPrevDateFormat);
  303. set_time_limit($iPreviousTimeLimit);
  304. $this->aStatusInfo['position'] += $this->iChunkSize;
  305. if ($this->aStatusInfo['total'] == 0)
  306. {
  307. $iPercentage = 100;
  308. }
  309. else
  310. {
  311. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  312. }
  313. if ($iCount < $this->iChunkSize)
  314. {
  315. $sRetCode = 'done';
  316. }
  317. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  318. return $sData;
  319. }
  320. public function GetSupportedFormats()
  321. {
  322. return array('csv' => Dict::S('Core:BulkExport:CSVFormat'));
  323. }
  324. public function GetMimeType()
  325. {
  326. return 'text/csv';
  327. }
  328. public function GetFileExtension()
  329. {
  330. return 'csv';
  331. }
  332. public function GetCharacterSet()
  333. {
  334. return $this->aStatusInfo['charset'];
  335. }
  336. }