csvimport.php 38 KB

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