csvimport.php 38 KB

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