csvimport.php 44 KB

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