ajax.csvimport.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. if ($bAdvanced || !$oTargetAttDef->IsExternalKey())
  70. {
  71. // When not in advanced mode do not allow to use reconciliation keys (on external keys) if they are themselves external keys !
  72. $aResult[$sAttCode.'->'.$sTargetAttCode] = $oExtKeyAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  73. }
  74. }
  75. }
  76. return $aResult;
  77. }
  78. /**
  79. * Helper function to build the mapping drop-down list for a field
  80. * Spec: Possible choices are "writable" fields in this class plus external fields that are listed as reconciliation keys
  81. * for any class pointed to by an external key in the current class.
  82. * If not in advanced mode, all "id" fields (id and external keys) must be mapped to ":none:" (i.e -- ignore this field --)
  83. * External fields that do not correspond to a reconciliation key must be mapped to ":none:"
  84. * Otherwise, if a field equals either the 'code' or the 'label' (translated) of a field, then it's mapped automatically
  85. * @param string $sClassName Name of the class used for the mapping
  86. * @param string $sFieldName Name of the field, as it comes from the data file (header line)
  87. * @param integer $iFieldIndex Number of the field in the sequence
  88. * @param bool $bAdvancedMode Whether or not advanced mode was chosen
  89. * @return string The HTML code corresponding to the drop-down list for this field
  90. */
  91. function GetMappingForField($sClassName, $sFieldName, $iFieldIndex, $bAdvancedMode = false)
  92. {
  93. $aChoices = array('' => Dict::S('UI:CSVImport:MappingSelectOne'));
  94. $aChoices[':none:'] = Dict::S('UI:CSVImport:MappingNotApplicable');
  95. $sFieldCode = ''; // Code of the attribute, if there is a match
  96. if ($sFieldName == 'id')
  97. {
  98. $sFieldCode = 'id';
  99. }
  100. if ($bAdvancedMode)
  101. {
  102. $aChoices['id'] = Dict::S('UI:CSVImport:idField');
  103. }
  104. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  105. {
  106. if ($oAttDef->IsExternalKey())
  107. {
  108. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  109. {
  110. $sFieldCode = $sAttCode;
  111. }
  112. if ($bAdvancedMode)
  113. {
  114. $aChoices[$sAttCode] = $oAttDef->GetLabel();
  115. }
  116. // Get fields of the external class that are considered as reconciliation keys
  117. $sTargetClass = $oAttDef->GetTargetClass();
  118. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sTargetAttCode => $oTargetAttDef)
  119. {
  120. if (MetaModel::IsReconcKey($sTargetClass, $sTargetAttCode))
  121. {
  122. if ($bAdvancedMode || (!$oTargetAttDef->IsExternalKey()))
  123. {
  124. // When not in advanced mode do not allow to use reconciliation keys (on external keys) if they are themselves external keys !
  125. $aChoices[$sAttCode.'->'.$sTargetAttCode] = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  126. if ((strcasecmp($sFieldName, $aChoices[$sAttCode.'->'.$sTargetAttCode]) == 0) || (strcasecmp($sFieldName, ($sAttCode.'->'.$sTargetAttCode)) == 0) )
  127. {
  128. $sFieldCode = $sAttCode.'->'.$sTargetAttCode;
  129. }
  130. }
  131. }
  132. }
  133. }
  134. else if ( ($oAttDef->IsWritable()) && (!$oAttDef->IsLinkSet()) )
  135. {
  136. $aChoices[$sAttCode] = $oAttDef->GetLabel();
  137. if ( ($sFieldName == $oAttDef->GetLabel()) || ($sFieldName == $sAttCode))
  138. {
  139. $sFieldCode = $sAttCode;
  140. }
  141. }
  142. }
  143. asort($aChoices);
  144. $sHtml = "<select id=\"mapping_{$iFieldIndex}\" name=\"field[$iFieldIndex]\">\n";
  145. $bIsIdField = IsIdField($sClassName, $sFieldCode);
  146. foreach($aChoices as $sAttCode => $sLabel)
  147. {
  148. $sSelected = '';
  149. if ($bIsIdField && (!$bAdvancedMode)) // When not in advanced mode, ID are mapped to n/a
  150. {
  151. if ($sAttCode == ':none:')
  152. {
  153. $sSelected = ' selected';
  154. }
  155. }
  156. else if (empty($sFieldCode) && (strpos($sFieldName, '->') !== false))
  157. {
  158. if ($sAttCode == ':none:')
  159. {
  160. $sSelected = ' selected';
  161. }
  162. }
  163. else if ($sFieldCode == $sAttCode) // Otherwise map by default if there is a match
  164. {
  165. $sSelected = ' selected';
  166. }
  167. $sHtml .= "<option value=\"$sAttCode\"$sSelected>$sLabel</option>\n";
  168. }
  169. $sHtml .= "</select>\n";
  170. return $sHtml;
  171. }
  172. require_once('../application/startup.inc.php');
  173. require_once('../application/loginwebpage.class.inc.php');
  174. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  175. $sOperation = utils::ReadParam('operation', '');
  176. switch($sOperation)
  177. {
  178. case 'parser_preview':
  179. $oPage = new ajax_page("");
  180. $oPage->no_cache();
  181. $sSeparator = utils::ReadParam('separator', ',');
  182. if ($sSeparator == 'tab') $sSeparator = "\t";
  183. $sTextQualifier = utils::ReadParam('qualifier', '"');
  184. $iLinesToSkip = utils::ReadParam('nb_lines_skipped', 0);
  185. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  186. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  187. $sData = stripslashes(utils::ReadParam('csvdata', true));
  188. $oCSVParser = new CSVParser($sData, $sSeparator, $sTextQualifier);
  189. $aData = $oCSVParser->ToArray($iLinesToSkip);
  190. $iTarget = count($aData);
  191. if ($iTarget == 0)
  192. {
  193. $oPage->p(Dict::S('UI:CSVImport:NoData'));
  194. }
  195. else
  196. {
  197. $sMaxLen = (strlen(''.$iTarget) < 3) ? 3 : strlen(''.$iTarget); // Pad line numbers to the appropriate number of chars, but at least 3
  198. $sFormat = '%0'.$sMaxLen.'d';
  199. $oPage->p("<h3>".Dict::S('UI:Title:DataPreview')."</h3>\n");
  200. $oPage->p("<div style=\"overflow-y:auto\" class=\"white\">\n");
  201. $oPage->add("<table cellspacing=\"0\" style=\"overflow-y:auto\">");
  202. $iMaxIndex= 10; // Display maximum 10 lines for the preview
  203. $index = 1;
  204. foreach($aData as $aRow)
  205. {
  206. $sCSSClass = 'csv_row'.($index % 2);
  207. if ( ($bFirstLineAsHeader) && ($index == 1))
  208. {
  209. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td><th>");
  210. $oPage->add(implode('</th><th>', $aRow));
  211. $oPage->add("</th></tr>\n");
  212. $iNbCols = count($aRow);
  213. }
  214. else
  215. {
  216. if ($index == 1) $iNbCols = count($aRow);
  217. $oPage->add("<tr class=\"$sCSSClass\"><td style=\"border-left:#999 3px solid;padding-right:10px;padding-left:10px;\">".sprintf($sFormat, $index)."</td><td>");
  218. $oPage->add(implode('</td><td>', $aRow));
  219. $oPage->add("</td></tr>\n");
  220. }
  221. $index++;
  222. if ($index > $iMaxIndex) break;
  223. }
  224. $oPage->add("</table>\n");
  225. $oPage->add("</div>\n");
  226. if($iNbCols == 1)
  227. {
  228. $oPage->p('<img src="../images/error.png">&nbsp;'.Dict::S('UI:CSVImport:ErrorOnlyOneColumn'));
  229. }
  230. else
  231. {
  232. $oPage->p('&nbsp;');
  233. }
  234. }
  235. break;
  236. case 'display_mapping_form':
  237. $oPage = new ajax_page("");
  238. $oPage->no_cache();
  239. $sSeparator = utils::ReadParam('separator', ',');
  240. $sTextQualifier = utils::ReadParam('qualifier', '"');
  241. $iLinesToSkip = utils::ReadParam('nb_lines_skipped', 0);
  242. $bFirstLineAsHeader = utils::ReadParam('header_line', true);
  243. $sData = stripslashes(utils::ReadParam('csvdata', true));
  244. $sClassName = utils::ReadParam('class_name', '');
  245. $bAdvanced = utils::ReadParam('advanced', false);
  246. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  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, $bAdvanced));
  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. ?>