csvimport.php 44 KB

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