csvbulkexport.class.inc.php 13 KB

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