csvbulkexport.class.inc.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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($aAliases, $sClass, $sAlias, $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($aAliases, $sClass, $sAlias, $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. if ($oObj)
  151. {
  152. $sRet = trim($oObj->GetAsCSV($sAttCode), '"');
  153. }
  154. else
  155. {
  156. $sRet = '';
  157. }
  158. return $sRet;
  159. }
  160. public function GetHeader()
  161. {
  162. $oSet = new DBObjectSet($this->oSearch);
  163. $this->aStatusInfo['status'] = 'running';
  164. $this->aStatusInfo['position'] = 0;
  165. $this->aStatusInfo['total'] = $oSet->Count();
  166. $aData = array();
  167. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  168. {
  169. $aData[] = $aFieldSpec['sColLabel'];
  170. }
  171. $sFrom = array("\r\n", $this->aStatusInfo['text_qualifier']);
  172. $sTo = array("\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']);
  173. foreach($aData as $idx => $sData)
  174. {
  175. // Escape and encode (if needed) the headers
  176. $sEscaped = str_replace($sFrom, $sTo, (string)$sData);
  177. $aData[$idx] = $this->aStatusInfo['text_qualifier'].$sEscaped.$this->aStatusInfo['text_qualifier'];
  178. if ($this->aStatusInfo['charset'] != 'UTF-8')
  179. {
  180. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  181. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  182. $aData[$idx] = iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $aData[$idx]);
  183. }
  184. }
  185. $sData = implode($this->aStatusInfo['separator'], $aData)."\n";
  186. return $sData;
  187. }
  188. public function GetNextChunk(&$aStatus)
  189. {
  190. $sRetCode = 'run';
  191. $iPercentage = 0;
  192. $oSet = new DBObjectSet($this->oSearch);
  193. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  194. $this->OptimizeColumnLoad($oSet);
  195. $iCount = 0;
  196. $sData = '';
  197. $iPreviousTimeLimit = ini_get('max_execution_time');
  198. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  199. while($aRow = $oSet->FetchAssoc())
  200. {
  201. set_time_limit($iLoopTimeLimit);
  202. $aData = array();
  203. foreach($this->aStatusInfo['fields'] as $iCol => $aFieldSpec)
  204. {
  205. $sAlias = $aFieldSpec['sAlias'];
  206. $sAttCode = $aFieldSpec['sAttCode'];
  207. $sField = '';
  208. $oObj = $aRow[$sAlias];
  209. if ($oObj != null)
  210. {
  211. switch($sAttCode)
  212. {
  213. case 'id':
  214. $sField = $oObj->GetKey();
  215. break;
  216. default:
  217. $sField = $oObj->GetAsCSV($sAttCode, $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->bLocalizeOutput);
  218. }
  219. }
  220. if ($this->aStatusInfo['charset'] != 'UTF-8')
  221. {
  222. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  223. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  224. $aData[] = iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $sField);
  225. }
  226. else
  227. {
  228. $aData[] = $sField;
  229. }
  230. }
  231. $sData .= implode($this->aStatusInfo['separator'], $aData)."\n";
  232. $iCount++;
  233. }
  234. set_time_limit($iPreviousTimeLimit);
  235. $this->aStatusInfo['position'] += $this->iChunkSize;
  236. if ($this->aStatusInfo['total'] == 0)
  237. {
  238. $iPercentage = 100;
  239. }
  240. else
  241. {
  242. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  243. }
  244. if ($iCount < $this->iChunkSize)
  245. {
  246. $sRetCode = 'done';
  247. }
  248. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  249. return $sData;
  250. }
  251. public function GetSupportedFormats()
  252. {
  253. return array('csv' => Dict::S('Core:BulkExport:CSVFormat'));
  254. }
  255. public function GetMimeType()
  256. {
  257. return 'text/csv';
  258. }
  259. public function GetFileExtension()
  260. {
  261. return 'csv';
  262. }
  263. }