csvimport.php 37 KB

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