ajax.csvimport.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. * @return string The HTML code corresponding to the drop-down list for this field
  97. */
  98. function GetMappingForField($sClassName, $sFieldName, $iFieldIndex, $bAdvancedMode = false)
  99. {
  100. $aChoices = array('' => Dict::S('UI:CSVImport:MappingSelectOne'));
  101. $aChoices[':none:'] = Dict::S('UI:CSVImport:MappingNotApplicable');
  102. $sFieldCode = ''; // Code of the attribute, if there is a match
  103. $aMatches = array();
  104. if (preg_match('/^(.+)\*$/', $sFieldName, $aMatches))
  105. {
  106. // Remove any trailing "star" character.
  107. // A star character at the end can be used to indicate a mandatory field
  108. $sFieldName = $aMatches[1];
  109. }
  110. if ($sFieldName == 'id')
  111. {
  112. $sFieldCode = 'id';
  113. }
  114. if ($bAdvancedMode)
  115. {
  116. $aChoices['id'] = Dict::S('UI:CSVImport:idField');
  117. }
  118. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  119. {
  120. $sStar = '';
  121. if ($oAttDef->IsExternalKey())
  122. {
  123. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  124. {
  125. $sFieldCode = $sAttCode;
  126. }
  127. if ($bAdvancedMode)
  128. {
  129. $aChoices[$sAttCode] = $oAttDef->GetLabel();
  130. }
  131. $oExtKeyAttDef = MetaModel::GetAttributeDef($sClassName, $oAttDef->GetKeyAttCode());
  132. if (!$oExtKeyAttDef->IsNullAllowed())
  133. {
  134. $sStar = '*';
  135. }
  136. // Get fields of the external class that are considered as reconciliation keys
  137. $sTargetClass = $oAttDef->GetTargetClass();
  138. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sTargetAttCode => $oTargetAttDef)
  139. {
  140. if (MetaModel::IsReconcKey($sTargetClass, $sTargetAttCode))
  141. {
  142. $bExtKey = $oTargetAttDef->IsExternalKey();
  143. $sSuffix = '';
  144. if ($bExtKey)
  145. {
  146. $sSuffix = '->id';
  147. }
  148. if ($bAdvancedMode || !$bExtKey)
  149. {
  150. // When not in advanced mode do not allow to use reconciliation keys (on external keys) if they are themselves external keys !
  151. $aChoices[$sAttCode.'->'.$sTargetAttCode] = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel().$sSuffix.$sStar;
  152. if ((strcasecmp($sFieldName, $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel().$sSuffix) == 0) || (strcasecmp($sFieldName, ($sAttCode.'->'.$sTargetAttCode.$sSuffix)) == 0) )
  153. {
  154. $sFieldCode = $sAttCode.'->'.$sTargetAttCode;
  155. }
  156. }
  157. }
  158. }
  159. }
  160. else if ($oAttDef->IsWritable() && (!$oAttDef->IsLinkset() || ($bAdvancedMode && $oAttDef->IsIndirect())))
  161. {
  162. if (!$oAttDef->IsNullAllowed())
  163. {
  164. $sStar = '*';
  165. }
  166. $aChoices[$sAttCode] = $oAttDef->GetLabel().$sStar;
  167. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  168. {
  169. $sFieldCode = $sAttCode;
  170. }
  171. }
  172. }
  173. asort($aChoices);
  174. $sHtml = "<select id=\"mapping_{$iFieldIndex}\" name=\"field[$iFieldIndex]\">\n";
  175. $bIsIdField = IsIdField($sClassName, $sFieldCode);
  176. foreach($aChoices as $sAttCode => $sLabel)
  177. {
  178. $sSelected = '';
  179. if ($bIsIdField && (!$bAdvancedMode)) // When not in advanced mode, ID are mapped to n/a
  180. {
  181. if ($sAttCode == ':none:')
  182. {
  183. $sSelected = ' selected';
  184. }
  185. }
  186. else if (empty($sFieldCode) && (strpos($sFieldName, '->') !== false))
  187. {
  188. if ($sAttCode == ':none:')
  189. {
  190. $sSelected = ' selected';
  191. }
  192. }
  193. else if ($sFieldCode == $sAttCode) // Otherwise map by default if there is a match
  194. {
  195. $sSelected = ' selected';
  196. }
  197. $sHtml .= "<option value=\"$sAttCode\"$sSelected>$sLabel</option>\n";
  198. }
  199. $sHtml .= "</select>\n";
  200. return $sHtml;
  201. }
  202. try
  203. {
  204. require_once(APPROOT.'/application/startup.inc.php');
  205. require_once(APPROOT.'/application/loginwebpage.class.inc.php');
  206. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  207. $sOperation = utils::ReadParam('operation', '');
  208. switch($sOperation)
  209. {
  210. case 'parser_preview':
  211. $oPage = new ajax_page("");
  212. $oPage->no_cache();
  213. $sSeparator = utils::ReadParam('separator', ',');
  214. if ($sSeparator == 'tab') $sSeparator = "\t";
  215. $sTextQualifier = utils::ReadParam('qualifier', '"');
  216. $iLinesToSkip = utils::ReadParam('nb_lines_skipped', 0);
  217. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  218. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  219. $sData = stripslashes(utils::ReadParam('csvdata', true));
  220. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  221. $aData = $oCSVParser->ToArray($iLinesToSkip);
  222. $iTarget = count($aData);
  223. if ($iTarget == 0)
  224. {
  225. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  226. }
  227. else
  228. {
  229. $sMaxLen = (strlen(''.$iTarget) < 3) ? 3 : strlen(''.$iTarget); // Pad line numbers to the appropriate number of chars, but at least 3
  230. $sFormat = '%0'.$sMaxLen.'d';
  231. $oPage->p("<h3>".Dict::S('UI:Title:DataPreview')."</h3>\n");
  232. $oPage->p("<div style=\"overflow-y:auto\" class=\"white\">\n");
  233. $oPage->add("<table cellspacing=\"0\" style=\"overflow-y:auto\">");
  234. $iMaxIndex= 10; // Display maximum 10 lines for the preview
  235. $index = 1;
  236. foreach($aData as $aRow)
  237. {
  238. $sCSSClass = 'csv_row'.($index % 2);
  239. if ( ($bFirstLineAsHeader) && ($index == 1))
  240. {
  241. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td><th>");
  242. $oPage->add(implode('</th><th>', $aRow));
  243. $oPage->add("</th></tr>\n");
  244. $iNbCols = count($aRow);
  245. }
  246. else
  247. {
  248. if ($index == 1) $iNbCols = count($aRow);
  249. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td><td>");
  250. $oPage->add(implode('</td><td>', $aRow));
  251. $oPage->add("</td></tr>\n");
  252. }
  253. $index++;
  254. if ($index > $iMaxIndex) break;
  255. }
  256. $oPage->add("</table>\n");
  257. $oPage->add("</div>\n");
  258. if($iNbCols == 1)
  259. {
  260. $oPage->p('<img src="../images/error.png">&nbsp;'.Dict::S('UI:CSVImport:ErrorOnlyOneColumn'));
  261. }
  262. else
  263. {
  264. $oPage->p('&nbsp;');
  265. }
  266. }
  267. break;
  268. case 'display_mapping_form':
  269. $oPage = new ajax_page("");
  270. $oPage->no_cache();
  271. $sSeparator = utils::ReadParam('separator', ',');
  272. $sTextQualifier = utils::ReadParam('qualifier', '"');
  273. $iLinesToSkip = utils::ReadParam('nb_lines_skipped', 0);
  274. $bFirstLineAsHeader = utils::ReadParam('header_line', false);
  275. $sData = stripslashes(utils::ReadParam('csvdata', ''));
  276. $sClassName = utils::ReadParam('class_name', '');
  277. $bAdvanced = utils::ReadParam('advanced', false);
  278. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  279. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  280. $aData = $oCSVParser->ToArray($iLinesToSkip);
  281. $iTarget = count($aData);
  282. if ($iTarget == 0)
  283. {
  284. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  285. }
  286. else
  287. {
  288. $oPage->add("<table>");
  289. $aFirstLine = $aData[0]; // Use the first row to determine the number of columns
  290. $iStartLine = 0;
  291. $iNbColumns = count($aFirstLine);
  292. if ($bFirstLineAsHeader)
  293. {
  294. $iStartLine = 1;
  295. foreach($aFirstLine as $sField)
  296. {
  297. $aHeader[] = $sField;
  298. }
  299. }
  300. else
  301. {
  302. // Build some conventional name for the fields: field1...fieldn
  303. $index= 1;
  304. foreach($aFirstLine as $sField)
  305. {
  306. $aHeader[] = Dict::Format('UI:CSVImport:FieldName', $index);
  307. $index++;
  308. }
  309. }
  310. $oPage->add("<table>\n");
  311. $oPage->add('<tr>');
  312. $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>');
  313. $oPage->add('</tr>');
  314. $index = 1;
  315. foreach($aHeader as $sField)
  316. {
  317. $oPage->add('<tr>');
  318. $oPage->add("<th>$sField</th>");
  319. $oPage->add('<td>'.GetMappingForField($sClassName, $sField, $index, $bAdvanced).'</td>');
  320. $oPage->add('<td>&nbsp;</td>');
  321. $oPage->add('<td><input id="search_'.$index.'" type="checkbox" name="search_field['.$index.']" value="1" /></td>');
  322. $oPage->add('<td>'.(isset($aData[$iStartLine][$index-1]) ? htmlentities($aData[$iStartLine][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  323. $oPage->add('<td>'.(isset($aData[$iStartLine+1][$index-1]) ? htmlentities($aData[$iStartLine+1][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  324. $oPage->add('</tr>');
  325. $index++;
  326. }
  327. $oPage->add("</table>\n");
  328. $aReconciliationKeys = MetaModel::GetReconcKeys($sClassName);
  329. $aMoreReconciliationKeys = array(); // Store: key => void to automatically remove duplicates
  330. foreach($aReconciliationKeys as $sAttCode)
  331. {
  332. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  333. if ($oAttDef->IsExternalKey())
  334. {
  335. // An external key is specified as a reconciliation key: this means that all the reconciliation
  336. // keys of this class are proposed to identify the target object
  337. $aMoreReconciliationKeys = array_merge($aMoreReconciliationKeys, GetMappingsForExtKey($sAttCode, $oAttDef, $bAdvanced));
  338. }
  339. elseif($oAttDef->IsExternalField())
  340. {
  341. // An external field is specified as a reconciliation key, translate the field into a field on the target class
  342. // since external fields are not writable, and thus never appears in the mapping form
  343. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  344. $sTargetAttCode = $oAttDef->GetExtAttCode();
  345. $aMoreReconciliationKeys[$sKeyAttCode.'->'.$sTargetAttCode] = '';
  346. }
  347. }
  348. $sDefaultKeys = '"'.implode('", "',array_merge($aReconciliationKeys, array_keys($aMoreReconciliationKeys))).'"';
  349. $oPage->add_ready_script(
  350. <<<EOF
  351. $('select[name^=field]').change( DoCheckMapping );
  352. aDefaultKeys = new Array($sDefaultKeys);
  353. DoCheckMapping();
  354. EOF
  355. );
  356. }
  357. break;
  358. case 'get_csv_template':
  359. $sClassName = utils::ReadParam('class_name');
  360. $oSearch = new DBObjectSearch($sClassName);
  361. $oSearch->AddCondition('id', 0, '='); // Make sure we create an empty set
  362. $oSet = new CMDBObjectSet($oSearch);
  363. $sResult = cmdbAbstractObject::GetSetAsCSV($oSet, array('showMandatoryFields' => true));
  364. //$aCSV = explode("\n", $sCSV);
  365. // If there are more than one line, let's assume that the first line is a comment and skip it.
  366. //if (count($aCSV) > 1)
  367. //{
  368. // $sResult = $aCSV[0];
  369. //}
  370. //else
  371. //{
  372. // $sResult = $sCSV;
  373. //}
  374. $sClassDisplayName = MetaModel::GetName($sClassName);
  375. $sDisposition = utils::ReadParam('disposition', 'inline');
  376. if ($sDisposition == 'attachment')
  377. {
  378. $oPage = new CSVPage("");
  379. $oPage->add_header("Content-type: text/csv; charset=utf-8");
  380. $oPage->add_header("Content-disposition: attachment; filename=\"{$sClassDisplayName}.csv\"");
  381. $oPage->no_cache();
  382. $oPage->add($sResult);
  383. }
  384. else
  385. {
  386. $oPage = new ajax_page("");
  387. $oPage->no_cache();
  388. $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>');
  389. $oPage->add('<p><textarea rows="5" cols="100">'.$sResult.'</textarea></p>');
  390. }
  391. break;
  392. }
  393. $oPage->output();
  394. }
  395. catch (Exception $e)
  396. {
  397. IssueLog::Error($e->getMessage());
  398. }
  399. ?>