csvbulkexport.class.inc.php 12 KB

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