csvbulkexport.class.inc.php 10 KB

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