ajax.csvimport.php 15 KB

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