csvbulkexport.class.inc.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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(" *\tcharacter-set: (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['localize'] = !((bool)utils::ReadParam('no_localize', 0, true, 'integer'));
  53. $this->aStatusInfo['charset'] = strtoupper(utils::ReadParam('character-set', 'UTF-8', true, 'raw_data'));
  54. }
  55. public function EnumFormParts()
  56. {
  57. return array_merge(parent::EnumFormParts(), array('csv_options' => array('separator', 'character-set', 'text-qualifier', 'no_localize') ,'interactive_fields_csv' => array('interactive_fields_csv')));
  58. }
  59. public function DisplayFormPart(WebPage $oP, $sPartId)
  60. {
  61. switch($sPartId)
  62. {
  63. case 'interactive_fields_csv':
  64. $this->GetInteractiveFieldsWidget($oP, 'interactive_fields_csv');
  65. break;
  66. case 'csv_options':
  67. $oP->add('<fieldset><legend>'.Dict::S('Core:BulkExport:CSVOptions').'</legend>');
  68. $oP->add('<table class="export_parameters"><tr><td style="vertical-align:top">');
  69. $oP->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  70. $sRawSeparator = utils::ReadParam('separator', ',', true, 'raw_data');
  71. $aSep = array(
  72. ';' => Dict::S('UI:CSVImport:SeparatorSemicolon+'),
  73. ',' => Dict::S('UI:CSVImport:SeparatorComma+'),
  74. 'tab' => Dict::S('UI:CSVImport:SeparatorTab+'),
  75. );
  76. $sOtherSeparator = '';
  77. if (!array_key_exists($sRawSeparator, $aSep))
  78. {
  79. $sOtherSeparator = $sRawSeparator;
  80. $sRawSeparator = 'other';
  81. }
  82. $aSep['other'] = Dict::S('UI:CSVImport:SeparatorOther').' <input type="text" size="3" name="other-separator" value="'.htmlentities($sOtherSeparator, ENT_QUOTES, 'UTF-8').'"/>';
  83. foreach($aSep as $sVal => $sLabel)
  84. {
  85. $sChecked = ($sVal == $sRawSeparator) ? 'checked' : '';
  86. $oP->add('<input type="radio" name="separator" value="'.htmlentities($sVal, ENT_QUOTES, 'UTF-8').'" '.$sChecked.'/>&nbsp;'.$sLabel.'<br/>');
  87. }
  88. $oP->add('</td><td style="vertical-align:top">');
  89. $oP->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  90. $sRawQualifier = utils::ReadParam('text-qualifier', '"', true, 'raw_data');
  91. $aQualifiers = array(
  92. '"' => Dict::S('UI:CSVImport:QualifierDoubleQuote+'),
  93. '\'' => Dict::S('UI:CSVImport:QualifierSimpleQuote+'),
  94. );
  95. $sOtherQualifier = '';
  96. if (!array_key_exists($sRawQualifier, $aQualifiers))
  97. {
  98. $sOtherQualifier = $sRawQualifier;
  99. $sRawQualifier = 'other';
  100. }
  101. $aQualifiers['other'] = Dict::S('UI:CSVImport:QualifierOther').' <input type="text" size="3" name="other-text-qualifier" value="'.htmlentities($sOtherQualifier, ENT_QUOTES, 'UTF-8').'"/>';
  102. foreach($aQualifiers as $sVal => $sLabel)
  103. {
  104. $sChecked = ($sVal == $sRawQualifier) ? 'checked' : '';
  105. $oP->add('<input type="radio" name="text-qualifier" value="'.htmlentities($sVal, ENT_QUOTES, 'UTF-8').'" '.$sChecked.'/>&nbsp;'.$sLabel.'<br/>');
  106. }
  107. $sChecked = (utils::ReadParam('no_localize', 0) == 1) ? ' checked ' : '';
  108. $oP->add('</td><td style="vertical-align:top">');
  109. $oP->add('<h3>'.Dict::S('Core:BulkExport:CSVLocalization').'</h3>');
  110. $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>');
  111. $oP->add('</td></tr></table>');
  112. $oP->add('</fieldset>');
  113. break;
  114. default:
  115. return parent:: DisplayFormPart($oP, $sPartId);
  116. }
  117. }
  118. protected function GetSampleData(DBObject $oObj, $sAttCode)
  119. {
  120. return trim($oObj->GetAsCSV($sAttCode), '"');
  121. }
  122. public function GetHeader()
  123. {
  124. $oSet = new DBObjectSet($this->oSearch);
  125. $this->aStatusInfo['status'] = 'running';
  126. $this->aStatusInfo['position'] = 0;
  127. $this->aStatusInfo['total'] = $oSet->Count();
  128. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  129. $aAuthorizedClasses = array();
  130. foreach($aSelectedClasses as $sAlias => $sClassName)
  131. {
  132. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_BULK_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  133. {
  134. $aAuthorizedClasses[$sAlias] = $sClassName;
  135. }
  136. }
  137. $aData = array();
  138. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  139. {
  140. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  141. {
  142. $sAlias = $aMatches[1];
  143. $sAttCode = $aMatches[2];
  144. }
  145. else
  146. {
  147. $sAlias = reset($aAuthorizedClasses);
  148. $sAttCode = $sExtendedAttCode;
  149. }
  150. if (!array_key_exists($sAlias, $aAuthorizedClasses))
  151. {
  152. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", array_keys($aAuthorizedClasses))."'");
  153. }
  154. $sClass = $aAuthorizedClasses[$sAlias];
  155. if ($this->aStatusInfo['localize'])
  156. {
  157. switch($sAttCode)
  158. {
  159. case 'id':
  160. if (count($aAuthorizedClasses) > 1)
  161. {
  162. $aData[] = $sAlias.'.id';
  163. }
  164. else
  165. {
  166. $aData[] = 'id';
  167. }
  168. break;
  169. default:
  170. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  171. $sLabel = $this->aStatusInfo['localize'] ? $oAttDef->GetLabel() : $sAttCode;
  172. if (count($aAuthorizedClasses) > 1)
  173. {
  174. $aData[] = $sAlias.'.'.$sLabel;
  175. }
  176. else
  177. {
  178. $aData[] = $sLabel;
  179. }
  180. }
  181. }
  182. else
  183. {
  184. $aData[] = $sExtendedAttCode;
  185. }
  186. }
  187. $sFrom = array("\r\n", $this->aStatusInfo['text_qualifier']);
  188. $sTo = array("\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']);
  189. foreach($aData as $idx => $sData)
  190. {
  191. // Escape and encode (if needed) the headers
  192. $sEscaped = str_replace($sFrom, $sTo, (string)$sData);
  193. $aData[$idx] = $this->aStatusInfo['text_qualifier'].$sEscaped.$this->aStatusInfo['text_qualifier'];
  194. if ($this->aStatusInfo['charset'] != 'UTF-8')
  195. {
  196. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  197. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  198. $aData[$idx] = iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $aData[$idx]);
  199. }
  200. }
  201. $sData = implode($this->aStatusInfo['separator'], $aData)."\n";
  202. return $sData;
  203. }
  204. public function GetNextChunk(&$aStatus)
  205. {
  206. $sRetCode = 'run';
  207. $iPercentage = 0;
  208. $oSet = new DBObjectSet($this->oSearch);
  209. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  210. $aAuthorizedClasses = array();
  211. foreach($aSelectedClasses as $sAlias => $sClassName)
  212. {
  213. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_BULK_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  214. {
  215. $aAuthorizedClasses[$sAlias] = $sClassName;
  216. }
  217. }
  218. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  219. $aAliasByField = array();
  220. $aColumnsToLoad = array();
  221. // Prepare the list of aliases / columns to load
  222. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  223. {
  224. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  225. {
  226. $sAlias = $aMatches[1];
  227. $sAttCode = $aMatches[2];
  228. }
  229. else
  230. {
  231. $sAlias = reset($aAuthorizedClasses);
  232. $sAttCode = $sExtendedAttCode;
  233. }
  234. if (!array_key_exists($sAlias, $aAuthorizedClasses))
  235. {
  236. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", array_keys($aAuthorizedClasses))."'");
  237. }
  238. if (!array_key_exists($sAlias, $aColumnsToLoad))
  239. {
  240. $aColumnsToLoad[$sAlias] = array();
  241. }
  242. if ($sAttCode != 'id')
  243. {
  244. // id is not a real attribute code and, moreover, is always loaded
  245. $aColumnsToLoad[$sAlias][] = $sAttCode;
  246. }
  247. $aAliasByField[$sExtendedAttCode] = array('alias' => $sAlias, 'attcode' => $sAttCode);
  248. }
  249. $iCount = 0;
  250. $sData = '';
  251. $oSet->OptimizeColumnLoad($aColumnsToLoad);
  252. $iPreviousTimeLimit = ini_get('max_execution_time');
  253. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  254. while($aRow = $oSet->FetchAssoc())
  255. {
  256. set_time_limit($iLoopTimeLimit);
  257. $aData = array();
  258. foreach($aAliasByField as $aAttCode)
  259. {
  260. $sField = '';
  261. $oObj = $aRow[$aAttCode['alias']];
  262. if ($oObj != null)
  263. {
  264. switch($aAttCode['attcode'])
  265. {
  266. case 'id':
  267. $sField = $oObj->GetKey();
  268. break;
  269. default:
  270. $sField = $oObj->GetAsCSV($aAttCode['attcode'], $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->aStatusInfo['localize']);
  271. }
  272. if ($this->aStatusInfo['charset'] != 'UTF-8')
  273. {
  274. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  275. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  276. $aData[] = iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $sField);
  277. }
  278. else
  279. {
  280. $aData[] = $sField;
  281. }
  282. }
  283. }
  284. $sData .= implode($this->aStatusInfo['separator'], $aData)."\n";
  285. $iCount++;
  286. }
  287. set_time_limit($iPreviousTimeLimit);
  288. $this->aStatusInfo['position'] += $this->iChunkSize;
  289. if ($this->aStatusInfo['total'] == 0)
  290. {
  291. $iPercentage = 100;
  292. }
  293. else
  294. {
  295. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  296. }
  297. if ($iCount < $this->iChunkSize)
  298. {
  299. $sRetCode = 'done';
  300. }
  301. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  302. return $sData;
  303. }
  304. public function GetSupportedFormats()
  305. {
  306. return array('csv' => Dict::S('Core:BulkExport:CSVFormat'));
  307. }
  308. public function GetMimeType()
  309. {
  310. return 'text/csv';
  311. }
  312. public function GetFileExtension()
  313. {
  314. return 'csv';
  315. }
  316. }