csvbulkexport.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 format used in the user interface). Example: 'm/d/Y 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', 'custom');
  57. if ($sDateFormatRadio == 'default')
  58. {
  59. $this->aStatusInfo['date_format'] = AttributeDateTime::GetFormat();
  60. }
  61. else
  62. {
  63. $this->aStatusInfo['date_format'] = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
  64. }
  65. }
  66. protected function SuggestField($sClass, $sAttCode)
  67. {
  68. switch($sAttCode)
  69. {
  70. case 'id': // replace 'id' by 'friendlyname'
  71. $sAttCode = 'friendlyname';
  72. break;
  73. default:
  74. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  75. if ($oAttDef instanceof AttributeExternalKey)
  76. {
  77. $sAttCode .= '_friendlyname';
  78. }
  79. }
  80. return parent::SuggestField($sClass, $sAttCode);
  81. }
  82. public function EnumFormParts()
  83. {
  84. return array_merge(parent::EnumFormParts(), array('csv_options' => array('separator', 'charset', 'text-qualifier', 'no_localize', 'formatted_text') ,'interactive_fields_csv' => array('interactive_fields_csv')));
  85. }
  86. public function DisplayFormPart(WebPage $oP, $sPartId)
  87. {
  88. switch($sPartId)
  89. {
  90. case 'interactive_fields_csv':
  91. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_csv');
  92. break;
  93. case 'csv_options':
  94. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:CSVOptions').'</legend>');
  95. $oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">');
  96. $oP->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  97. $sRawSeparator = utils::ReadParam('separator', ',', true, 'raw_data');
  98. $sCustomDateTimeFormat = utils::ReadParam('', ',', true, 'raw_data');
  99. $aSep = array(
  100. ';' => Dict::S('UI:CSVImport:SeparatorSemicolon+'),
  101. ',' => Dict::S('UI:CSVImport:SeparatorComma+'),
  102. 'tab' => Dict::S('UI:CSVImport:SeparatorTab+'),
  103. );
  104. $sOtherSeparator = '';
  105. if (!array_key_exists($sRawSeparator, $aSep))
  106. {
  107. $sOtherSeparator = $sRawSeparator;
  108. $sRawSeparator = 'other';
  109. }
  110. $aSep['other'] = Dict::S('UI:CSVImport:SeparatorOther').' <input type="text" size="3" name="other-separator" value="'.htmlentities($sOtherSeparator, ENT_QUOTES, 'UTF-8').'"/>';
  111. foreach($aSep as $sVal => $sLabel)
  112. {
  113. $sChecked = ($sVal == $sRawSeparator) ? 'checked' : '';
  114. $oP->add('<input type="radio" name="separator" value="'.htmlentities($sVal, ENT_QUOTES, 'UTF-8').'" '.$sChecked.'/>&nbsp;'.$sLabel.'<br/>');
  115. }
  116. $oP->add('</td><td style="vertical-align:top">');
  117. $oP->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  118. $sRawQualifier = utils::ReadParam('text-qualifier', '"', true, 'raw_data');
  119. $aQualifiers = array(
  120. '"' => Dict::S('UI:CSVImport:QualifierDoubleQuote+'),
  121. '\'' => Dict::S('UI:CSVImport:QualifierSimpleQuote+'),
  122. );
  123. $sOtherQualifier = '';
  124. if (!array_key_exists($sRawQualifier, $aQualifiers))
  125. {
  126. $sOtherQualifier = $sRawQualifier;
  127. $sRawQualifier = 'other';
  128. }
  129. $aQualifiers['other'] = Dict::S('UI:CSVImport:QualifierOther').' <input type="text" size="3" name="other-text-qualifier" value="'.htmlentities($sOtherQualifier, ENT_QUOTES, 'UTF-8').'"/>';
  130. foreach($aQualifiers as $sVal => $sLabel)
  131. {
  132. $sChecked = ($sVal == $sRawQualifier) ? 'checked' : '';
  133. $oP->add('<input type="radio" name="text-qualifier" value="'.htmlentities($sVal, ENT_QUOTES, 'UTF-8').'" '.$sChecked.'/>&nbsp;'.$sLabel.'<br/>');
  134. }
  135. $sChecked = (utils::ReadParam('no_localize', 0) == 1) ? ' checked ' : '';
  136. $oP->add('</td><td style="vertical-align:top">');
  137. $oP->add('<h3>'.Dict::S('Core:BulkExport:CSVLocalization').'</h3>');
  138. $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>');
  139. $oP->add('<br/>');
  140. $oP->add('<br/>');
  141. $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
  142. $aPossibleEncodings = utils::GetPossibleEncodings(MetaModel::GetConfig()->GetCSVImportCharsets());
  143. $sDefaultEncoding = MetaModel::GetConfig()->Get('csv_file_default_charset');
  144. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  145. {
  146. $sSelected = '';
  147. if ($sIconvCode == $sDefaultEncoding)
  148. {
  149. $sSelected = ' selected';
  150. }
  151. $oP->add('<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>');
  152. }
  153. $oP->add('</select>');
  154. $sChecked = (utils::ReadParam('formatted_text', 0) == 1) ? ' checked ' : '';
  155. $oP->add('<h3>'.Dict::S('Core:BulkExport:TextFormat').'</h3>');
  156. $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>');
  157. $oP->add('</td><td style="vertical-align:top">');
  158. $sDateTimeFormat = utils::ReadParam('date_format', AttributeDateTime::GetFormat(), true, 'raw_data');
  159. $sDefaultChecked = ($sDateTimeFormat == AttributeDateTime::GetFormat()) ? ' checked' : '';
  160. $sCustomChecked = ($sDateTimeFormat !== AttributeDateTime::GetFormat()) ? ' checked' : '';
  161. $oP->add('<h3>'.Dict::S('Core:BulkExport:DateTimeFormat').'</h3>');
  162. $sDefaultFormat = htmlentities(AttributeDateTime::GetFormat(), ENT_QUOTES, 'UTF-8');
  163. $sExample = htmlentities(date(AttributeDateTime::GetFormat()), ENT_QUOTES, 'UTF-8');
  164. $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/>');
  165. $sFormatInput = '<input type="text" size="15" name="date_format" id="csv_custom_date_time_format" title="" value="'.htmlentities($sDateTimeFormat, ENT_QUOTES, 'UTF-8').'"/>';
  166. $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>');
  167. $oP->add('</td></tr></table>');
  168. $oP->add('</fieldset>');
  169. $sJSTooltip = json_encode('<div class="date_format_tooltip">'.Dict::S('UI:CSVImport:CustomDateTimeFormatTooltip').'</div>');
  170. $oP->add_ready_script(
  171. <<<EOF
  172. $('#csv_custom_date_time_format').tooltip({content: function() { return $sJSTooltip; } });
  173. $('#csv_custom_date_time_format').on('click', function() { $('#csv_date_time_format_custom').prop('checked', true); });
  174. EOF
  175. );
  176. break;
  177. default:
  178. return parent:: DisplayFormPart($oP, $sPartId);
  179. }
  180. }
  181. protected function GetSampleData($oObj, $sAttCode)
  182. {
  183. return '<div class="text-preview">'.htmlentities($this->GetValue($oObj, $sAttCode), ENT_QUOTES, 'UTF-8').'</div>';
  184. }
  185. protected function GetValue($oObj, $sAttCode)
  186. {
  187. switch($sAttCode)
  188. {
  189. case 'id':
  190. $sRet = $oObj->GetKey();
  191. break;
  192. default:
  193. $sRet = trim($oObj->GetAsCSV($sAttCode), '"');
  194. }
  195. return $sRet;
  196. }
  197. public function GetHeader()
  198. {
  199. $oSet = new DBObjectSet($this->oSearch);
  200. $this->aStatusInfo['status'] = 'running';
  201. $this->aStatusInfo['position'] = 0;
  202. $this->aStatusInfo['total'] = $oSet->Count();
  203. $aData = array();
  204. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  205. {
  206. $aData[] = $aFieldSpec['sColLabel'];
  207. }
  208. $sFrom = array("\r\n", $this->aStatusInfo['text_qualifier']);
  209. $sTo = array("\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']);
  210. foreach($aData as $idx => $sData)
  211. {
  212. // Escape and encode (if needed) the headers
  213. $sEscaped = str_replace($sFrom, $sTo, (string)$sData);
  214. $aData[$idx] = $this->aStatusInfo['text_qualifier'].$sEscaped.$this->aStatusInfo['text_qualifier'];
  215. if ($this->aStatusInfo['charset'] != 'UTF-8')
  216. {
  217. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  218. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  219. $aData[$idx] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $aData[$idx]);
  220. }
  221. }
  222. $sData = implode($this->aStatusInfo['separator'], $aData)."\n";
  223. return $sData;
  224. }
  225. public function GetNextChunk(&$aStatus)
  226. {
  227. $sRetCode = 'run';
  228. $iPercentage = 0;
  229. $oSet = new DBObjectSet($this->oSearch);
  230. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  231. $this->OptimizeColumnLoad($oSet);
  232. $iCount = 0;
  233. $sData = '';
  234. $iPreviousTimeLimit = ini_get('max_execution_time');
  235. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  236. while($aRow = $oSet->FetchAssoc())
  237. {
  238. set_time_limit($iLoopTimeLimit);
  239. $aData = array();
  240. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  241. {
  242. $sAlias = $aFieldSpec['sAlias'];
  243. $sAttCode = $aFieldSpec['sAttCode'];
  244. $sField = '';
  245. $oObj = $aRow[$sAlias];
  246. if ($oObj != null)
  247. {
  248. switch($sAttCode)
  249. {
  250. case 'id':
  251. $sField = $oObj->GetKey();
  252. break;
  253. default:
  254. $sPrevFormat = AttributeDateTime::GetFormat();
  255. AttributeDateTime::SetFormat($this->aStatusInfo['date_format']);
  256. $sField = $oObj->GetAsCSV($sAttCode, $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->bLocalizeOutput, !$this->aStatusInfo['formatted_text']);
  257. AttributeDateTime::SetFormat($sPrevFormat);
  258. }
  259. }
  260. if ($this->aStatusInfo['charset'] != 'UTF-8')
  261. {
  262. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  263. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  264. $aData[] = @iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $sField);
  265. }
  266. else
  267. {
  268. $aData[] = $sField;
  269. }
  270. }
  271. $sData .= implode($this->aStatusInfo['separator'], $aData)."\n";
  272. $iCount++;
  273. }
  274. set_time_limit($iPreviousTimeLimit);
  275. $this->aStatusInfo['position'] += $this->iChunkSize;
  276. if ($this->aStatusInfo['total'] == 0)
  277. {
  278. $iPercentage = 100;
  279. }
  280. else
  281. {
  282. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  283. }
  284. if ($iCount < $this->iChunkSize)
  285. {
  286. $sRetCode = 'done';
  287. }
  288. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  289. return $sData;
  290. }
  291. public function GetSupportedFormats()
  292. {
  293. return array('csv' => Dict::S('Core:BulkExport:CSVFormat'));
  294. }
  295. public function GetMimeType()
  296. {
  297. return 'text/csv';
  298. }
  299. public function GetFileExtension()
  300. {
  301. return 'csv';
  302. }
  303. public function GetCharacterSet()
  304. {
  305. return $this->aStatusInfo['charset'];
  306. }
  307. }