csvbulkexport.class.inc.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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('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="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="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. $('#csv_custom_date_time_format').on('click', function() { $('#csv_date_time_format_custom').prop('checked', true); });
  180. EOF
  181. );
  182. break;
  183. default:
  184. return parent:: DisplayFormPart($oP, $sPartId);
  185. }
  186. }
  187. protected function GetSampleData($oObj, $sAttCode)
  188. {
  189. return '<div class="text-preview">'.htmlentities($this->GetValue($oObj, $sAttCode), ENT_QUOTES, 'UTF-8').'</div>';
  190. }
  191. protected function GetValue($oObj, $sAttCode)
  192. {
  193. switch($sAttCode)
  194. {
  195. case 'id':
  196. $sRet = $oObj->GetKey();
  197. break;
  198. default:
  199. $sRet = trim($oObj->GetAsCSV($sAttCode), '"');
  200. }
  201. return $sRet;
  202. }
  203. public function GetHeader()
  204. {
  205. $oSet = new DBObjectSet($this->oSearch);
  206. $this->aStatusInfo['status'] = 'running';
  207. $this->aStatusInfo['position'] = 0;
  208. $this->aStatusInfo['total'] = $oSet->Count();
  209. $aData = array();
  210. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  211. {
  212. $aData[] = $aFieldSpec['sColLabel'];
  213. }
  214. $sFrom = array("\r\n", $this->aStatusInfo['text_qualifier']);
  215. $sTo = array("\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']);
  216. foreach($aData as $idx => $sData)
  217. {
  218. // Escape and encode (if needed) the headers
  219. $sEscaped = str_replace($sFrom, $sTo, (string)$sData);
  220. $aData[$idx] = $this->aStatusInfo['text_qualifier'].$sEscaped.$this->aStatusInfo['text_qualifier'];
  221. if ($this->aStatusInfo['charset'] != 'UTF-8')
  222. {
  223. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  224. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  225. $aData[$idx] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $aData[$idx]);
  226. }
  227. }
  228. $sData = implode($this->aStatusInfo['separator'], $aData)."\n";
  229. return $sData;
  230. }
  231. public function GetNextChunk(&$aStatus)
  232. {
  233. $sRetCode = 'run';
  234. $iPercentage = 0;
  235. $oSet = new DBObjectSet($this->oSearch);
  236. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  237. $this->OptimizeColumnLoad($oSet);
  238. $iCount = 0;
  239. $sData = '';
  240. $iPreviousTimeLimit = ini_get('max_execution_time');
  241. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  242. $sExportDateTimeFormat = $this->aStatusInfo['date_format'];
  243. $oPrevDateTimeFormat = AttributeDateTime::GetFormat();
  244. $oPrevDateFormat = AttributeDate::GetFormat();
  245. if ($sExportDateTimeFormat !== (string)$oPrevDateTimeFormat)
  246. {
  247. // Change date & time formats
  248. $oDateTimeFormat = new DateTimeFormat($sExportDateTimeFormat);
  249. $oDateFormat = new DateTimeFormat($oDateTimeFormat->ToDateFormat());
  250. AttributeDateTime::SetFormat($oDateTimeFormat);
  251. AttributeDate::SetFormat($oDateFormat);
  252. }
  253. while($aRow = $oSet->FetchAssoc())
  254. {
  255. set_time_limit($iLoopTimeLimit);
  256. $aData = array();
  257. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  258. {
  259. $sAlias = $aFieldSpec['sAlias'];
  260. $sAttCode = $aFieldSpec['sAttCode'];
  261. $sField = '';
  262. $oObj = $aRow[$sAlias];
  263. if ($oObj != null)
  264. {
  265. switch($sAttCode)
  266. {
  267. case 'id':
  268. $sField = $oObj->GetKey();
  269. break;
  270. default:
  271. $sField = $oObj->GetAsCSV($sAttCode, $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->bLocalizeOutput, !$this->aStatusInfo['formatted_text']);
  272. }
  273. }
  274. if ($this->aStatusInfo['charset'] != 'UTF-8')
  275. {
  276. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  277. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  278. $aData[] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $sField);
  279. }
  280. else
  281. {
  282. $aData[] = $sField;
  283. }
  284. }
  285. $sData .= implode($this->aStatusInfo['separator'], $aData)."\n";
  286. $iCount++;
  287. }
  288. // Restore original date & time formats
  289. AttributeDateTime::SetFormat($oPrevDateTimeFormat);
  290. AttributeDate::SetFormat($oPrevDateFormat);
  291. set_time_limit($iPreviousTimeLimit);
  292. $this->aStatusInfo['position'] += $this->iChunkSize;
  293. if ($this->aStatusInfo['total'] == 0)
  294. {
  295. $iPercentage = 100;
  296. }
  297. else
  298. {
  299. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  300. }
  301. if ($iCount < $this->iChunkSize)
  302. {
  303. $sRetCode = 'done';
  304. }
  305. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  306. return $sData;
  307. }
  308. public function GetSupportedFormats()
  309. {
  310. return array('csv' => Dict::S('Core:BulkExport:CSVFormat'));
  311. }
  312. public function GetMimeType()
  313. {
  314. return 'text/csv';
  315. }
  316. public function GetFileExtension()
  317. {
  318. return 'csv';
  319. }
  320. public function GetCharacterSet()
  321. {
  322. return $this->aStatusInfo['charset'];
  323. }
  324. }