ajax.csvimport.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Specific to the interactive csv import
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  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. if ($sFieldName == 'id')
  112. {
  113. $sFieldCode = 'id';
  114. }
  115. if ($bAdvancedMode)
  116. {
  117. $aChoices['id'] = Dict::S('UI:CSVImport:idField');
  118. }
  119. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  120. {
  121. $sStar = '';
  122. if ($oAttDef->IsExternalKey())
  123. {
  124. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  125. {
  126. $sFieldCode = $sAttCode;
  127. }
  128. if ($bAdvancedMode)
  129. {
  130. $aChoices[$sAttCode] = $oAttDef->GetLabel();
  131. }
  132. $oExtKeyAttDef = MetaModel::GetAttributeDef($sClassName, $oAttDef->GetKeyAttCode());
  133. if (!$oExtKeyAttDef->IsNullAllowed())
  134. {
  135. $sStar = '*';
  136. }
  137. // Get fields of the external class that are considered as reconciliation keys
  138. $sTargetClass = $oAttDef->GetTargetClass();
  139. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sTargetAttCode => $oTargetAttDef)
  140. {
  141. if (MetaModel::IsReconcKey($sTargetClass, $sTargetAttCode))
  142. {
  143. $bExtKey = $oTargetAttDef->IsExternalKey();
  144. $sSuffix = '';
  145. if ($bExtKey)
  146. {
  147. $sSuffix = '->id';
  148. }
  149. if ($bAdvancedMode || !$bExtKey)
  150. {
  151. // When not in advanced mode do not allow to use reconciliation keys (on external keys) if they are themselves external keys !
  152. $aChoices[$sAttCode.'->'.$sTargetAttCode] = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel().$sSuffix.$sStar;
  153. if ((strcasecmp($sFieldName, $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel().$sSuffix) == 0) || (strcasecmp($sFieldName, ($sAttCode.'->'.$sTargetAttCode.$sSuffix)) == 0) )
  154. {
  155. $sFieldCode = $sAttCode.'->'.$sTargetAttCode;
  156. }
  157. }
  158. }
  159. }
  160. }
  161. else if ($oAttDef->IsWritable() && (!$oAttDef->IsLinkset() || ($bAdvancedMode && $oAttDef->IsIndirect())))
  162. {
  163. if (!$oAttDef->IsNullAllowed())
  164. {
  165. $sStar = '*';
  166. }
  167. $aChoices[$sAttCode] = $oAttDef->GetLabel().$sStar;
  168. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  169. {
  170. $sFieldCode = $sAttCode;
  171. }
  172. }
  173. }
  174. asort($aChoices);
  175. $sHtml = "<select id=\"mapping_{$iFieldIndex}\" name=\"field[$iFieldIndex]\">\n";
  176. $bIsIdField = IsIdField($sClassName, $sFieldCode);
  177. foreach($aChoices as $sAttCode => $sLabel)
  178. {
  179. $sSelected = '';
  180. if ($bIsIdField && (!$bAdvancedMode)) // When not in advanced mode, ID are mapped to n/a
  181. {
  182. if ($sAttCode == ':none:')
  183. {
  184. $sSelected = ' selected';
  185. }
  186. }
  187. else if (empty($sFieldCode) && (strpos($sFieldName, '->') !== false))
  188. {
  189. if ($sAttCode == ':none:')
  190. {
  191. $sSelected = ' selected';
  192. }
  193. }
  194. else if (is_null($sDefaultChoice) && ($sFieldCode == $sAttCode))
  195. {
  196. $sSelected = ' selected';
  197. }
  198. else if (!is_null($sDefaultChoice) && ($sDefaultChoice == $sAttCode))
  199. {
  200. $sSelected = ' selected';
  201. }
  202. $sHtml .= "<option value=\"$sAttCode\"$sSelected>$sLabel</option>\n";
  203. }
  204. $sHtml .= "</select>\n";
  205. return $sHtml;
  206. }
  207. try
  208. {
  209. require_once(APPROOT.'/application/startup.inc.php');
  210. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  211. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  212. $sOperation = utils::ReadParam('operation', '');
  213. switch($sOperation)
  214. {
  215. case 'parser_preview':
  216. $oPage = new ajax_page("");
  217. $oPage->no_cache();
  218. $oPage->SetContentType('text/html');
  219. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  220. if ($sSeparator == 'tab') $sSeparator = "\t";
  221. $sTextQualifier = utils::ReadParam('qualifier', '"', false, 'raw_data');
  222. $iLinesToSkip = utils::ReadParam('do_skip_lines', 0);
  223. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  224. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  225. $sData = stripslashes(utils::ReadParam('csvdata', true, false, 'raw_data'));
  226. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  227. $aData = $oCSVParser->ToArray($iLinesToSkip);
  228. $iTarget = count($aData);
  229. if ($iTarget == 0)
  230. {
  231. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  232. }
  233. else
  234. {
  235. $sMaxLen = (strlen(''.$iTarget) < 3) ? 3 : strlen(''.$iTarget); // Pad line numbers to the appropriate number of chars, but at least 3
  236. $sFormat = '%0'.$sMaxLen.'d';
  237. $oPage->p("<h3>".Dict::S('UI:Title:DataPreview')."</h3>\n");
  238. $oPage->p("<div style=\"overflow-y:auto\" class=\"white\">\n");
  239. $oPage->add("<table cellspacing=\"0\" style=\"overflow-y:auto\">");
  240. $iMaxIndex= 10; // Display maximum 10 lines for the preview
  241. $index = 1;
  242. foreach($aData as $aRow)
  243. {
  244. $sCSSClass = 'csv_row'.($index % 2);
  245. if ( ($bFirstLineAsHeader) && ($index == 1))
  246. {
  247. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td>");
  248. foreach ($aRow as $sCell)
  249. {
  250. $oPage->add('<th>'.htmlentities($sCell, ENT_QUOTES, 'UTF-8').'</th>');
  251. }
  252. $oPage->add("</tr>\n");
  253. $iNbCols = count($aRow);
  254. }
  255. else
  256. {
  257. if ($index == 1) $iNbCols = count($aRow);
  258. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td>");
  259. foreach ($aRow as $sCell)
  260. {
  261. $oPage->add('<td>'.htmlentities($sCell, ENT_QUOTES, 'UTF-8').'</td>');
  262. }
  263. $oPage->add("</tr>\n");
  264. }
  265. $index++;
  266. if ($index > $iMaxIndex) break;
  267. }
  268. $oPage->add("</table>\n");
  269. $oPage->add("</div>\n");
  270. if($iNbCols == 1)
  271. {
  272. $oPage->p('<img src="../images/error.png">&nbsp;'.Dict::S('UI:CSVImport:ErrorOnlyOneColumn'));
  273. }
  274. else
  275. {
  276. $oPage->p('&nbsp;');
  277. }
  278. }
  279. break;
  280. case 'display_mapping_form':
  281. $oPage = new ajax_page("");
  282. $oPage->no_cache();
  283. $oPage->SetContentType('text/html');
  284. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  285. $sTextQualifier = utils::ReadParam('qualifier', '"', false, 'raw_data');
  286. $iLinesToSkip = utils::ReadParam('do_skip_lines', 0);
  287. $bFirstLineAsHeader = utils::ReadParam('header_line', false);
  288. $sData = stripslashes(utils::ReadParam('csvdata', '', false, 'raw_data'));
  289. $sClassName = utils::ReadParam('class_name', '');
  290. $bAdvanced = utils::ReadParam('advanced', false);
  291. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  292. $sInitFieldMapping = utils::ReadParam('init_field_mapping', '', false, 'raw_data');
  293. $sInitSearchField = utils::ReadParam('init_search_field', '', false, 'raw_data');
  294. $aInitFieldMapping = empty($sInitFieldMapping) ? array() : json_decode($sInitFieldMapping, true);
  295. $aInitSearchField = empty($sInitSearchField) ? array() : json_decode($sInitSearchField, true);
  296. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  297. $aData = $oCSVParser->ToArray($iLinesToSkip);
  298. $iTarget = count($aData);
  299. if ($iTarget == 0)
  300. {
  301. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  302. }
  303. else
  304. {
  305. $oPage->add("<table>");
  306. $aFirstLine = $aData[0]; // Use the first row to determine the number of columns
  307. $iStartLine = 0;
  308. $iNbColumns = count($aFirstLine);
  309. if ($bFirstLineAsHeader)
  310. {
  311. $iStartLine = 1;
  312. foreach($aFirstLine as $sField)
  313. {
  314. $aHeader[] = $sField;
  315. }
  316. }
  317. else
  318. {
  319. // Build some conventional name for the fields: field1...fieldn
  320. $index= 1;
  321. foreach($aFirstLine as $sField)
  322. {
  323. $aHeader[] = Dict::Format('UI:CSVImport:FieldName', $index);
  324. $index++;
  325. }
  326. }
  327. $oPage->add("<table>\n");
  328. $oPage->add('<tr>');
  329. $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>');
  330. $oPage->add('</tr>');
  331. $index = 1;
  332. foreach($aHeader as $sField)
  333. {
  334. $sDefaultChoice = null;
  335. if (isset($aInitFieldMapping[$index]))
  336. {
  337. $sDefaultChoice = $aInitFieldMapping[$index];
  338. }
  339. $oPage->add('<tr>');
  340. $oPage->add("<th>$sField</th>");
  341. $oPage->add('<td>'.GetMappingForField($sClassName, $sField, $index, $bAdvanced, $sDefaultChoice).'</td>');
  342. $oPage->add('<td>&nbsp;</td>');
  343. $oPage->add('<td><input id="search_'.$index.'" type="checkbox" name="search_field['.$index.']" value="1" /></td>');
  344. $oPage->add('<td>'.(isset($aData[$iStartLine][$index-1]) ? htmlentities($aData[$iStartLine][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  345. $oPage->add('<td>'.(isset($aData[$iStartLine+1][$index-1]) ? htmlentities($aData[$iStartLine+1][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  346. $oPage->add('</tr>');
  347. $index++;
  348. }
  349. $oPage->add("</table>\n");
  350. if (empty($sInitSearchField))
  351. {
  352. // Propose a reconciliation scheme
  353. //
  354. $aReconciliationKeys = MetaModel::GetReconcKeys($sClassName);
  355. $aMoreReconciliationKeys = array(); // Store: key => void to automatically remove duplicates
  356. foreach($aReconciliationKeys as $sAttCode)
  357. {
  358. if (!MetaModel::IsValidAttCode($sClassName, $sAttCode)) continue;
  359. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  360. if ($oAttDef->IsExternalKey())
  361. {
  362. // An external key is specified as a reconciliation key: this means that all the reconciliation
  363. // keys of this class are proposed to identify the target object
  364. $aMoreReconciliationKeys = array_merge($aMoreReconciliationKeys, GetMappingsForExtKey($sAttCode, $oAttDef, $bAdvanced));
  365. }
  366. elseif($oAttDef->IsExternalField())
  367. {
  368. // An external field is specified as a reconciliation key, translate the field into a field on the target class
  369. // since external fields are not writable, and thus never appears in the mapping form
  370. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  371. $sTargetAttCode = $oAttDef->GetExtAttCode();
  372. $aMoreReconciliationKeys[$sKeyAttCode.'->'.$sTargetAttCode] = '';
  373. }
  374. }
  375. $sDefaultKeys = '"'.implode('", "',array_merge($aReconciliationKeys, array_keys($aMoreReconciliationKeys))).'"';
  376. }
  377. else
  378. {
  379. // The reconciliation scheme is given (navigating back in the wizard)
  380. //
  381. $aDefaultKeys = array();
  382. foreach ($aInitSearchField as $iSearchField => $void)
  383. {
  384. $sAttCodeEx = $aInitFieldMapping[$iSearchField];
  385. $aDefaultKeys[] = $sAttCodeEx;
  386. }
  387. $sDefaultKeys = '"'.implode('", "', $aDefaultKeys).'"';
  388. }
  389. $oPage->add_ready_script(
  390. <<<EOF
  391. $('select[name^=field]').change( DoCheckMapping );
  392. aDefaultKeys = new Array($sDefaultKeys);
  393. DoCheckMapping();
  394. EOF
  395. );
  396. }
  397. break;
  398. case 'get_csv_template':
  399. $sClassName = utils::ReadParam('class_name');
  400. if (MetaModel::IsValidClass($sClassName))
  401. {
  402. $oSearch = new DBObjectSearch($sClassName);
  403. $oSearch->AddCondition('id', 0, '='); // Make sure we create an empty set
  404. $oSet = new CMDBObjectSet($oSearch);
  405. $sResult = cmdbAbstractObject::GetSetAsCSV($oSet, array('showMandatoryFields' => true));
  406. $sClassDisplayName = MetaModel::GetName($sClassName);
  407. $sDisposition = utils::ReadParam('disposition', 'inline');
  408. if ($sDisposition == 'attachment')
  409. {
  410. $oPage = new CSVPage("");
  411. $oPage->add_header("Content-type: text/csv; charset=utf-8");
  412. $oPage->add_header("Content-disposition: attachment; filename=\"{$sClassDisplayName}.csv\"");
  413. $oPage->no_cache();
  414. $oPage->add($sResult);
  415. }
  416. else
  417. {
  418. $oPage = new ajax_page("");
  419. $oPage->no_cache();
  420. $oPage->add('<p style="text-align:center"><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></p>');
  421. $oPage->add('<p><textarea rows="5" cols="100">'.$sResult.'</textarea></p>');
  422. }
  423. }
  424. else
  425. {
  426. $oPage = new ajax_page("Class $sClassName is not a valid class !");
  427. }
  428. break;
  429. }
  430. $oPage->output();
  431. }
  432. catch (Exception $e)
  433. {
  434. IssueLog::Error($e->getMessage());
  435. }
  436. ?>