ajax.csvimport.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. * @return Ash List of codes=>display name: xxx->yyy where yyy are the reconciliation keys for the object xxx
  58. */
  59. function GetMappingsForExtKey($sAttCode, AttributeDefinition $oExtKeyAttDef)
  60. {
  61. $aResult = array();
  62. $sTargetClass = $oExtKeyAttDef->GetTargetClass();
  63. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sTargetAttCode => $oTargetAttDef)
  64. {
  65. if (MetaModel::IsReconcKey($sTargetClass, $sTargetAttCode))
  66. {
  67. $aResult[$sAttCode.'->'.$sTargetAttCode] = $oExtKeyAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  68. }
  69. }
  70. return $aResult;
  71. }
  72. /**
  73. * Helper function to build the mapping drop-down list for a field
  74. * Spec: Possible choices are "writable" fields in this class plus external fields that are listed as reconciliation keys
  75. * for any class pointed to by an external key in the current class.
  76. * If not in advanced mode, all "id" fields (id and external keys) must be mapped to ":none:" (i.e -- ignore this field --)
  77. * External fields that do not correspond to a reconciliation key must be mapped to ":none:"
  78. * Otherwise, if a field equals either the 'code' or the 'label' (translated) of a field, then it's mapped automatically
  79. * @param string $sClassName Name of the class used for the mapping
  80. * @param string $sFieldName Name of the field, as it comes from the data file (header line)
  81. * @param integer $iFieldIndex Number of the field in the sequence
  82. * @param bool $bAdvancedMode Whether or not advanced mode was chosen
  83. * @return string The HTML code corresponding to the drop-down list for this field
  84. */
  85. function GetMappingForField($sClassName, $sFieldName, $iFieldIndex, $bAdvancedMode = false)
  86. {
  87. $aChoices = array('' => Dict::S('UI:CSVImport:MappingSelectOne'));
  88. $aChoices[':none:'] = Dict::S('UI:CSVImport:MappingNotApplicable');
  89. $sFieldCode = ''; // Code of the attribute, if there is a match
  90. if ($sFieldName == 'id')
  91. {
  92. $sFieldCode = 'id';
  93. }
  94. if ($bAdvancedMode)
  95. {
  96. $aChoices['id'] = Dict::S('UI:CSVImport:idField');
  97. }
  98. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  99. {
  100. if ($oAttDef->IsExternalKey())
  101. {
  102. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  103. {
  104. $sFieldCode = $sAttCode;
  105. }
  106. if ($bAdvancedMode)
  107. {
  108. $aChoices[$sAttCode] = $oAttDef->GetLabel();
  109. }
  110. // Get fields of the external class that are considered as reconciliation keys
  111. $sTargetClass = $oAttDef->GetTargetClass();
  112. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sTargetAttCode => $oTargetAttDef)
  113. {
  114. if (MetaModel::IsReconcKey($sTargetClass, $sTargetAttCode))
  115. {
  116. $aChoices[$sAttCode.'->'.$sTargetAttCode] = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  117. if ((strcasecmp($sFieldName, $aChoices[$sAttCode.'->'.$sTargetAttCode]) == 0) || (strcasecmp($sFieldName, ($sAttCode.'->'.$sTargetAttCode)) == 0) )
  118. {
  119. $sFieldCode = $sAttCode.'->'.$sTargetAttCode;
  120. }
  121. }
  122. }
  123. }
  124. else if ($oAttDef->IsWritable())
  125. {
  126. $aChoices[$sAttCode] = $oAttDef->GetLabel();
  127. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  128. {
  129. $sFieldCode = $sAttCode;
  130. }
  131. }
  132. }
  133. asort($aChoices);
  134. $sHtml = "<select id=\"mapping_{$iFieldIndex}\" name=\"field[$iFieldIndex]\">\n";
  135. $bIsIdField = IsIdField($sClassName, $sFieldCode);
  136. foreach($aChoices as $sAttCode => $sLabel)
  137. {
  138. $sSelected = '';
  139. if ($bIsIdField && (!$bAdvancedMode)) // When not in advanced mode, ID are mapped to n/a
  140. {
  141. if ($sAttCode == ':none:')
  142. {
  143. $sSelected = ' selected';
  144. }
  145. }
  146. else if (empty($sFieldCode) && (strpos($sFieldName, '->') !== false))
  147. {
  148. if ($sAttCode == ':none:')
  149. {
  150. $sSelected = ' selected';
  151. }
  152. }
  153. else if ($sFieldCode == $sAttCode) // Otherwise map by default if there is a match
  154. {
  155. $sSelected = ' selected';
  156. }
  157. $sHtml .= "<option value=\"$sAttCode\"$sSelected>$sLabel</option>\n";
  158. }
  159. $sHtml .= "</select>\n";
  160. return $sHtml;
  161. }
  162. require_once('../application/startup.inc.php');
  163. session_start();
  164. if (isset($_SESSION['auth_user']))
  165. {
  166. $sAuthUser = $_SESSION['auth_user'];
  167. $sAuthPwd = $_SESSION['auth_pwd'];
  168. // Attempt to login, fails silently
  169. UserRights::Login($sAuthUser, $sAuthPwd);
  170. }
  171. else
  172. {
  173. // No session information
  174. echo "<p>No session information</p>\n";
  175. }
  176. $oContext = new UserContext();
  177. $sOperation = utils::ReadParam('operation', '');
  178. switch($sOperation)
  179. {
  180. case 'parser_preview':
  181. $oPage = new ajax_page("");
  182. $oPage->no_cache();
  183. $sSeparator = utils::ReadParam('separator', ',');
  184. if ($sSeparator == 'tab') $sSeparator = "\t";
  185. $sTextQualifier = utils::ReadParam('qualifier', '"');
  186. $iLinesToSkip = utils::ReadParam('nb_lines_skipped', 0);
  187. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  188. $sData = stripslashes(utils::ReadParam('csvdata', true));
  189. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  190. $aData = $oCSVParser->ToArray($iLinesToSkip);
  191. $iTarget = count($aData);
  192. if ($iTarget == 0)
  193. {
  194. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  195. }
  196. else
  197. {
  198. $sMaxLen = (strlen(''.$iTarget) < 3) ? 3 : strlen(''.$iTarget); // Pad line numbers to the appropriate number of chars, but at least 3
  199. $sFormat = '%0'.$sMaxLen.'d';
  200. $oPage->p("<h3>".Dict::S('UI:Title:DataPreview')."</h3>\n");
  201. $oPage->p("<div style=\"overflow-y:auto\" class=\"white\">\n");
  202. $oPage->add("<table cellspacing=\"0\" style=\"overflow-y:auto\">");
  203. $iMaxIndex= 10; // Display maximum 10 lines for the preview
  204. $index = 1;
  205. foreach($aData as $aRow)
  206. {
  207. $sCSSClass = 'csv_row'.($index % 2);
  208. if ( ($bFirstLineAsHeader) && ($index == 1))
  209. {
  210. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td><th>");
  211. $oPage->add(implode('</th><th>', $aRow));
  212. $oPage->add("</th></tr>\n");
  213. $iNbCols = count($aRow);
  214. }
  215. else
  216. {
  217. if ($index == 1) $iNbCols = count($aRow);
  218. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td><td>");
  219. $oPage->add(implode('</td><td>', $aRow));
  220. $oPage->add("</td></tr>\n");
  221. }
  222. $index++;
  223. if ($index > $iMaxIndex) break;
  224. }
  225. $oPage->add("</table>\n");
  226. $oPage->add("</div>\n");
  227. if($iNbCols == 1)
  228. {
  229. $oPage->p('<img src="../images/error.png">&nbsp;'.Dict::S('UI:CSVImport:ErrorOnlyOneColumn'));
  230. }
  231. else
  232. {
  233. $oPage->p('&nbsp;');
  234. }
  235. }
  236. break;
  237. case 'display_mapping_form':
  238. $oPage = new ajax_page("");
  239. $oPage->no_cache();
  240. $sSeparator = utils::ReadParam('separator', ',');
  241. $sTextQualifier = utils::ReadParam('qualifier', '"');
  242. $iLinesToSkip = utils::ReadParam('nb_lines_skipped', 0);
  243. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  244. $sData = stripslashes(utils::ReadParam('csvdata', true));
  245. $sClassName = utils::ReadParam('class_name', '');
  246. $bAdvanced = utils::ReadParam('advanced', false);
  247. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  248. $aData = $oCSVParser->ToArray($iLinesToSkip);
  249. $iTarget = count($aData);
  250. if ($iTarget == 0)
  251. {
  252. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  253. }
  254. else
  255. {
  256. $oPage->add("<table>");
  257. $index = 1;
  258. $aFirstLine = $aData[0]; // Use the first row to determine the number of columns
  259. $iStartLine = 0;
  260. $iNbColumns = count($aFirstLine);
  261. if ($bFirstLineAsHeader)
  262. { $iStartLine = 1;
  263. foreach($aFirstLine as $sField)
  264. {
  265. $aHeader[] = $sField;
  266. }
  267. }
  268. else
  269. {
  270. // Build some conventional name for the fields: field1...fieldn
  271. $index= 1;
  272. foreach($aFirstLine as $sField)
  273. {
  274. $aHeader[] = Dict::Format('UI:CSVImport:FieldName', $index);
  275. $index++;
  276. }
  277. }
  278. $oPage->add("<table>\n");
  279. $oPage->add('<tr>');
  280. $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>');
  281. $oPage->add('</tr>');
  282. foreach($aHeader as $sField)
  283. {
  284. $oPage->add('<tr>');
  285. $oPage->add("<th>$sField</th>");
  286. $oPage->add('<td>'.GetMappingForField($sClassName, $sField, $index, $bAdvanced).'</td>');
  287. $oPage->add('<td>&nbsp;</td>');
  288. $oPage->add('<td><input id="search_'.$index.'" type="checkbox" name="search_field['.$index.']" value="1" /></td>');
  289. $oPage->add('<td>'.(isset($aData[$iStartLine][$index-1]) ? htmlentities($aData[$iStartLine][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  290. $oPage->add('<td>'.(isset($aData[$iStartLine+1][$index-1]) ? htmlentities($aData[$iStartLine+1][$index-1], ENT_QUOTES, 'UTF-8') : '&nbsp;').'</td>');
  291. $oPage->add('</tr>');
  292. $index++;
  293. }
  294. $oPage->add("</table>\n");
  295. $aReconciliationKeys = MetaModel::GetReconcKeys($sClassName);
  296. $aMoreReconciliationKeys = array();
  297. foreach($aReconciliationKeys as $sAttCode)
  298. {
  299. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  300. if ($oAttDef->IsExternalKey())
  301. {
  302. $aMoreReconciliationKeys = array_keys(GetMappingsForExtKey($sAttCode, $oAttDef));
  303. }
  304. }
  305. $sDefaultKeys = '"'.implode('", "',array_merge($aReconciliationKeys,$aMoreReconciliationKeys)).'"';
  306. $oPage->add_ready_script(
  307. <<<EOF
  308. $('select[name^=field]').change( DoCheckMapping );
  309. aDefaultKeys = new Array($sDefaultKeys);
  310. DoCheckMapping();
  311. EOF
  312. );
  313. }
  314. break;
  315. case 'get_csv_template':
  316. $sClassName = utils::ReadParam('class_name');
  317. $oSearch = new DBObjectSearch($sClassName);
  318. $oSearch->AddCondition('id', 0); // Make sure we create an empty set
  319. $oSet = new CMDBObjectSet($oSearch);
  320. $sResult = cmdbAbstractObject::GetSetAsCSV($oSet);
  321. //$aCSV = explode("\n", $sCSV);
  322. // If there are more than one line, let's assume that the first line is a comment and skip it.
  323. //if (count($aCSV) > 1)
  324. //{
  325. // $sResult = $aCSV[0];
  326. //}
  327. //else
  328. //{
  329. // $sResult = $sCSV;
  330. //}
  331. $sClassDisplayName = MetaModel::GetName($sClassName);
  332. $sDisposition = utils::ReadParam('disposition', 'inline');
  333. if ($sDisposition == 'attachment')
  334. {
  335. $oPage = new CSVPage("");
  336. $oPage->add_header("Content-disposition: attachment; filename=\"{$sClassDisplayName}.csv\"");
  337. $oPage->no_cache();
  338. $oPage->add($sResult);
  339. }
  340. else
  341. {
  342. $oPage = new ajax_page("");
  343. $oPage->no_cache();
  344. $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>');
  345. $oPage->add('<p><textarea rows="5" cols="100">'.$sResult.'</textarea></p>');
  346. }
  347. break;
  348. }
  349. $oPage->output();
  350. ?>