ajax.csvimport.php 12 KB

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