ajax.csvimport.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. // Copyright (C) 2010-2012 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. * Specific to the interactive csv import
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once('../approot.inc.php');
  25. require_once(APPROOT.'/application/application.inc.php');
  26. require_once(APPROOT.'/application/webpage.class.inc.php');
  27. require_once(APPROOT.'/application/ajaxwebpage.class.inc.php');
  28. require_once(APPROOT.'/application/wizardhelper.class.inc.php');
  29. require_once(APPROOT.'/application/ui.linkswidget.class.inc.php');
  30. require_once(APPROOT.'/application/csvpage.class.inc.php');
  31. /**
  32. * Determines if the name of the field to be mapped correspond
  33. * to the name of an external key or an Id of the given class
  34. * @param string $sClassName The name of the class
  35. * @param string $sFieldCode The attribute code of the field , or empty if no match
  36. * @return bool true if the field corresponds to an id/External key, false otherwise
  37. */
  38. function IsIdField($sClassName, $sFieldCode)
  39. {
  40. $bResult = false;
  41. if (!empty($sFieldCode))
  42. {
  43. if ($sFieldCode == 'id')
  44. {
  45. $bResult = true;
  46. }
  47. else if (strpos($sFieldCode, '->') === false)
  48. {
  49. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFieldCode);
  50. $bResult = $oAttDef->IsExternalKey();
  51. }
  52. }
  53. return $bResult;
  54. }
  55. /**
  56. * Get all the fields xxx->yyy based on the field xxx which is an external key
  57. * @param string $sExtKeyAttCode Attribute code of the external key
  58. * @param AttributeDefinition $oExtKeyAttDef Attribute definition of the external key
  59. * @param bool $bAdvanced True if advanced mode
  60. * @return Ash List of codes=>display name: xxx->yyy where yyy are the reconciliation keys for the object xxx
  61. */
  62. function GetMappingsForExtKey($sAttCode, AttributeDefinition $oExtKeyAttDef, $bAdvanced)
  63. {
  64. $aResult = array();
  65. $sTargetClass = $oExtKeyAttDef->GetTargetClass();
  66. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sTargetAttCode => $oTargetAttDef)
  67. {
  68. if (MetaModel::IsReconcKey($sTargetClass, $sTargetAttCode))
  69. {
  70. $bExtKey = $oTargetAttDef->IsExternalKey();
  71. $sSuffix = '';
  72. if ($bExtKey)
  73. {
  74. $sSuffix = '->id';
  75. }
  76. if ($bAdvanced || !$bExtKey)
  77. {
  78. // When not in advanced mode do not allow to use reconciliation keys (on external keys) if they are themselves external keys !
  79. $aResult[$sAttCode.'->'.$sTargetAttCode] = $oExtKeyAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel().$sSuffix;
  80. }
  81. }
  82. }
  83. return $aResult;
  84. }
  85. /**
  86. * Helper function to build the mapping drop-down list for a field
  87. * Spec: Possible choices are "writable" fields in this class plus external fields that are listed as reconciliation keys
  88. * for any class pointed to by an external key in the current class.
  89. * If not in advanced mode, all "id" fields (id and external keys) must be mapped to ":none:" (i.e -- ignore this field --)
  90. * External fields that do not correspond to a reconciliation key must be mapped to ":none:"
  91. * Otherwise, if a field equals either the 'code' or the 'label' (translated) of a field, then it's mapped automatically
  92. * @param string $sClassName Name of the class used for the mapping
  93. * @param string $sFieldName Name of the field, as it comes from the data file (header line)
  94. * @param integer $iFieldIndex Number of the field in the sequence
  95. * @param bool $bAdvancedMode Whether or not advanced mode was chosen
  96. * @param string $sDefaultChoice If set, this will be the item selected by default
  97. * @return string The HTML code corresponding to the drop-down list for this field
  98. */
  99. function GetMappingForField($sClassName, $sFieldName, $iFieldIndex, $bAdvancedMode, $sDefaultChoice)
  100. {
  101. $aChoices = array('' => Dict::S('UI:CSVImport:MappingSelectOne'));
  102. $aChoices[':none:'] = Dict::S('UI:CSVImport:MappingNotApplicable');
  103. $sFieldCode = ''; // Code of the attribute, if there is a match
  104. $aMatches = array();
  105. if (preg_match('/^(.+)\*$/', $sFieldName, $aMatches))
  106. {
  107. // Remove any trailing "star" character.
  108. // A star character at the end can be used to indicate a mandatory field
  109. $sFieldName = $aMatches[1];
  110. }
  111. else if (preg_match('/^(.+)\*->(.+)$/', $sFieldName, $aMatches))
  112. {
  113. // Remove any trailing "star" character before the arrow (->)
  114. // A star character at the end can be used to indicate a mandatory field
  115. $sFieldName = $aMatches[1].'->'.$aMatches[2];
  116. }
  117. if ($sFieldName == 'id')
  118. {
  119. $sFieldCode = 'id';
  120. }
  121. if ($bAdvancedMode)
  122. {
  123. $aChoices['id'] = Dict::S('UI:CSVImport:idField');
  124. }
  125. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  126. {
  127. $sStar = '';
  128. if ($oAttDef->IsExternalKey())
  129. {
  130. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  131. {
  132. $sFieldCode = $sAttCode;
  133. }
  134. if ($bAdvancedMode)
  135. {
  136. $aChoices[$sAttCode] = $oAttDef->GetLabel();
  137. }
  138. $oExtKeyAttDef = MetaModel::GetAttributeDef($sClassName, $oAttDef->GetKeyAttCode());
  139. if (!$oExtKeyAttDef->IsNullAllowed())
  140. {
  141. $sStar = '*';
  142. }
  143. // Get fields of the external class that are considered as reconciliation keys
  144. $sTargetClass = $oAttDef->GetTargetClass();
  145. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sTargetAttCode => $oTargetAttDef)
  146. {
  147. if (MetaModel::IsReconcKey($sTargetClass, $sTargetAttCode))
  148. {
  149. $bExtKey = $oTargetAttDef->IsExternalKey();
  150. $sSuffix = '';
  151. if ($bExtKey)
  152. {
  153. $sSuffix = '->id';
  154. }
  155. if ($bAdvancedMode || !$bExtKey)
  156. {
  157. // When not in advanced mode do not allow to use reconciliation keys (on external keys) if they are themselves external keys !
  158. $aChoices[$sAttCode.'->'.$sTargetAttCode] = MetaModel::GetLabel($sClassName, $sAttCode.'->'.$sTargetAttCode, true);
  159. if ((strcasecmp($sFieldName, $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel().$sSuffix) == 0) || (strcasecmp($sFieldName, ($sAttCode.'->'.$sTargetAttCode.$sSuffix)) == 0) )
  160. {
  161. $sFieldCode = $sAttCode.'->'.$sTargetAttCode;
  162. }
  163. }
  164. }
  165. }
  166. }
  167. else if ($oAttDef->IsWritable() && (!$oAttDef->IsLinkset() || ($bAdvancedMode && $oAttDef->IsIndirect())))
  168. {
  169. $aChoices[$sAttCode] = MetaModel::GetLabel($sClassName, $sAttCode, true);
  170. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  171. {
  172. $sFieldCode = $sAttCode;
  173. }
  174. }
  175. }
  176. asort($aChoices);
  177. $sHtml = "<select id=\"mapping_{$iFieldIndex}\" name=\"field[$iFieldIndex]\">\n";
  178. $bIsIdField = IsIdField($sClassName, $sFieldCode);
  179. foreach($aChoices as $sAttCode => $sLabel)
  180. {
  181. $sSelected = '';
  182. if ($bIsIdField && (!$bAdvancedMode)) // When not in advanced mode, ID are mapped to n/a
  183. {
  184. if ($sAttCode == ':none:')
  185. {
  186. $sSelected = ' selected';
  187. }
  188. }
  189. else if (empty($sFieldCode) && (strpos($sFieldName, '->') !== false))
  190. {
  191. if ($sAttCode == ':none:')
  192. {
  193. $sSelected = ' selected';
  194. }
  195. }
  196. else if (is_null($sDefaultChoice) && ($sFieldCode == $sAttCode))
  197. {
  198. $sSelected = ' selected';
  199. }
  200. else if (!is_null($sDefaultChoice) && ($sDefaultChoice == $sAttCode))
  201. {
  202. $sSelected = ' selected';
  203. }
  204. $sHtml .= "<option value=\"$sAttCode\"$sSelected>$sLabel</option>\n";
  205. }
  206. $sHtml .= "</select>\n";
  207. return $sHtml;
  208. }
  209. try
  210. {
  211. require_once(APPROOT.'/application/startup.inc.php');
  212. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  213. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  214. $sOperation = utils::ReadParam('operation', '');
  215. switch($sOperation)
  216. {
  217. case 'parser_preview':
  218. $oPage = new ajax_page("");
  219. $oPage->no_cache();
  220. $oPage->SetContentType('text/html');
  221. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  222. if ($sSeparator == 'tab') $sSeparator = "\t";
  223. $sTextQualifier = utils::ReadParam('qualifier', '"', false, 'raw_data');
  224. $iLinesToSkip = utils::ReadParam('do_skip_lines', 0);
  225. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  226. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  227. $sData = stripslashes(utils::ReadParam('csvdata', true, false, 'raw_data'));
  228. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  229. $aData = $oCSVParser->ToArray($iLinesToSkip);
  230. $iTarget = count($aData);
  231. if ($iTarget == 0)
  232. {
  233. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  234. }
  235. else
  236. {
  237. $sMaxLen = (strlen(''.$iTarget) < 3) ? 3 : strlen(''.$iTarget); // Pad line numbers to the appropriate number of chars, but at least 3
  238. $sFormat = '%0'.$sMaxLen.'d';
  239. $oPage->p("<h3>".Dict::S('UI:Title:DataPreview')."</h3>\n");
  240. $oPage->p("<div style=\"overflow-y:auto\" class=\"white\">\n");
  241. $oPage->add("<table cellspacing=\"0\" style=\"overflow-y:auto\">");
  242. $iMaxIndex= 10; // Display maximum 10 lines for the preview
  243. $index = 1;
  244. foreach($aData as $aRow)
  245. {
  246. $sCSSClass = 'csv_row'.($index % 2);
  247. if ( ($bFirstLineAsHeader) && ($index == 1))
  248. {
  249. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td>");
  250. foreach ($aRow as $sCell)
  251. {
  252. $oPage->add('<th>'.htmlentities($sCell, ENT_QUOTES, 'UTF-8').'</th>');
  253. }
  254. $oPage->add("</tr>\n");
  255. $iNbCols = count($aRow);
  256. }
  257. else
  258. {
  259. if ($index == 1) $iNbCols = count($aRow);
  260. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td>");
  261. foreach ($aRow as $sCell)
  262. {
  263. $oPage->add('<td>'.htmlentities($sCell, ENT_QUOTES, 'UTF-8').'</td>');
  264. }
  265. $oPage->add("</tr>\n");
  266. }
  267. $index++;
  268. if ($index > $iMaxIndex) break;
  269. }
  270. $oPage->add("</table>\n");
  271. $oPage->add("</div>\n");
  272. if($iNbCols == 1)
  273. {
  274. $oPage->p('<img src="../images/error.png">&nbsp;'.Dict::S('UI:CSVImport:ErrorOnlyOneColumn'));
  275. }
  276. else
  277. {
  278. $oPage->p('&nbsp;');
  279. }
  280. }
  281. break;
  282. case 'display_mapping_form':
  283. $oPage = new ajax_page("");
  284. $oPage->no_cache();
  285. $oPage->SetContentType('text/html');
  286. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  287. $sTextQualifier = utils::ReadParam('qualifier', '"', false, 'raw_data');
  288. $iLinesToSkip = utils::ReadParam('do_skip_lines', 0);
  289. $bFirstLineAsHeader = utils::ReadParam('header_line', false);
  290. $sData = stripslashes(utils::ReadParam('csvdata', '', false, 'raw_data'));
  291. $sClassName = utils::ReadParam('class_name', '');
  292. $bAdvanced = utils::ReadParam('advanced', false);
  293. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  294. $sInitFieldMapping = utils::ReadParam('init_field_mapping', '', false, 'raw_data');
  295. $sInitSearchField = utils::ReadParam('init_search_field', '', false, 'raw_data');
  296. $aInitFieldMapping = empty($sInitFieldMapping) ? array() : json_decode($sInitFieldMapping, true);
  297. $aInitSearchField = empty($sInitSearchField) ? array() : json_decode($sInitSearchField, true);
  298. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  299. $aData = $oCSVParser->ToArray($iLinesToSkip);
  300. $iTarget = count($aData);
  301. if ($iTarget == 0)
  302. {
  303. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  304. }
  305. else
  306. {
  307. $oPage->add("<table>");
  308. $aFirstLine = $aData[0]; // Use the first row to determine the number of columns
  309. $iStartLine = 0;
  310. $iNbColumns = count($aFirstLine);
  311. if ($bFirstLineAsHeader)
  312. {
  313. $iStartLine = 1;
  314. foreach($aFirstLine as $sField)
  315. {
  316. $aHeader[] = $sField;
  317. }
  318. }
  319. else
  320. {
  321. // Build some conventional name for the fields: field1...fieldn
  322. $index= 1;
  323. foreach($aFirstLine as $sField)
  324. {
  325. $aHeader[] = Dict::Format('UI:CSVImport:FieldName', $index);
  326. $index++;
  327. }
  328. }
  329. $oPage->add("<table>\n");
  330. $oPage->add('<tr>');
  331. $oPage->add('<th>'.Dict::S('UI:CSVImport:HeaderFields').'</th><th>'.Dict::S('UI:CSVImport:HeaderMappings').'</th><th>&nbsp;</th><th>'.Dict::S('UI:CSVImport:HeaderSearch').'</th><th>'.Dict::S('UI:CSVImport:DataLine1').'</th><th>'.Dict::S('UI:CSVImport:DataLine2').'</th>');
  332. $oPage->add('</tr>');
  333. $index = 1;
  334. foreach($aHeader as $sField)
  335. {
  336. $sDefaultChoice = null;
  337. if (isset($aInitFieldMapping[$index]))
  338. {
  339. $sDefaultChoice = $aInitFieldMapping[$index];
  340. }
  341. $oPage->add('<tr>');
  342. $oPage->add("<th>$sField</th>");
  343. $oPage->add('<td>'.GetMappingForField($sClassName, $sField, $index, $bAdvanced, $sDefaultChoice).'</td>');
  344. $oPage->add('<td>&nbsp;</td>');
  345. $oPage->add('<td><input id="search_'.$index.'" type="checkbox" name="search_field['.$index.']" value="1" /></td>');
  346. $oPage->add('<td>'.(isset($aData[$iStartLine][$index-1]) ? htmlentities($aData[$iStartLine][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  347. $oPage->add('<td>'.(isset($aData[$iStartLine+1][$index-1]) ? htmlentities($aData[$iStartLine+1][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  348. $oPage->add('</tr>');
  349. $index++;
  350. }
  351. $oPage->add("</table>\n");
  352. if (empty($sInitSearchField))
  353. {
  354. // Propose a reconciliation scheme
  355. //
  356. $aReconciliationKeys = MetaModel::GetReconcKeys($sClassName);
  357. $aMoreReconciliationKeys = array(); // Store: key => void to automatically remove duplicates
  358. foreach($aReconciliationKeys as $sAttCode)
  359. {
  360. if (!MetaModel::IsValidAttCode($sClassName, $sAttCode)) continue;
  361. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  362. if ($oAttDef->IsExternalKey())
  363. {
  364. // An external key is specified as a reconciliation key: this means that all the reconciliation
  365. // keys of this class are proposed to identify the target object
  366. $aMoreReconciliationKeys = array_merge($aMoreReconciliationKeys, GetMappingsForExtKey($sAttCode, $oAttDef, $bAdvanced));
  367. }
  368. elseif($oAttDef->IsExternalField())
  369. {
  370. // An external field is specified as a reconciliation key, translate the field into a field on the target class
  371. // since external fields are not writable, and thus never appears in the mapping form
  372. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  373. $sTargetAttCode = $oAttDef->GetExtAttCode();
  374. $aMoreReconciliationKeys[$sKeyAttCode.'->'.$sTargetAttCode] = '';
  375. }
  376. }
  377. $sDefaultKeys = '"'.implode('", "',array_merge($aReconciliationKeys, array_keys($aMoreReconciliationKeys))).'"';
  378. }
  379. else
  380. {
  381. // The reconciliation scheme is given (navigating back in the wizard)
  382. //
  383. $aDefaultKeys = array();
  384. foreach ($aInitSearchField as $iSearchField => $void)
  385. {
  386. $sAttCodeEx = $aInitFieldMapping[$iSearchField];
  387. $aDefaultKeys[] = $sAttCodeEx;
  388. }
  389. $sDefaultKeys = '"'.implode('", "', $aDefaultKeys).'"';
  390. }
  391. $oPage->add_ready_script(
  392. <<<EOF
  393. $('select[name^=field]').change( DoCheckMapping );
  394. aDefaultKeys = new Array($sDefaultKeys);
  395. DoCheckMapping();
  396. EOF
  397. );
  398. }
  399. break;
  400. case 'get_csv_template':
  401. $sClassName = utils::ReadParam('class_name');
  402. $sFormat = utils::ReadParam('format', 'csv');
  403. if (MetaModel::IsValidClass($sClassName))
  404. {
  405. $oSearch = new DBObjectSearch($sClassName);
  406. $oSearch->AddCondition('id', 0, '='); // Make sure we create an empty set
  407. $oSet = new CMDBObjectSet($oSearch);
  408. $sResult = cmdbAbstractObject::GetSetAsCSV($oSet, array('showMandatoryFields' => true));
  409. $sClassDisplayName = MetaModel::GetName($sClassName);
  410. $sDisposition = utils::ReadParam('disposition', 'inline');
  411. if ($sDisposition == 'attachment')
  412. {
  413. switch($sFormat)
  414. {
  415. case 'xlsx':
  416. $oPage = new ajax_page("");
  417. $oPage->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  418. $oPage->SetContentDisposition('attachment', $sClassDisplayName.'.xlsx');
  419. require_once(APPROOT.'/application/excelexporter.class.inc.php');
  420. $writer = new XLSXWriter();
  421. $writer->setAuthor(UserRights::GetUserFriendlyName());
  422. $aHeaders = array( 0 => explode(',', $sResult)); // comma is the default separator
  423. $writer->writeSheet($aHeaders, $sClassDisplayName, array());
  424. $oPage->add($writer->writeToString());
  425. break;
  426. case 'csv':
  427. default:
  428. $oPage = new CSVPage("");
  429. $oPage->add_header("Content-type: text/csv; charset=utf-8");
  430. $oPage->add_header("Content-disposition: attachment; filename=\"{$sClassDisplayName}.csv\"");
  431. $oPage->no_cache();
  432. $oPage->add($sResult);
  433. }
  434. }
  435. else
  436. {
  437. $oPage = new ajax_page("");
  438. $oPage->no_cache();
  439. $oPage->add('<p style="text-align:center">');
  440. $oPage->add('<div style="display:inline-block;margin:0.5em;"><a style="text-decoration:none" href="'.utils::GetAbsoluteUrlAppRoot().'pages/ajax.csvimport.php?operation=get_csv_template&disposition=attachment&class_name='.$sClassName.'"><img border="0" src="../images/csv.png"><br/>'.$sClassDisplayName.'.csv</a></div>');
  441. $oPage->add('<div style="display:inline-block;margin:0.5em;"><a style="text-decoration:none" href="'.utils::GetAbsoluteUrlAppRoot().'pages/ajax.csvimport.php?operation=get_csv_template&disposition=attachment&format=xlsx&class_name='.$sClassName.'"><img border="0" src="../images/xlsx.png"><br/>'.$sClassDisplayName.'.xlsx</a></div>');
  442. $oPage->add('</p>');
  443. $oPage->add('<p><textarea rows="5" cols="100">'.$sResult.'</textarea></p>');
  444. }
  445. }
  446. else
  447. {
  448. $oPage = new ajax_page("Class $sClassName is not a valid class !");
  449. }
  450. break;
  451. }
  452. $oPage->output();
  453. }
  454. catch (Exception $e)
  455. {
  456. IssueLog::Error($e->getMessage());
  457. }
  458. ?>