ajax.csvimport.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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') || ($sFieldName == Dict::S('UI:CSVImport:idField')))
  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. $aSignatures = array();
  151. $aSignatures[] = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  152. $aSignatures[] = $sAttCode.'->'.$sTargetAttCode;
  153. if ($bExtKey)
  154. {
  155. $aSignatures[] = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel().'->id';
  156. $aSignatures[] = $sAttCode.'->'.$sTargetAttCode.'->id';
  157. }
  158. if ($bAdvancedMode || !$bExtKey)
  159. {
  160. // When not in advanced mode do not allow to use reconciliation keys (on external keys) if they are themselves external keys !
  161. $aChoices[$sAttCode.'->'.$sTargetAttCode] = MetaModel::GetLabel($sClassName, $sAttCode.'->'.$sTargetAttCode, true);
  162. foreach ($aSignatures as $sSignature)
  163. {
  164. if (strcasecmp($sFieldName, $sSignature) == 0)
  165. {
  166. $sFieldCode = $sAttCode.'->'.$sTargetAttCode;
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. else if ($oAttDef->IsWritable() && (!$oAttDef->IsLinkset() || ($bAdvancedMode && $oAttDef->IsIndirect())))
  174. {
  175. $aChoices[$sAttCode] = MetaModel::GetLabel($sClassName, $sAttCode, true);
  176. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  177. {
  178. $sFieldCode = $sAttCode;
  179. }
  180. }
  181. }
  182. asort($aChoices);
  183. $sHtml = "<select id=\"mapping_{$iFieldIndex}\" name=\"field[$iFieldIndex]\">\n";
  184. $bIsIdField = IsIdField($sClassName, $sFieldCode);
  185. foreach($aChoices as $sAttCode => $sLabel)
  186. {
  187. $sSelected = '';
  188. if ($bIsIdField && (!$bAdvancedMode)) // When not in advanced mode, ID are mapped to n/a
  189. {
  190. if ($sAttCode == ':none:')
  191. {
  192. $sSelected = ' selected';
  193. }
  194. }
  195. else if (empty($sFieldCode) && (strpos($sFieldName, '->') !== false))
  196. {
  197. if ($sAttCode == ':none:')
  198. {
  199. $sSelected = ' selected';
  200. }
  201. }
  202. else if (is_null($sDefaultChoice) && ($sFieldCode == $sAttCode))
  203. {
  204. $sSelected = ' selected';
  205. }
  206. else if (!is_null($sDefaultChoice) && ($sDefaultChoice == $sAttCode))
  207. {
  208. $sSelected = ' selected';
  209. }
  210. $sHtml .= "<option value=\"$sAttCode\"$sSelected>$sLabel</option>\n";
  211. }
  212. $sHtml .= "</select>\n";
  213. return $sHtml;
  214. }
  215. try
  216. {
  217. require_once(APPROOT.'/application/startup.inc.php');
  218. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  219. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  220. $sOperation = utils::ReadParam('operation', '');
  221. switch($sOperation)
  222. {
  223. case 'parser_preview':
  224. $oPage = new ajax_page("");
  225. $oPage->no_cache();
  226. $oPage->SetContentType('text/html');
  227. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  228. if ($sSeparator == 'tab') $sSeparator = "\t";
  229. $sTextQualifier = utils::ReadParam('qualifier', '"', false, 'raw_data');
  230. $iLinesToSkip = utils::ReadParam('do_skip_lines', 0);
  231. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  232. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  233. $sData = stripslashes(utils::ReadParam('csvdata', true, false, 'raw_data'));
  234. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  235. $aData = $oCSVParser->ToArray($iLinesToSkip);
  236. $iTarget = count($aData);
  237. if ($iTarget == 0)
  238. {
  239. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  240. }
  241. else
  242. {
  243. $sMaxLen = (strlen(''.$iTarget) < 3) ? 3 : strlen(''.$iTarget); // Pad line numbers to the appropriate number of chars, but at least 3
  244. $sFormat = '%0'.$sMaxLen.'d';
  245. $oPage->p("<h3>".Dict::S('UI:Title:DataPreview')."</h3>\n");
  246. $oPage->p("<div style=\"overflow-y:auto\" class=\"white\">\n");
  247. $oPage->add("<table cellspacing=\"0\" style=\"overflow-y:auto\">");
  248. $iMaxIndex= 10; // Display maximum 10 lines for the preview
  249. $index = 1;
  250. foreach($aData as $aRow)
  251. {
  252. $sCSSClass = 'csv_row'.($index % 2);
  253. if ( ($bFirstLineAsHeader) && ($index == 1))
  254. {
  255. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td>");
  256. foreach ($aRow as $sCell)
  257. {
  258. $oPage->add('<th>'.htmlentities($sCell, ENT_QUOTES, 'UTF-8').'</th>');
  259. }
  260. $oPage->add("</tr>\n");
  261. $iNbCols = count($aRow);
  262. }
  263. else
  264. {
  265. if ($index == 1) $iNbCols = count($aRow);
  266. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td>");
  267. foreach ($aRow as $sCell)
  268. {
  269. $oPage->add('<td>'.htmlentities($sCell, ENT_QUOTES, 'UTF-8').'</td>');
  270. }
  271. $oPage->add("</tr>\n");
  272. }
  273. $index++;
  274. if ($index > $iMaxIndex) break;
  275. }
  276. $oPage->add("</table>\n");
  277. $oPage->add("</div>\n");
  278. if($iNbCols == 1)
  279. {
  280. $oPage->p('<img src="../images/error.png">&nbsp;'.Dict::S('UI:CSVImport:ErrorOnlyOneColumn'));
  281. }
  282. else
  283. {
  284. $oPage->p('&nbsp;');
  285. }
  286. }
  287. break;
  288. case 'display_mapping_form':
  289. $oPage = new ajax_page("");
  290. $oPage->no_cache();
  291. $oPage->SetContentType('text/html');
  292. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  293. $sTextQualifier = utils::ReadParam('qualifier', '"', false, 'raw_data');
  294. $iLinesToSkip = utils::ReadParam('do_skip_lines', 0);
  295. $bFirstLineAsHeader = utils::ReadParam('header_line', false);
  296. $sData = stripslashes(utils::ReadParam('csvdata', '', false, 'raw_data'));
  297. $sClassName = utils::ReadParam('class_name', '');
  298. $bAdvanced = utils::ReadParam('advanced', false);
  299. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  300. $sInitFieldMapping = utils::ReadParam('init_field_mapping', '', false, 'raw_data');
  301. $sInitSearchField = utils::ReadParam('init_search_field', '', false, 'raw_data');
  302. $aInitFieldMapping = empty($sInitFieldMapping) ? array() : json_decode($sInitFieldMapping, true);
  303. $aInitSearchField = empty($sInitSearchField) ? array() : json_decode($sInitSearchField, true);
  304. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  305. $aData = $oCSVParser->ToArray($iLinesToSkip);
  306. $iTarget = count($aData);
  307. if ($iTarget == 0)
  308. {
  309. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  310. }
  311. else
  312. {
  313. $oPage->add("<table>");
  314. $aFirstLine = $aData[0]; // Use the first row to determine the number of columns
  315. $iStartLine = 0;
  316. $iNbColumns = count($aFirstLine);
  317. if ($bFirstLineAsHeader)
  318. {
  319. $iStartLine = 1;
  320. foreach($aFirstLine as $sField)
  321. {
  322. $aHeader[] = $sField;
  323. }
  324. }
  325. else
  326. {
  327. // Build some conventional name for the fields: field1...fieldn
  328. $index= 1;
  329. foreach($aFirstLine as $sField)
  330. {
  331. $aHeader[] = Dict::Format('UI:CSVImport:FieldName', $index);
  332. $index++;
  333. }
  334. }
  335. $oPage->add("<table>\n");
  336. $oPage->add('<tr>');
  337. $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>');
  338. $oPage->add('</tr>');
  339. $index = 1;
  340. foreach($aHeader as $sField)
  341. {
  342. $sDefaultChoice = null;
  343. if (isset($aInitFieldMapping[$index]))
  344. {
  345. $sDefaultChoice = $aInitFieldMapping[$index];
  346. }
  347. $oPage->add('<tr>');
  348. $oPage->add("<th>$sField</th>");
  349. $oPage->add('<td>'.GetMappingForField($sClassName, $sField, $index, $bAdvanced, $sDefaultChoice).'</td>');
  350. $oPage->add('<td>&nbsp;</td>');
  351. $oPage->add('<td><input id="search_'.$index.'" type="checkbox" name="search_field['.$index.']" value="1" /></td>');
  352. $oPage->add('<td>'.(isset($aData[$iStartLine][$index-1]) ? htmlentities($aData[$iStartLine][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  353. $oPage->add('<td>'.(isset($aData[$iStartLine+1][$index-1]) ? htmlentities($aData[$iStartLine+1][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  354. $oPage->add('</tr>');
  355. $index++;
  356. }
  357. $oPage->add("</table>\n");
  358. if (empty($sInitSearchField))
  359. {
  360. // Propose a reconciliation scheme
  361. //
  362. $aReconciliationKeys = MetaModel::GetReconcKeys($sClassName);
  363. $aMoreReconciliationKeys = array(); // Store: key => void to automatically remove duplicates
  364. foreach($aReconciliationKeys as $sAttCode)
  365. {
  366. if (!MetaModel::IsValidAttCode($sClassName, $sAttCode)) continue;
  367. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  368. if ($oAttDef->IsExternalKey())
  369. {
  370. // An external key is specified as a reconciliation key: this means that all the reconciliation
  371. // keys of this class are proposed to identify the target object
  372. $aMoreReconciliationKeys = array_merge($aMoreReconciliationKeys, GetMappingsForExtKey($sAttCode, $oAttDef, $bAdvanced));
  373. }
  374. elseif($oAttDef->IsExternalField())
  375. {
  376. // An external field is specified as a reconciliation key, translate the field into a field on the target class
  377. // since external fields are not writable, and thus never appears in the mapping form
  378. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  379. $sTargetAttCode = $oAttDef->GetExtAttCode();
  380. $aMoreReconciliationKeys[$sKeyAttCode.'->'.$sTargetAttCode] = '';
  381. }
  382. }
  383. $sDefaultKeys = '"'.implode('", "',array_merge($aReconciliationKeys, array_keys($aMoreReconciliationKeys))).'"';
  384. }
  385. else
  386. {
  387. // The reconciliation scheme is given (navigating back in the wizard)
  388. //
  389. $aDefaultKeys = array();
  390. foreach ($aInitSearchField as $iSearchField => $void)
  391. {
  392. $sAttCodeEx = $aInitFieldMapping[$iSearchField];
  393. $aDefaultKeys[] = $sAttCodeEx;
  394. }
  395. $sDefaultKeys = '"'.implode('", "', $aDefaultKeys).'"';
  396. }
  397. $oPage->add_ready_script(
  398. <<<EOF
  399. $('select[name^=field]').change( DoCheckMapping );
  400. aDefaultKeys = new Array($sDefaultKeys);
  401. DoCheckMapping();
  402. EOF
  403. );
  404. }
  405. break;
  406. case 'get_csv_template':
  407. $sClassName = utils::ReadParam('class_name');
  408. $sFormat = utils::ReadParam('format', 'csv');
  409. if (MetaModel::IsValidClass($sClassName))
  410. {
  411. $oSearch = new DBObjectSearch($sClassName);
  412. $oSearch->AddCondition('id', 0, '='); // Make sure we create an empty set
  413. $oSet = new CMDBObjectSet($oSearch);
  414. $sResult = cmdbAbstractObject::GetSetAsCSV($oSet, array('showMandatoryFields' => true));
  415. $sClassDisplayName = MetaModel::GetName($sClassName);
  416. $sDisposition = utils::ReadParam('disposition', 'inline');
  417. if ($sDisposition == 'attachment')
  418. {
  419. switch($sFormat)
  420. {
  421. case 'xlsx':
  422. $oPage = new ajax_page("");
  423. $oPage->SetContentType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  424. $oPage->SetContentDisposition('attachment', $sClassDisplayName.'.xlsx');
  425. require_once(APPROOT.'/application/excelexporter.class.inc.php');
  426. $writer = new XLSXWriter();
  427. $writer->setAuthor(UserRights::GetUserFriendlyName());
  428. $aHeaders = array( 0 => explode(',', $sResult)); // comma is the default separator
  429. $writer->writeSheet($aHeaders, $sClassDisplayName, array());
  430. $oPage->add($writer->writeToString());
  431. break;
  432. case 'csv':
  433. default:
  434. $oPage = new CSVPage("");
  435. $oPage->add_header("Content-type: text/csv; charset=utf-8");
  436. $oPage->add_header("Content-disposition: attachment; filename=\"{$sClassDisplayName}.csv\"");
  437. $oPage->no_cache();
  438. $oPage->add($sResult);
  439. }
  440. }
  441. else
  442. {
  443. $oPage = new ajax_page("");
  444. $oPage->no_cache();
  445. $oPage->add('<p style="text-align:center">');
  446. $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>');
  447. $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>');
  448. $oPage->add('</p>');
  449. $oPage->add('<p><textarea rows="5" cols="100">'.$sResult.'</textarea></p>');
  450. }
  451. }
  452. else
  453. {
  454. $oPage = new ajax_page("Class $sClassName is not a valid class !");
  455. }
  456. break;
  457. }
  458. $oPage->output();
  459. }
  460. catch (Exception $e)
  461. {
  462. IssueLog::Error($e->getMessage());
  463. }
  464. ?>