csvbulkexport.class.inc.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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['localize'] = !((bool)utils::ReadParam('no_localize', 0, true, 'integer'));
  53. $this->aStatusInfo['charset'] = strtoupper(utils::ReadParam('charset', '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', 'charset', '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('<br/>');
  128. $oP->add('<br/>');
  129. $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
  130. $aPossibleEncodings = utils::GetPossibleEncodings(MetaModel::GetConfig()->GetCSVImportCharsets());
  131. $sDefaultEncoding = MetaModel::GetConfig()->Get('csv_file_default_charset');
  132. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  133. {
  134. $sSelected = '';
  135. if ($sIconvCode == $sDefaultEncoding)
  136. {
  137. $sSelected = ' selected';
  138. }
  139. $oP->add('<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>');
  140. }
  141. $oP->add('</select>');
  142. $oP->add('</td></tr></table>');
  143. $oP->add('</fieldset>');
  144. break;
  145. default:
  146. return parent:: DisplayFormPart($oP, $sPartId);
  147. }
  148. }
  149. protected function GetSampleData(DBObject $oObj, $sAttCode)
  150. {
  151. return trim($oObj->GetAsCSV($sAttCode), '"');
  152. }
  153. public function GetHeader()
  154. {
  155. $oSet = new DBObjectSet($this->oSearch);
  156. $this->aStatusInfo['status'] = 'running';
  157. $this->aStatusInfo['position'] = 0;
  158. $this->aStatusInfo['total'] = $oSet->Count();
  159. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  160. $aAuthorizedClasses = array();
  161. foreach($aSelectedClasses as $sAlias => $sClassName)
  162. {
  163. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_BULK_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  164. {
  165. $aAuthorizedClasses[$sAlias] = $sClassName;
  166. }
  167. }
  168. $aAliases = array_keys($aAuthorizedClasses);
  169. $aData = array();
  170. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  171. {
  172. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  173. {
  174. $sAlias = $aMatches[1];
  175. $sAttCode = $aMatches[2];
  176. }
  177. else
  178. {
  179. $sAlias = reset($aAliases);
  180. $sAttCode = $sExtendedAttCode;
  181. }
  182. if (!in_array($sAlias, $aAliases))
  183. {
  184. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", $aAliases)."'");
  185. }
  186. $sClass = $aAuthorizedClasses[$sAlias];
  187. switch($sAttCode)
  188. {
  189. case 'id':
  190. $sLabel = 'id';
  191. break;
  192. default:
  193. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  194. if (($oAttDef instanceof AttributeExternalField) || (($oAttDef instanceof AttributeFriendlyName) && ($oAttDef->GetKeyAttCode() != 'id')))
  195. {
  196. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $oAttDef->GetKeyAttCode());
  197. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $oAttDef->GetExtAttCode());
  198. if ($this->aStatusInfo['localize'])
  199. {
  200. $sStar = $oAttDef->IsNullAllowed() ? '' : '*';
  201. $sLabel = $oKeyAttDef->GetLabel().$sStar.'->'.$oExtAttDef->GetLabel();
  202. }
  203. else
  204. {
  205. $sLabel = $oKeyAttDef->GetCode().'->'.$oExtAttDef->GetCode();
  206. }
  207. }
  208. else
  209. {
  210. $sLabel = $this->aStatusInfo['localize'] ? $oAttDef->GetLabel() : $sAttCode;
  211. }
  212. }
  213. if (count($aAuthorizedClasses) > 1)
  214. {
  215. $aData[] = $sAlias.'.'.$sLabel;
  216. }
  217. else
  218. {
  219. $aData[] = $sLabel;
  220. }
  221. }
  222. $sFrom = array("\r\n", $this->aStatusInfo['text_qualifier']);
  223. $sTo = array("\n", $this->aStatusInfo['text_qualifier'].$this->aStatusInfo['text_qualifier']);
  224. foreach($aData as $idx => $sData)
  225. {
  226. // Escape and encode (if needed) the headers
  227. $sEscaped = str_replace($sFrom, $sTo, (string)$sData);
  228. $aData[$idx] = $this->aStatusInfo['text_qualifier'].$sEscaped.$this->aStatusInfo['text_qualifier'];
  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[$idx] = iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $aData[$idx]);
  234. }
  235. }
  236. $sData = implode($this->aStatusInfo['separator'], $aData)."\n";
  237. return $sData;
  238. }
  239. public function GetNextChunk(&$aStatus)
  240. {
  241. $sRetCode = 'run';
  242. $iPercentage = 0;
  243. $oSet = new DBObjectSet($this->oSearch);
  244. $aSelectedClasses = $this->oSearch->GetSelectedClasses();
  245. $aAuthorizedClasses = array();
  246. foreach($aSelectedClasses as $sAlias => $sClassName)
  247. {
  248. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_BULK_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  249. {
  250. $aAuthorizedClasses[$sAlias] = $sClassName;
  251. }
  252. }
  253. $aAliases = array_keys($aAuthorizedClasses);
  254. $oSet->SetLimit($this->iChunkSize, $this->aStatusInfo['position']);
  255. $aAliasByField = array();
  256. $aColumnsToLoad = array();
  257. // Prepare the list of aliases / columns to load
  258. foreach($this->aStatusInfo['fields'] as $sExtendedAttCode)
  259. {
  260. if (preg_match('/^([^\.]+)\.(.+)$/', $sExtendedAttCode, $aMatches))
  261. {
  262. $sAlias = $aMatches[1];
  263. $sAttCode = $aMatches[2];
  264. }
  265. else
  266. {
  267. $sAlias = reset($aAliases);
  268. $sAttCode = $sExtendedAttCode;
  269. }
  270. if (!in_array($sAlias, $aAliases))
  271. {
  272. throw new Exception("Invalid alias '$sAlias' for the column '$sExtendedAttCode'. Availables aliases: '".implode("', '", $aAliases)."'");
  273. }
  274. if (!array_key_exists($sAlias, $aColumnsToLoad))
  275. {
  276. $aColumnsToLoad[$sAlias] = array();
  277. }
  278. if ($sAttCode != 'id')
  279. {
  280. // id is not a real attribute code and, moreover, is always loaded
  281. $aColumnsToLoad[$sAlias][] = $sAttCode;
  282. }
  283. $aAliasByField[$sExtendedAttCode] = array('alias' => $sAlias, 'attcode' => $sAttCode);
  284. }
  285. $iCount = 0;
  286. $sData = '';
  287. $oSet->OptimizeColumnLoad($aColumnsToLoad);
  288. $iPreviousTimeLimit = ini_get('max_execution_time');
  289. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  290. while($aRow = $oSet->FetchAssoc())
  291. {
  292. set_time_limit($iLoopTimeLimit);
  293. $aData = array();
  294. foreach($aAliasByField as $aAttCode)
  295. {
  296. $sField = '';
  297. $oObj = $aRow[$aAttCode['alias']];
  298. if ($oObj != null)
  299. {
  300. switch($aAttCode['attcode'])
  301. {
  302. case 'id':
  303. $sField = $oObj->GetKey();
  304. break;
  305. default:
  306. $sField = $oObj->GetAsCSV($aAttCode['attcode'], $this->aStatusInfo['separator'], $this->aStatusInfo['text_qualifier'], $this->aStatusInfo['localize']);
  307. }
  308. if ($this->aStatusInfo['charset'] != 'UTF-8')
  309. {
  310. // Note: due to bugs in the glibc library it's safer to call iconv on the smallest possible string
  311. // and thus to convert field by field and not the whole row or file at once (see ticket #991)
  312. $aData[] = iconv('UTF-8', $this->aStatusInfo['charset'].'//IGNORE//TRANSLIT', $sField);
  313. }
  314. else
  315. {
  316. $aData[] = $sField;
  317. }
  318. }
  319. }
  320. $sData .= implode($this->aStatusInfo['separator'], $aData)."\n";
  321. $iCount++;
  322. }
  323. set_time_limit($iPreviousTimeLimit);
  324. $this->aStatusInfo['position'] += $this->iChunkSize;
  325. if ($this->aStatusInfo['total'] == 0)
  326. {
  327. $iPercentage = 100;
  328. }
  329. else
  330. {
  331. $iPercentage = floor(min(100.0, 100.0*$this->aStatusInfo['position']/$this->aStatusInfo['total']));
  332. }
  333. if ($iCount < $this->iChunkSize)
  334. {
  335. $sRetCode = 'done';
  336. }
  337. $aStatus = array('code' => $sRetCode, 'message' => Dict::S('Core:BulkExport:RetrievingData'), 'percentage' => $iPercentage);
  338. return $sData;
  339. }
  340. public function GetSupportedFormats()
  341. {
  342. return array('csv' => Dict::S('Core:BulkExport:CSVFormat'));
  343. }
  344. public function GetMimeType()
  345. {
  346. return 'text/csv';
  347. }
  348. public function GetFileExtension()
  349. {
  350. return 'csv';
  351. }
  352. }