csvbulkexport.class.inc.php 11 KB

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