csvimport.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. * CSV Import Page
  18. * Wizard to import CSV (or TSV) data into the database
  19. *
  20. * @author Erwan Taloc <erwan.taloc@combodo.com>
  21. * @author Romain Quetiez <romain.quetiez@combodo.com>
  22. * @author Denis Flaven <denis.flaven@combodo.com>
  23. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  24. */
  25. ini_set('memory_limit', '256M');
  26. require_once('../application/application.inc.php');
  27. require_once('../application/itopwebpage.class.inc.php');
  28. require_once('../application/startup.inc.php');
  29. require_once('../application/loginwebpage.class.inc.php');
  30. LoginWebPage::DoLogin(); // Check user rights and prompt if needed
  31. $oAppContext = new ApplicationContext();
  32. $currentOrganization = utils::ReadParam('org_id', 1);
  33. $iStep = utils::ReadParam('step', 1);
  34. $oPage = new iTopWebPage(Dict::S('UI:Title:BulkImport'), $currentOrganization);
  35. /**
  36. * Helper function to build a select from the list of valid classes for a given action
  37. * @param string $sName The name of the select in the HTML form
  38. * @param string $sDefaulfValue The defaut value (i.e the value selected by default)
  39. * @param integer $iWidthPx The width (in pixels) of the drop-down list
  40. * @param integer $iActionCode The ActionCode (from UserRights) to check for authorization for the classes
  41. * @return string The HTML fragment corresponding to the select tag
  42. */
  43. function GetClassesSelect($sName, $sDefaultValue, $iWidthPx, $iActionCode = null)
  44. {
  45. $sHtml = "<select id=\"select_$sName\" name=\"$sName\">";
  46. $sHtml .= "<option tyle=\"width: ".$iWidthPx."px;\" title=\"Select the class you want to load\" value=\"\">".Dict::S('UI:CSVImport:ClassesSelectOne')."</option>\n";
  47. $aValidClasses = array();
  48. $aClassCategories = array('bizmodel');
  49. if (UserRights::IsAdministrator())
  50. {
  51. $aClassCategories = array('bizmodel', 'application', 'addon/authentication');
  52. }
  53. foreach($aClassCategories as $sClassCategory)
  54. {
  55. foreach(MetaModel::GetClasses($sClassCategory) as $sClassName)
  56. {
  57. if ( (is_null($iActionCode) || UserRights::IsActionAllowed($sClassName, $iActionCode)) &&
  58. (!MetaModel::IsAbstract($sClassName)) )
  59. {
  60. $sSelected = ($sClassName == $sDefaultValue) ? " selected" : "";
  61. $sDescription = MetaModel::GetClassDescription($sClassName);
  62. $sDisplayName = MetaModel::GetName($sClassName);
  63. $aValidClasses[$sDisplayName] = "<option style=\"width: ".$iWidthPx."px;\" title=\"$sDescription\" value=\"$sClassName\"$sSelected>$sDisplayName</option>";
  64. }
  65. }
  66. }
  67. ksort($aValidClasses);
  68. $sHtml .= implode("\n", $aValidClasses);
  69. $sHtml .= "</select>";
  70. return $sHtml;
  71. }
  72. /**
  73. * Helper to 'check' an input in an HTML form if the current value equals the value given
  74. * @param mixed $sCurrentValue The current value to be chacked against the value of the input
  75. * @param mixed $sProposedValue The value of the input
  76. * @param bool $bInverseCondition Set to true to perform the reversed comparison
  77. * @return string Either ' checked' or an empty string
  78. */
  79. function IsChecked($sCurrentValue, $sProposedValue, $bInverseCondition = false)
  80. {
  81. $bCondition = ($sCurrentValue == $sProposedValue);
  82. return ($bCondition xor $bInverseCondition) ? ' checked' : '';
  83. }
  84. /**
  85. * Get the user friendly name for an 'extended' attribute code i.e 'name', becomes 'Name' and 'org_id->name' becomes 'Organization->Name'
  86. * @param string $sClassName The name of the class
  87. * @param string $sAttCodeEx Either an attribute code of ext_key_name->att_code
  88. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  89. */
  90. function GetFriendlyAttCodeName($sClassName, $sAttCodeEx)
  91. {
  92. $sFriendlyName = '';
  93. if (preg_match('/(.+)->(.+)/', $sAttCodeEx, $aMatches) > 0)
  94. {
  95. $sAttribute = $aMatches[1];
  96. $sField = $aMatches[2];
  97. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttribute);
  98. if ($oAttDef->IsExternalKey())
  99. {
  100. $sTargetClass = $oAttDef->GetTargetClass();
  101. $oTargetAttDef = MetaModel::GetAttributeDef($sTargetClass, $sField);
  102. $sFriendlyName = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  103. }
  104. else
  105. {
  106. // hum, hum... should never happen, we'd better raise an exception
  107. throw(new Exception(Dict::Format('UI:CSVImport:ErrorExtendedAttCode', $sAttCodeEx, $sAttribute, $sClassName)));
  108. }
  109. }
  110. else
  111. {
  112. if ($sAttCodeEx == 'id')
  113. {
  114. $sFriendlyName = Dict::S('UI:CSVImport:idField');
  115. }
  116. else
  117. {
  118. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCodeEx);
  119. $sFriendlyName = $oAttDef->GetLabel();
  120. }
  121. }
  122. return $sFriendlyName;
  123. }
  124. /**
  125. * Returns the number of occurences of each char from the set in the specified string
  126. * @param string $sString The input data
  127. * @param array $aSet The set of characters to count
  128. * @return hash 'char' => nb of occurences
  129. */
  130. function CountCharsFromSet($sString, $aSet)
  131. {
  132. $aResult = array();
  133. $aCount = count_chars($sString);
  134. foreach($aSet as $sChar)
  135. {
  136. $aResult[$sChar] = isset($aCount[ord($sChar)]) ? $aCount[ord($sChar)] : 0;
  137. }
  138. return $aResult;
  139. }
  140. /**
  141. * Return the most frequent (and regularly occuring) character among the given set, in the specified lines
  142. * @param array $aCSVData The input data, one entry per line
  143. * @param array $aPossibleSeparators The list of characters to count
  144. * @return string The most frequent character from the set
  145. */
  146. function GuessFromFrequency($aCSVData, $aPossibleSeparators)
  147. {
  148. $iLine = 0;
  149. $iMaxLine = 20; // Process max 20 lines to guess the parameters
  150. foreach($aPossibleSeparators as $sSep)
  151. {
  152. $aGuesses[$sSep]['total'] = $aGuesses[$sSep]['max'] = 0;
  153. $aGuesses[$sSep]['min'] = 999;
  154. }
  155. $aStats = array();
  156. while(($iLine < count($aCSVData)) && ($iLine < $iMaxLine) )
  157. {
  158. if (strlen($aCSVData[$iLine]) > 0)
  159. {
  160. $aStats[$iLine] = CountCharsFromSet($aCSVData[$iLine], $aPossibleSeparators);
  161. }
  162. $iLine++;
  163. }
  164. $iLine = 1;
  165. foreach($aStats as $aLineStats)
  166. {
  167. foreach($aPossibleSeparators as $sSep)
  168. {
  169. $aGuesses[$sSep]['total'] += $aLineStats[$sSep];
  170. if ($aLineStats[$sSep] > $aGuesses[$sSep]['max']) $aGuesses[$sSep]['max'] = $aLineStats[$sSep];
  171. if ($aLineStats[$sSep] < $aGuesses[$sSep]['min']) $aGuesses[$sSep]['min'] = $aLineStats[$sSep];
  172. }
  173. $iLine++;
  174. }
  175. $aScores = array();
  176. foreach($aGuesses as $sSep => $aData)
  177. {
  178. $aScores[$sSep] = $aData['total'] + $aData['max'] - $aData['min'];
  179. }
  180. arsort($aScores, SORT_NUMERIC); // Sort the array, higher scores first
  181. $aKeys = array_keys($aScores);
  182. $sSeparator = $aKeys[0]; // Take the first key, the one with the best score
  183. return $sSeparator;
  184. }
  185. /**
  186. * Try to predict the CSV parameters based on the input data
  187. * @param string $sCSVData The input data
  188. * @return hash 'separator' => the_guessed_separator, 'qualifier' => the_guessed_text_qualifier
  189. */
  190. function GuessParameters($sCSVData)
  191. {
  192. $aData = explode("\n", $sCSVData);
  193. $sSeparator = GuessFromFrequency($aData, array("\t", ',', ';', '|')); // Guess the most frequent (and regular) character on each line
  194. $sQualifier = GuessFromFrequency($aData, array('"', "'")); // Guess the most frequent (and regular) character on each line
  195. return array('separator' => $sSeparator, 'qualifier' => $sQualifier);
  196. }
  197. /**
  198. * Process the CSV data, for real or as a simulation
  199. * @param WebPage $oPage The page used to display the wizard
  200. * @param bool $bSimulate Whether or not to simulate the data load
  201. * @return array The CSV lines in error that were rejected from the load (with the header line - if any) or null
  202. */
  203. function ProcessCSVData(WebPage $oPage, $bSimulate = true)
  204. {
  205. $aResult = array();
  206. $sCSVData = utils::ReadParam('csvdata', '');
  207. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');
  208. $sSeparator = utils::ReadParam('separator', ',');
  209. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  210. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  211. $iRealSkippedLines = $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  212. $sClassName = utils::ReadParam('class_name', '');
  213. $aFieldsMapping = utils::ReadParam('field', array());
  214. $aSearchFields = utils::ReadParam('search_field', array());
  215. $iCurrentStep = $bSimulate ? 4 : 5;
  216. $bAdvanced = utils::ReadParam('advanced', 0);
  217. // Parse the data set
  218. $oCSVParser = new CSVParser($sCSVData, $sSeparator, $sTextQualifier);
  219. $aData = $oCSVParser->ToArray($iSkippedLines);
  220. if ($bHeaderLine)
  221. {
  222. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier, array_shift($aData)).$sTextQualifier; // Remove the first line and store it in case of error
  223. $iRealSkippedLines++;
  224. }
  225. // Format for the line numbers
  226. $sMaxLen = (strlen(''.count($aData)) < 3) ? 3 : strlen(''.count($aData)); // Pad line numbers to the appropriate number of chars, but at least 3
  227. // Compute the list of search/reconciliation criteria
  228. $aSearchKeys = array();
  229. foreach($aSearchFields as $index => $sDummy)
  230. {
  231. $sSearchField = $aFieldsMapping[$index];
  232. $aMatches = array();
  233. if (preg_match('/(.+)->(.+)/', $sSearchField, $aMatches) > 0)
  234. {
  235. $sSearchField = $aMatches[1];
  236. $aSearchKeys[$aMatches[1]] = '';
  237. }
  238. else
  239. {
  240. $aSearchKeys[$sSearchField] = '';
  241. }
  242. if (!MetaModel::IsValidFilterCode($sClassName, $sSearchField))
  243. {
  244. // Remove invalid or unmapped search fields
  245. $aSearchFields[$index] = null;
  246. unset($aSearchKeys[$sSearchField]);
  247. }
  248. }
  249. // Compute the list of fields and external keys to process
  250. $aExtKeys = array();
  251. $aAttributes = array();
  252. $aExternalKeysByColumn = array();
  253. foreach($aFieldsMapping as $iNumber => $sAttCode)
  254. {
  255. $iIndex = $iNumber-1;
  256. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  257. {
  258. if (preg_match('/(.+)->(.+)/', $sAttCode, $aMatches) > 0)
  259. {
  260. $sAttribute = $aMatches[1];
  261. $sField = $aMatches[2];
  262. $aExtKeys[$sAttribute][$sField] = $iIndex;
  263. $aExternalKeysByColumn[$iIndex] = $sAttribute;
  264. }
  265. else
  266. {
  267. if ($sAttCode == 'id')
  268. {
  269. $aAttributes['id'] = $iIndex;
  270. }
  271. else
  272. {
  273. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  274. if ($oAttDef->IsExternalKey())
  275. {
  276. $aExtKeys[$sAttCode]['id'] = $iIndex;
  277. $aExternalKeysByColumn[$iIndex] = $sAttCode;
  278. }
  279. else
  280. {
  281. $aAttributes[$sAttCode] = $iIndex;
  282. }
  283. }
  284. }
  285. }
  286. }
  287. $oMyChange = null;
  288. if (!$bSimulate)
  289. {
  290. // We're doing it for real, let's create a change
  291. $oMyChange = MetaModel::NewObject("CMDBChange");
  292. $oMyChange->Set("date", time());
  293. if (UserRights::GetUser() != UserRights::GetRealUser())
  294. {
  295. $sUserString = UserRights::GetRealUser()." on behalf of ".UserRights::GetUser();
  296. }
  297. else
  298. {
  299. $sUserString = UserRights::GetUser();
  300. }
  301. $oMyChange->Set("userinfo", $sUserString);
  302. $iChangeId = $oMyChange->DBInsert();
  303. }
  304. $oBulk = new BulkChange(
  305. $sClassName,
  306. $aData,
  307. $aAttributes,
  308. $aExtKeys,
  309. array_keys($aSearchKeys)
  310. );
  311. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  312. $aRes = $oBulk->Process($oMyChange);
  313. $sHtml = '<table id="bulk_preview">';
  314. $sHtml .= '<tr><th>Line</th>';
  315. $sHtml .= '<th>Status</th>';
  316. $sHtml .= '<th>Object</th>';
  317. foreach($aFieldsMapping as $iNumber => $sAttCode)
  318. {
  319. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  320. {
  321. $sHtml .= "<th>".GetFriendlyAttCodeName($sClassName, $sAttCode)."</th>";
  322. }
  323. }
  324. $sHtml .= '<th>Message</th>';
  325. $sHtml .= '</tr>';
  326. $iLine = 0;
  327. $iErrors = 0;
  328. $iCreated = 0;
  329. $iModified = 0;
  330. $iUnchanged = 0;
  331. foreach($aData as $aRow)
  332. {
  333. $oStatus = $aRes[$iLine]['__STATUS__'];
  334. $sUrl = '';
  335. $sMessage = '';
  336. $sCSSRowClass = '';
  337. $sCSSMessageClass = 'cell_ok';
  338. switch(get_class($oStatus))
  339. {
  340. case 'RowStatus_NoChange':
  341. $iUnchanged++;
  342. $sFinalClass = $aRes[$iLine]['finalclass'];
  343. $oObj = MetaModel::GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  344. $sUrl = $oObj->GetHyperlink();
  345. $sStatus = '<img src="../images/unchanged.png" title="Unchanged">';
  346. $sCSSRowClass = 'row_unchanged';
  347. break;
  348. case 'RowStatus_Modify':
  349. $iModified++;
  350. $sFinalClass = $aRes[$iLine]['finalclass'];
  351. $oObj = MetaModel::GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  352. $sUrl = $oObj->GetHyperlink();
  353. $sStatus = '<img src="../images/modified.png" title="Modified">';
  354. $sCSSRowClass = 'row_modified';
  355. break;
  356. case 'RowStatus_NewObj':
  357. $iCreated++;
  358. $sFinalClass = $aRes[$iLine]['finalclass'];
  359. $sStatus = '<img src="../images/added.png" title="Created">';
  360. $sCSSRowClass = 'row_added';
  361. if ($bSimulate)
  362. {
  363. $sMessage = 'Object will be created';
  364. }
  365. else
  366. {
  367. $sFinalClass = $aRes[$iLine]['finalclass'];
  368. $oObj = MetaModel::GetObject($sFinalClass, $aRes[$iLine]['id']->GetValue());
  369. $sUrl = $oObj->GetHyperlink();
  370. $sMessage = 'Object created';
  371. }
  372. break;
  373. case 'RowStatus_Issue':
  374. $iErrors++;
  375. $sMessage .= $oPage->GetP($oStatus->GetDescription());
  376. $sStatus = '<img src="../images/error.png" title="Error">';
  377. $sCSSMessageClass = 'cell_error';
  378. $sCSSRowClass = 'row_error';
  379. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier,$aRow).$sTextQualifier; // Remove the first line and store it in case of error
  380. break;
  381. }
  382. $sHtml .= '<tr class="'.$sCSSRowClass.'">';
  383. $sHtml .= "<td>".sprintf("%0{$sMaxLen}d", 1+$iLine+$iRealSkippedLines)."</td>";
  384. $sHtml .= "<td>$sStatus</td>";
  385. $sHtml .= "<td>$sUrl</td>";
  386. foreach($aFieldsMapping as $iNumber => $sAttCode)
  387. {
  388. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  389. {
  390. $oCellStatus = $aRes[$iLine][$iNumber -1];
  391. $sCellMessage = '';
  392. if (isset($aExternalKeysByColumn[$iNumber -1]))
  393. {
  394. $sExtKeyName = $aExternalKeysByColumn[$iNumber -1];
  395. $oExtKeyCellStatus = $aRes[$iLine][$sExtKeyName];
  396. switch(get_class($oExtKeyCellStatus))
  397. {
  398. case 'CellStatus_Issue':
  399. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  400. break;
  401. case 'CellStatus_Ambiguous':
  402. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  403. break;
  404. default:
  405. // Do nothing
  406. }
  407. }
  408. switch(get_class($oCellStatus))
  409. {
  410. case 'CellStatus_Issue':
  411. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  412. $sHtml .= '<td class="cell_error">ERROR: '.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').$sCellMessage.'</td>';
  413. break;
  414. case 'CellStatus_Ambiguous':
  415. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  416. $sHtml .= '<td class="cell_error">AMBIGUOUS: '.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').$sCellMessage.'</td>';
  417. break;
  418. case 'CellStatus_Modify':
  419. $sHtml .= '<td class="cell_modified"><b>'.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').'</b></td>';
  420. break;
  421. default:
  422. $sHtml .= '<td class="cell_ok">'.htmlentities($aData[$iLine][$iNumber-1], ENT_QUOTES, 'UTF-8').$sCellMessage.'</td>';
  423. }
  424. }
  425. }
  426. $sHtml .= "<td class=\"$sCSSMessageClass\">$sMessage</td>";
  427. $iLine++;
  428. $sHtml .= '</tr>';
  429. }
  430. $sHtml .= '</table>';
  431. $oPage->add('<div class="wizContainer">');
  432. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" onSubmit="return CheckValues()">');
  433. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  434. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  435. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  436. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  437. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  438. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  439. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  440. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  441. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  442. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  443. foreach($aFieldsMapping as $iNumber => $sAttCode)
  444. {
  445. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  446. }
  447. foreach($aSearchFields as $index => $sDummy)
  448. {
  449. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  450. }
  451. $aFieldsMapping = utils::ReadParam('field', array());
  452. $aSearchFields = utils::ReadParam('search_field', array());
  453. $aDisplayFilters = array();
  454. if ($bSimulate)
  455. {
  456. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsWillStayUnchanged');
  457. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWillBeModified');
  458. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWillBeAdded');
  459. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsWillHaveErrors');
  460. }
  461. else
  462. {
  463. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsRemainedUnchanged');
  464. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWereModified');
  465. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWereAdded');
  466. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsHadErrors');
  467. }
  468. $oPage->add('<p><input type="checkbox" checked id="show_unchanged" onClick="ToggleRows(\'row_unchanged\')"/>&nbsp;<img src="../images/unchanged.png">&nbsp;'.sprintf($aDisplayFilters['unchanged'], $iUnchanged).'&nbsp&nbsp;');
  469. $oPage->add('<input type="checkbox" checked id="show_modified" onClick="ToggleRows(\'row_modified\')"/>&nbsp;<img src="../images/modified.png">&nbsp;'.sprintf($aDisplayFilters['modified'], $iModified).'&nbsp&nbsp;');
  470. $oPage->add('<input type="checkbox" checked id="show_created" onClick="ToggleRows(\'row_added\')"/>&nbsp;<img src="../images/added.png">&nbsp;'.sprintf($aDisplayFilters['added'], $iCreated).'&nbsp&nbsp;');
  471. $oPage->add('<input type="checkbox" checked id="show_errors" onClick="ToggleRows(\'row_error\')"/>&nbsp;<img src="../images/error.png">&nbsp;'.sprintf($aDisplayFilters['errors'], $iErrors).'</p>');
  472. $oPage->add('<div style="overflow-y:auto" class="white">');
  473. $oPage->add($sHtml);
  474. $oPage->add('</div> <!-- end of preview -->');
  475. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  476. if ($bSimulate)
  477. {
  478. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:DoImport').'"/></p>');
  479. }
  480. else
  481. {
  482. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Done').'"/></p>');
  483. }
  484. $oPage->add('</form>');
  485. $oPage->add('</div> <!-- end of wizForm -->');
  486. $oPage->add_script(
  487. <<< EOF
  488. function CSVGoBack()
  489. {
  490. $('input[name=step]').val($iCurrentStep-1);
  491. $('#wizForm').submit();
  492. }
  493. function ToggleRows(sCSSClass)
  494. {
  495. $('.'+sCSSClass).toggle();
  496. }
  497. EOF
  498. );
  499. if ($iErrors > 0)
  500. {
  501. return $aResult;
  502. }
  503. else
  504. {
  505. return null;
  506. }
  507. }
  508. /**
  509. * Perform the actual load of the CSV data and display the results
  510. * @param WebPage $oPage The web page to display the wizard
  511. * @return void
  512. */
  513. function LoadData(WebPage $oPage)
  514. {
  515. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep5').'</h2>');
  516. $aResult = ProcessCSVData($oPage, false /* simulate = false */);
  517. if (is_array($aResult))
  518. {
  519. $oPage->StartCollapsibleSection(Dict::S('UI:CSVImport:LinesNotImported'), false);
  520. $oPage->p(Dict::S('UI:CSVImport:LinesNotImported+'));
  521. $oPage->add('<textarea rows="30" cols="100">');
  522. $oPage->add(htmlentities(implode("\n", $aResult), ENT_QUOTES, 'UTF-8'));
  523. $oPage->add('</textarea>');
  524. $oPage->EndCollapsibleSection();
  525. }
  526. }
  527. /**
  528. * Simulate the load of the CSV data and display the results
  529. * @param WebPage $oPage The web page to display the wizard
  530. * @return void
  531. */
  532. function Preview(WebPage $oPage)
  533. {
  534. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep4').'</h2>');
  535. ProcessCSVData($oPage, true /* simulate */);
  536. }
  537. /**
  538. * Select the mapping between the CSV column and the fields of the objects
  539. * @param WebPage $oPage The web page to display the wizard
  540. * @return void
  541. */
  542. function SelectMapping(WebPage $oPage)
  543. {
  544. $sCSVData = utils::ReadParam('csvdata', '');
  545. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');;
  546. $sSeparator = utils::ReadParam('separator', ',');
  547. if ($sSeparator == 'tab') $sSeparator = "\t";
  548. if ($sSeparator == 'other')
  549. {
  550. $sSeparator = utils::ReadParam('other_separator', ',');
  551. }
  552. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  553. if ($sTextQualifier == 'other')
  554. {
  555. $sTextQualifier = utils::ReadParam('other_qualifier', '"');
  556. }
  557. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  558. $iSkippedLines = 0;
  559. if (utils::ReadParam('box_skiplines', '0') == 1)
  560. {
  561. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  562. }
  563. $sClassName = utils::ReadParam('class_name', '');
  564. $bAdvanced = utils::ReadParam('advanced', 0);
  565. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep3').'</h2>');
  566. $oPage->add('<div class="wizContainer">');
  567. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" onSubmit="return CheckValues()"><table style="width:100%" class="transparent"><tr><td>'.Dict::S('UI:CSVImport:SelectClass').' ');
  568. $oPage->add(GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY));
  569. $oPage->add('</td><td style="text-align:right"><input type="checkbox" name="advanced" value="1" '.IsChecked($bAdvanced, 1).' onChange="DoMapping()">&nbsp;'.Dict::S('UI:CSVImport:AdvancedMode').'</td></tr></table>');
  570. $oPage->add('<div style="padding:1em;display:none" id="advanced_help" style="display:none">'.Dict::S('UI:CSVImport:AdvancedMode+').'</div>');
  571. $oPage->add('<div id="mapping" class="white"><p style="text-align:center;width:100%;font-size:1.5em;padding:1em;">'.Dict::S('UI:CSVImport:SelectAClassFirst').'<br/></p></div>');
  572. $oPage->add('<input type="hidden" name="step" value="4"/>');
  573. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  574. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  575. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  576. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  577. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  578. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  579. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  580. $oPage->add('<input type="hidden" name="_charset_"/>');
  581. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  582. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:SimulateImport').'"/></p>');
  583. $oPage->add('</form>');
  584. $oPage->add('</div>');
  585. $sAlertIncompleteMapping = Dict::S('UI:CSVImport:AlertIncompleteMapping');
  586. $sAlertNoSearchCriteria = Dict::S('UI:CSVImport:AlertNoSearchCriteria');
  587. $oPage->add_ready_script(
  588. <<<EOF
  589. $('#select_class_name').change( DoMapping );
  590. EOF
  591. );
  592. if ($sClassName != '')
  593. {
  594. $oPage->add_ready_script("DoMapping();"); // There is already a class selected, run the mapping
  595. }
  596. $oPage->add_script(
  597. <<<EOF
  598. var aDefaultKeys = new Array();
  599. function CSVGoBack()
  600. {
  601. $('input[name=step]').val(2);
  602. $('#wizForm').submit();
  603. }
  604. var ajax_request = null;
  605. function DoMapping()
  606. {
  607. var class_name = $('select[name=class_name]').val();
  608. var advanced = $('input[name=advanced]:checked').val();
  609. if (advanced != 1)
  610. {
  611. $('#advanced_help').hide();
  612. }
  613. else
  614. {
  615. $('#advanced_help').show();
  616. }
  617. if (class_name != '')
  618. {
  619. var separator = $('input[name=separator]').val();
  620. var text_qualifier = $('input[name=text_qualifier]').val();
  621. var header_line = $('input[name=header_line]').val();
  622. var nb_lines_skipped = $('input[name=nb_skipped_lines]').val();
  623. var csv_data = $('input[name=csvdata]').val();
  624. if (advanced != 1)
  625. {
  626. advanced = 0;
  627. }
  628. $('#mapping').block();
  629. // Make sure that we cancel any pending request before issuing another
  630. // since responses may arrive in arbitrary order
  631. if (ajax_request != null)
  632. {
  633. ajax_request.abort();
  634. ajax_request = null;
  635. }
  636. ajax_request = $.post('ajax.csvimport.php',
  637. { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator,
  638. qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, class_name: class_name,
  639. advanced: advanced },
  640. function(data) {
  641. $('#mapping').empty();
  642. $('#mapping').append(data);
  643. $('#mapping').unblock();
  644. }
  645. );
  646. }
  647. }
  648. function CheckValues()
  649. {
  650. bResult = true;
  651. bMappingOk = true;
  652. bSearchOk = false;
  653. $('select[name^=field]').each( function() {
  654. if ($(this).val() == '')
  655. {
  656. $(this).parent().css({'border': '2px #D81515 solid'});
  657. bMappingOk = false;
  658. bResult = false;
  659. }
  660. else
  661. {
  662. $(this).parent().css({'border': '0'});
  663. }
  664. });
  665. // At least one search field must be checked
  666. $('input[name^=search]:checked').each( function() {
  667. bSearchOk = true;
  668. });
  669. if (!bMappingOk)
  670. {
  671. alert("$sAlertIncompleteMapping");
  672. }
  673. if (!bSearchOk)
  674. {
  675. bResult = false;
  676. alert("$sAlertNoSearchCriteria");
  677. }
  678. if (bResult)
  679. {
  680. $('#mapping').block();
  681. // Re-enable all search_xxx checkboxes so that their value gets posted
  682. $('input[name^=search]').each(function() {
  683. $(this).attr('disabled', false);
  684. });
  685. }
  686. return bResult;
  687. }
  688. function DoCheckMapping()
  689. {
  690. // Check if there is a field mapped to 'id'
  691. // In which case, it's the only possible search key
  692. var idSelected = 0;
  693. var nbSearchKeys = $('input[name^=search]:checked').length;
  694. var nbMappings = $('select[name^=field]').length;
  695. for(index=1; index <= nbMappings; index++)
  696. {
  697. var selectedValue = $('#mapping_'+index).val();
  698. if (selectedValue == 'id')
  699. {
  700. idSelected = index;
  701. }
  702. }
  703. for (index=1; index <= nbMappings; index++)
  704. {
  705. sMappingValue = $('#mapping_'+index).val();
  706. if ((sMappingValue == '') || (sMappingValue == ':none:'))
  707. {
  708. // Non-mapped field, uncheck and disabled
  709. $('#search_'+index).attr('checked', false);
  710. $('#search_'+index).attr('disabled', true);
  711. }
  712. else if (index == idSelected)
  713. {
  714. // The 'id' field was mapped, it's the only possible reconciliation key
  715. $('#search_'+index).attr('checked', true);
  716. $('#search_'+index).attr('disabled', true);
  717. }
  718. else
  719. {
  720. if (idSelected > 0)
  721. {
  722. // The 'id' field was mapped, it's the only possible reconciliation key
  723. $('#search_'+index).attr('checked', false);
  724. $('#search_'+index).attr('disabled', true);
  725. }
  726. else
  727. {
  728. $('#search_'+index).attr('disabled', false);
  729. if (nbSearchKeys == 0)
  730. {
  731. // No search key was selected, select the default ones
  732. for(j =0; j < aDefaultKeys.length; j++)
  733. {
  734. if (sMappingValue == aDefaultKeys[j])
  735. {
  736. $('#search_'+index).attr('checked', true);
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. }
  744. EOF
  745. );
  746. }
  747. /**
  748. * Select the options of the CSV load and check for CSV parsing errors
  749. * @param WebPage $oPage The current web page
  750. * @return void
  751. */
  752. function SelectOptions(WebPage $oPage)
  753. {
  754. $sOperation = utils::ReadParam('operation', 'csv_data', 'post');
  755. $sCSVData = '';
  756. switch($sOperation)
  757. {
  758. case 'file_upload':
  759. $oDocument = utils::ReadPostedDocument('csvdata');
  760. if (!$oDocument->IsEmpty())
  761. {
  762. $sCSVData = $oDocument->GetData();
  763. }
  764. break;
  765. default:
  766. $sCSVData = utils::ReadParam('csvdata', '', 'post');
  767. }
  768. $aGuesses = GuessParameters($sCSVData); // Try to predict the parameters, based on the input data
  769. $sSeparator = utils::ReadParam('separator', '');
  770. if ($sSeparator == '') // May be set to an empty value by the previous page
  771. {
  772. $sSeparator = $aGuesses['separator'];
  773. }
  774. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  775. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  776. if ($sSeparator == 'tab') $sSeparator = "\t";
  777. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  778. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  779. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  780. {
  781. $sTextQualifier = $aGuesses['qualifier'];
  782. }
  783. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  784. $bHeaderLine = utils::ReadParam('header_line', 0);
  785. $sClassName = utils::ReadParam('class_name', '');
  786. $bAdvanced = utils::ReadParam('advanced', 0);
  787. // Create a truncated version of the data used for the fast preview
  788. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  789. $iMaxLines = 20;
  790. $iMaxLen = strlen($sCSVData);
  791. $iCurPos = true;
  792. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  793. {
  794. $pos = strpos($sCSVData, "\n", $iCurPos);
  795. if ($pos !== false)
  796. {
  797. $iCurPos = 1+$pos;
  798. }
  799. else
  800. {
  801. $iCurPos = strlen($sCSVData);
  802. $iMaxLines = 1;
  803. }
  804. $iMaxLines--;
  805. }
  806. $sCSVDataTruncated = substr($sCSVData, 0, $iCurPos);
  807. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep2').'</h2>');
  808. $oPage->add('<div class="wizContainer">');
  809. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;">');
  810. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  811. $oPage->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  812. $oPage->add('<p><input type="radio" name="separator" value="," onChange="DoPreview()"'.IsChecked($sSeparator, ',').'/> '.Dict::S('UI:CSVImport:SeparatorComma+').'<br/>');
  813. $oPage->add('<input type="radio" name="separator" value=";" onChange="DoPreview()"'.IsChecked($sSeparator, ';').'/> '.Dict::S('UI:CSVImport:SeparatorSemicolon+').'<br/>');
  814. $oPage->add('<input type="radio" name="separator" value="tab" onChange="DoPreview()"'.IsChecked($sSeparator, "\t").'/> '.Dict::S('UI:CSVImport:SeparatorTab+').'<br/>');
  815. $oPage->add('<input type="radio" name="separator" value="other" onChange="DoPreview()"'.IsChecked($sOtherSeparator, '', true).'/> '.Dict::S('UI:CSVImport:SeparatorOther').' <input type="text" size="3" maxlength="1" name="other_separator" id="other_separator" value="'.$sOtherSeparator.'" onChange="DoPreview()"/>');
  816. $oPage->add('</p>');
  817. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;">');
  818. $oPage->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  819. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onChange="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> '.Dict::S('UI:CSVImport:QualifierDoubleQuote+').'<br/>');
  820. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onChange="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> '.Dict::S('UI:CSVImport:QualifierSimpleQuote+').'<br/>');
  821. $oPage->add('<input type="radio" name="text_qualifier" value="other" onChange="DoPreview()"'.IsChecked($sOtherTextQualifier, '', true).'/> '.Dict::S('UI:CSVImport:QualifierOther').' <input type="text" size="3" maxlength="1" name="other_qualifier" value="'.htmlentities($sOtherTextQualifier, ENT_QUOTES, 'UTF-8').'" onChange="DoPreview()"/>');
  822. $oPage->add('</p>');
  823. $oPage->add('</td><td style="vertical-align:top;">');
  824. $oPage->add('<h3>'.Dict::S('UI:CSVImport:CommentsAndHeader').'</h3>');
  825. $oPage->add('<p><input type="checkbox" name="header_line" id="box_header" value="1" onChange="DoPreview()"'.IsChecked($bHeaderLine, 1).'/> '.Dict::S('UI:CSVImport:TreatFirstLineAsHeader').'<p>');
  826. $oPage->add('<p><input type="checkbox" name="box_skiplines" value="1" id="box_skiplines" onChange="DoPreview()"'.IsChecked($bBoxSkipLines, 1).'/> '.Dict::Format('UI:CSVImport:Skip_N_LinesAtTheBeginning', '<input type="text" size=2 name="nb_skipped_lines" id="nb_skipped_lines" onChange="DoPreview()" value="'.$iSkippedLines.'">').'<p>');
  827. $oPage->add('</td></tr></table>');
  828. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  829. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  830. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  831. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  832. $oPage->add('<input type="hidden" name="step" value="3"/>');
  833. $oPage->add('<div id="preview">');
  834. $oPage->add('<p style="text-align:center">'.Dict::S('UI:CSVImport:CSVDataPreview').'</p>');
  835. $oPage->add('</div>');
  836. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="GoBack()"/>');
  837. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Next').'"/>');
  838. $oPage->add('</form>');
  839. $oPage->add('</div>');
  840. $oPage->add_script(
  841. <<<EOF
  842. function GoBack()
  843. {
  844. $('input[name=step]').val(1);
  845. $('#wizForm').submit();
  846. }
  847. var ajax_request = null;
  848. function DoPreview()
  849. {
  850. var separator = $('input[name=separator]:checked').val();
  851. if (separator == 'other')
  852. {
  853. separator = $('#other_separator').val();
  854. }
  855. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  856. if (text_qualifier == 'other')
  857. {
  858. text_qualifier = $('#other_qualifier').val();
  859. }
  860. var nb_lines_skipped = 0;
  861. if ($('#box_skiplines:checked').val() != null)
  862. {
  863. nb_lines_skipped = $('#nb_skipped_lines').val();
  864. }
  865. var header_line = 0;
  866. if ($('#box_header:checked').val() != null)
  867. {
  868. header_line = 1;
  869. }
  870. $('#preview').block();
  871. // Make sure that we cancel any pending request before issuing another
  872. // since responses may arrive in arbitrary order
  873. if (ajax_request != null)
  874. {
  875. ajax_request.abort();
  876. ajax_request = null;
  877. }
  878. ajax_request = $.post('ajax.csvimport.php',
  879. { operation: 'parser_preview', enctype: 'multipart/form-data', csvdata: $("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line },
  880. function(data) {
  881. $('#preview').empty();
  882. $('#preview').append(data);
  883. $('#preview').unblock();
  884. }
  885. );
  886. }
  887. EOF
  888. );
  889. $oPage->add_ready_script('DoPreview();');
  890. }
  891. /**
  892. * Prompt for the data to be loaded (either via a file or a copy/paste)
  893. * @param WebPage $oPage The current web page
  894. * @return void
  895. */
  896. function Welcome(iTopWebPage $oPage)
  897. {
  898. $oPage->add("<div><p><h1>".Dict::S('UI:Title:BulkImport+')."</h1></p></div>\n");
  899. $oPage->AddTabContainer('tabs1');
  900. $sSeparator = utils::ReadParam('separator', '');
  901. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  902. $bHeaderLine = utils::ReadParam('header_line', true);
  903. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  904. $sClassName = utils::ReadParam('class_name', '');
  905. $bAdvanced = utils::ReadParam('advanced', 0);
  906. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:SelectFile').'</p>'.
  907. '<p><input type="file" name="csvdata"/></p>'.
  908. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  909. '<p><input type="hidden" name="step" value="2"/></p>'.
  910. '<p><input type="hidden" name="operation" value="file_upload"/></p>'.
  911. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  912. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  913. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  914. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  915. '</form></div>';
  916. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:LoadFromFile'), $sFileLoadHtml);
  917. $sCSVData = utils::ReadParam('csvdata', '');
  918. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:PasteData').'</p>'.
  919. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>'.
  920. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  921. '<input type="hidden" name="step" value="2"/>'.
  922. '<input type="hidden" name="operation" value="csv_data"/>'.
  923. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  924. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  925. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  926. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  927. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  928. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  929. '</form></div>';
  930. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'), $sPasteDataHtml);
  931. if (!empty($sCSVData))
  932. {
  933. // When there are some data, activate the 'copy & paste' tab by default
  934. $oPage->SelectTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'));
  935. }
  936. $sTemplateHtml = '<div><p>'.Dict::S('UI:CSVImport:PickClassForTemplate').' ';
  937. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  938. $sTemplateHtml .= '</div>';
  939. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  940. $sTemplateHtml .= '</div>';
  941. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:Templates'), $sTemplateHtml);
  942. $oPage->add_script(
  943. <<<EOF
  944. var ajax_request = null;
  945. function DisplayTemplate(sClassName) {
  946. $('#template').block();
  947. // Make sure that we cancel any pending request before issuing another
  948. // since responses may arrive in arbitrary order
  949. if (ajax_request != null)
  950. {
  951. ajax_request.abort();
  952. ajax_request = null;
  953. }
  954. ajax_request = $.post('ajax.csvimport.php',
  955. { operation: 'get_csv_template', class_name: sClassName },
  956. function(data) {
  957. $('#template').empty();
  958. $('#template').append(data);
  959. $('#template').unblock();
  960. }
  961. );
  962. }
  963. EOF
  964. );
  965. $oPage->add_ready_script(
  966. <<<EOF
  967. $('#select_template_class').change( function() {
  968. DisplayTemplate(this.value);
  969. });
  970. EOF
  971. );
  972. }
  973. switch($iStep)
  974. {
  975. case 5:
  976. LoadData($oPage);
  977. break;
  978. case 4:
  979. Preview($oPage);
  980. break;
  981. case 3:
  982. SelectMapping($oPage);
  983. break;
  984. case 2:
  985. SelectOptions($oPage);
  986. break;
  987. case 1:
  988. case 6: // Loop back here when we are done
  989. default:
  990. Welcome($oPage);
  991. }
  992. $oPage->output();
  993. ?>