csvimport.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * CSV Import Page
  20. * Wizard to import CSV (or TSV) data into the database
  21. *
  22. * @copyright Copyright (C) 2010-2012 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  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. $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. * Returns the number of occurences of each char from the set in the specified string
  87. * @param string $sString The input data
  88. * @param array $aSet The set of characters to count
  89. * @return hash 'char' => nb of occurences
  90. */
  91. function CountCharsFromSet($sString, $aSet)
  92. {
  93. $aResult = array();
  94. $aCount = count_chars($sString);
  95. foreach($aSet as $sChar)
  96. {
  97. $aResult[$sChar] = isset($aCount[ord($sChar)]) ? $aCount[ord($sChar)] : 0;
  98. }
  99. return $aResult;
  100. }
  101. /**
  102. * Return the most frequent (and regularly occuring) character among the given set, in the specified lines
  103. * @param array $aCSVData The input data, one entry per line
  104. * @param array $aPossibleSeparators The list of characters to count
  105. * @return string The most frequent character from the set
  106. */
  107. function GuessFromFrequency($aCSVData, $aPossibleSeparators)
  108. {
  109. $iLine = 0;
  110. $iMaxLine = 20; // Process max 20 lines to guess the parameters
  111. foreach($aPossibleSeparators as $sSep)
  112. {
  113. $aGuesses[$sSep]['total'] = $aGuesses[$sSep]['max'] = 0;
  114. $aGuesses[$sSep]['min'] = 999;
  115. }
  116. $aStats = array();
  117. while(($iLine < count($aCSVData)) && ($iLine < $iMaxLine) )
  118. {
  119. if (strlen($aCSVData[$iLine]) > 0)
  120. {
  121. $aStats[$iLine] = CountCharsFromSet($aCSVData[$iLine], $aPossibleSeparators);
  122. }
  123. $iLine++;
  124. }
  125. $iLine = 1;
  126. foreach($aStats as $aLineStats)
  127. {
  128. foreach($aPossibleSeparators as $sSep)
  129. {
  130. $aGuesses[$sSep]['total'] += $aLineStats[$sSep];
  131. if ($aLineStats[$sSep] > $aGuesses[$sSep]['max']) $aGuesses[$sSep]['max'] = $aLineStats[$sSep];
  132. if ($aLineStats[$sSep] < $aGuesses[$sSep]['min']) $aGuesses[$sSep]['min'] = $aLineStats[$sSep];
  133. }
  134. $iLine++;
  135. }
  136. $aScores = array();
  137. foreach($aGuesses as $sSep => $aData)
  138. {
  139. $aScores[$sSep] = $aData['total'] + $aData['max'] - $aData['min'];
  140. }
  141. arsort($aScores, SORT_NUMERIC); // Sort the array, higher scores first
  142. $aKeys = array_keys($aScores);
  143. $sSeparator = $aKeys[0]; // Take the first key, the one with the best score
  144. return $sSeparator;
  145. }
  146. /**
  147. * Try to predict the CSV parameters based on the input data
  148. * @param string $sCSVData The input data
  149. * @return hash 'separator' => the_guessed_separator, 'qualifier' => the_guessed_text_qualifier
  150. */
  151. function GuessParameters($sCSVData)
  152. {
  153. $aData = explode("\n", $sCSVData);
  154. $sSeparator = GuessFromFrequency($aData, array("\t", ',', ';', '|')); // Guess the most frequent (and regular) character on each line
  155. $sQualifier = GuessFromFrequency($aData, array('"', "'")); // Guess the most frequent (and regular) character on each line
  156. return array('separator' => $sSeparator, 'qualifier' => $sQualifier);
  157. }
  158. /**
  159. * Display a banner for the special "synchro" mode
  160. * @param WebPage $oP The Page for the output
  161. * @param string $sClass The class of objects to synchronize
  162. * @param integer $iCount The number of objects to synchronize
  163. * @return none
  164. */
  165. function DisplaySynchroBanner(WebPage $oP, $sClass, $iCount)
  166. {
  167. $oP->add("<div class=\"notification\"><p><h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Title:BulkSynchro_nbItem_ofClass_class', $iCount, MetaModel::GetName($sClass))."</h1></p></div>\n");
  168. }
  169. /**
  170. * Process the CSV data, for real or as a simulation
  171. * @param WebPage $oPage The page used to display the wizard
  172. * @param bool $bSimulate Whether or not to simulate the data load
  173. * @return array The CSV lines in error that were rejected from the load (with the header line - if any) or null
  174. */
  175. function ProcessCSVData(WebPage $oPage, $bSimulate = true)
  176. {
  177. $aResult = array();
  178. $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data');
  179. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '', false, 'raw_data');
  180. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  181. $sTextQualifier = utils::ReadParam('text_qualifier', '"', false, 'raw_data');
  182. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  183. $iSkippedLines = 0;
  184. if (utils::ReadParam('box_skiplines', '0') == 1)
  185. {
  186. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  187. }
  188. $sClassName = utils::ReadParam('class_name', '', false, 'class');
  189. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  190. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  191. $iCurrentStep = $bSimulate ? 4 : 5;
  192. $bAdvanced = utils::ReadParam('advanced', 0);
  193. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  194. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  195. if (!empty($sSynchroScope))
  196. {
  197. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  198. $sClassName = $oSearch->GetClass(); // If a synchronization scope is set, then the class is fixed !
  199. $oSet = new DBObjectSet($oSearch);
  200. $iCount = $oSet->Count();
  201. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  202. $sClassesSelect = "<select id=\"select_class_name\" name=\"class_name\"><option value=\"$sClassName\" selected>".MetaModel::GetName($sClassName)."</option>";
  203. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  204. }
  205. else
  206. {
  207. $sSynchroScope = '';
  208. $aSynchroUpdate = null;
  209. }
  210. // Parse the data set
  211. $oCSVParser = new CSVParser($sCSVData, $sSeparator, $sTextQualifier);
  212. $aData = $oCSVParser->ToArray($iSkippedLines);
  213. $iRealSkippedLines = $iSkippedLines;
  214. if ($bHeaderLine)
  215. {
  216. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier, array_shift($aData)).$sTextQualifier; // Remove the first line and store it in case of error
  217. $iRealSkippedLines++;
  218. }
  219. // Format for the line numbers
  220. $sMaxLen = (strlen(''.count($aData)) < 3) ? 3 : strlen(''.count($aData)); // Pad line numbers to the appropriate number of chars, but at least 3
  221. // Compute the list of search/reconciliation criteria
  222. $aSearchKeys = array();
  223. foreach($aSearchFields as $index => $sDummy)
  224. {
  225. $sSearchField = $aFieldsMapping[$index];
  226. $aMatches = array();
  227. if (preg_match('/(.+)->(.+)/', $sSearchField, $aMatches) > 0)
  228. {
  229. $sSearchField = $aMatches[1];
  230. $aSearchKeys[$aMatches[1]] = '';
  231. }
  232. else
  233. {
  234. $aSearchKeys[$sSearchField] = '';
  235. }
  236. if (!MetaModel::IsValidFilterCode($sClassName, $sSearchField))
  237. {
  238. // Remove invalid or unmapped search fields
  239. $aSearchFields[$index] = null;
  240. unset($aSearchKeys[$sSearchField]);
  241. }
  242. }
  243. // Compute the list of fields and external keys to process
  244. $aExtKeys = array();
  245. $aAttributes = array();
  246. $aExternalKeysByColumn = array();
  247. foreach($aFieldsMapping as $iNumber => $sAttCode)
  248. {
  249. $iIndex = $iNumber-1;
  250. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  251. {
  252. if (preg_match('/(.+)->(.+)/', $sAttCode, $aMatches) > 0)
  253. {
  254. $sAttribute = $aMatches[1];
  255. $sField = $aMatches[2];
  256. $aExtKeys[$sAttribute][$sField] = $iIndex;
  257. $aExternalKeysByColumn[$iIndex] = $sAttribute;
  258. }
  259. else
  260. {
  261. if ($sAttCode == 'id')
  262. {
  263. $aAttributes['id'] = $iIndex;
  264. }
  265. else
  266. {
  267. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  268. if ($oAttDef->IsExternalKey())
  269. {
  270. $aExtKeys[$sAttCode]['id'] = $iIndex;
  271. $aExternalKeysByColumn[$iIndex] = $sAttCode;
  272. }
  273. else
  274. {
  275. $aAttributes[$sAttCode] = $iIndex;
  276. }
  277. }
  278. }
  279. }
  280. }
  281. $oMyChange = null;
  282. if (!$bSimulate)
  283. {
  284. // We're doing it for real, let's create a change
  285. $sUserString = CMDBChange::GetCurrentUserName().' (CSV)';
  286. CMDBObject::SetTrackInfo($sUserString);
  287. $oMyChange = CMDBObject::GetCurrentChange();
  288. }
  289. $oBulk = new BulkChange(
  290. $sClassName,
  291. $aData,
  292. $aAttributes,
  293. $aExtKeys,
  294. array_keys($aSearchKeys),
  295. empty($sSynchroScope) ? null : $sSynchroScope,
  296. $aSynchroUpdate,
  297. null, // date format
  298. true // localize
  299. );
  300. $oBulk->SetReportHtml();
  301. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  302. $aRes = $oBulk->Process($oMyChange);
  303. $sHtml = '<table id="bulk_preview" style="border-collapse: collapse;">';
  304. $sHtml .= '<tr><th style="padding:2px;border-right: 2px #fff solid;">Line</th>';
  305. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Status</th>';
  306. $sHtml .= '<th style="padding:2px;border-right: 2px #fff solid;">Object</th>';
  307. foreach($aFieldsMapping as $iNumber => $sAttCode)
  308. {
  309. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  310. {
  311. $sHtml .= "<th style=\"padding:2px;border-right: 2px #fff solid;\">".MetaModel::GetLabel($sClassName, $sAttCode)."</th>";
  312. }
  313. }
  314. $sHtml .= '<th>Message</th>';
  315. $sHtml .= '</tr>';
  316. $iErrors = 0;
  317. $iCreated = 0;
  318. $iModified = 0;
  319. $iUnchanged = 0;
  320. foreach($aRes as $iLine => $aResRow)
  321. {
  322. $oStatus = $aResRow['__STATUS__'];
  323. $sUrl = '';
  324. $sMessage = '';
  325. $sCSSRowClass = '';
  326. $sCSSMessageClass = 'cell_ok';
  327. switch(get_class($oStatus))
  328. {
  329. case 'RowStatus_NoChange':
  330. $iUnchanged++;
  331. $sFinalClass = $aResRow['finalclass'];
  332. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  333. $sUrl = $oObj->GetHyperlink();
  334. $sStatus = '<img src="../images/unchanged.png" title="'.Dict::S('UI:CSVReport-Icon-Unchanged').'">';
  335. $sCSSRowClass = 'row_unchanged';
  336. break;
  337. case 'RowStatus_Modify':
  338. $iModified++;
  339. $sFinalClass = $aResRow['finalclass'];
  340. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  341. $sUrl = $oObj->GetHyperlink();
  342. $sStatus = '<img src="../images/modified.png" title="'.Dict::S('UI:CSVReport-Icon-Modified').'">';
  343. $sCSSRowClass = 'row_modified';
  344. break;
  345. case 'RowStatus_Disappeared':
  346. $iModified++;
  347. $sFinalClass = $aResRow['finalclass'];
  348. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  349. $sUrl = $oObj->GetHyperlink();
  350. $sStatus = '<img src="../images/delete.png" title="'.Dict::S('UI:CSVReport-Icon-Missing').'">';
  351. $sCSSRowClass = 'row_modified';
  352. if ($bSimulate)
  353. {
  354. $sMessage = Dict::S('UI:CSVReport-Object-MissingToUpdate');
  355. }
  356. else
  357. {
  358. $sMessage = Dict::S('UI:CSVReport-Object-MissingUpdated');
  359. }
  360. break;
  361. case 'RowStatus_NewObj':
  362. $iCreated++;
  363. $sFinalClass = $aResRow['finalclass'];
  364. $sStatus = '<img src="../images/added.png" title="'.Dict::S('UI:CSVReport-Icon-Created').'">';
  365. $sCSSRowClass = 'row_added';
  366. if ($bSimulate)
  367. {
  368. $sMessage = Dict::S('UI:CSVReport-Object-ToCreate');
  369. }
  370. else
  371. {
  372. $sFinalClass = $aResRow['finalclass'];
  373. $oObj = MetaModel::GetObject($sFinalClass, $aResRow['id']->GetPureValue());
  374. $sUrl = $oObj->GetHyperlink();
  375. $sMessage = Dict::S('UI:CSVReport-Object-Created');
  376. }
  377. break;
  378. case 'RowStatus_Issue':
  379. $iErrors++;
  380. $sMessage .= $oPage->GetP($oStatus->GetDescription());
  381. $sStatus = '<img src="../images/error.png" title="'.Dict::S('UI:CSVReport-Icon-Error').'">';//translate
  382. $sCSSMessageClass = 'cell_error';
  383. $sCSSRowClass = 'row_error';
  384. if (array_key_exists($iLine, $aData))
  385. {
  386. $aRow = $aData[$iLine];
  387. $aResult[] = $sTextQualifier.implode($sTextQualifier.$sSeparator.$sTextQualifier,$aRow).$sTextQualifier; // Remove the first line and store it in case of error
  388. }
  389. break;
  390. }
  391. $sHtml .= '<tr class="'.$sCSSRowClass.'">';
  392. $sHtml .= "<td style=\"background-color:#f1f1f1;border-right:2px #fff solid;\">".sprintf("%0{$sMaxLen}d", 1+$iLine+$iRealSkippedLines)."</td>";
  393. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;border-right:2px #fff solid;\">$sStatus</td>";
  394. $sHtml .= "<td style=\"text-align:center;background-color:#f1f1f1;\">$sUrl</td>";
  395. foreach($aFieldsMapping as $iNumber => $sAttCode)
  396. {
  397. if (!empty($sAttCode) && ($sAttCode != ':none:') && ($sAttCode != 'finalclass'))
  398. {
  399. $oCellStatus = $aResRow[$iNumber -1];
  400. $sCellMessage = '';
  401. if (isset($aExternalKeysByColumn[$iNumber -1]))
  402. {
  403. $sExtKeyName = $aExternalKeysByColumn[$iNumber -1];
  404. $oExtKeyCellStatus = $aResRow[$sExtKeyName];
  405. switch(get_class($oExtKeyCellStatus))
  406. {
  407. case 'CellStatus_Issue':
  408. case 'CellStatus_SearchIssue':
  409. case 'CellStatus_NullIssue':
  410. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  411. break;
  412. case 'CellStatus_Ambiguous':
  413. $sCellMessage .= $oPage->GetP($oExtKeyCellStatus->GetDescription());
  414. break;
  415. default:
  416. // Do nothing
  417. }
  418. }
  419. $sHtmlValue = $oCellStatus->GetDisplayableValue();
  420. switch(get_class($oCellStatus))
  421. {
  422. case 'CellStatus_Issue':
  423. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  424. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">'.Dict::Format('UI:CSVReport-Object-Error', $sHtmlValue).$sCellMessage.'</td>';
  425. break;
  426. case 'CellStatus_SearchIssue':
  427. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  428. $sHtml .= '<td class="cell_error">ERROR: '.$sHtmlValue.$sCellMessage.'</td>';
  429. break;
  430. case 'CellStatus_Ambiguous':
  431. $sCellMessage .= $oPage->GetP($oCellStatus->GetDescription());
  432. $sHtml .= '<td class="cell_error" style="border-right:1px #eee solid;">'.Dict::Format('UI:CSVReport-Object-Ambiguous', $sHtmlValue).$sCellMessage.'</td>';
  433. break;
  434. case 'CellStatus_Modify':
  435. $sHtml .= '<td class="cell_modified" style="border-right:1px #eee solid;"><b>'.$sHtmlValue.'</b></td>';
  436. break;
  437. default:
  438. $sHtml .= '<td class="cell_ok" style="border-right:1px #eee solid;">'.$sHtmlValue.$sCellMessage.'</td>';
  439. }
  440. }
  441. }
  442. $sHtml .= "<td class=\"$sCSSMessageClass\" style=\"background-color:#f1f1f1;\">$sMessage</td>";
  443. $sHtml .= '</tr>';
  444. }
  445. $iUnchanged = count($aRes) - $iErrors - $iModified - $iCreated;
  446. $sHtml .= '</table>';
  447. $oPage->add('<div class="wizContainer" style="width:auto;display:inline-block;">');
  448. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post">');
  449. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  450. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  451. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  452. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  453. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>');
  454. $oPage->add('<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>');
  455. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  456. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  457. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  458. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  459. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'"/>');
  460. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  461. if (!empty($sSynchroScope))
  462. {
  463. foreach($aSynchroUpdate as $sKey => $value)
  464. {
  465. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  466. }
  467. }
  468. foreach($aFieldsMapping as $iNumber => $sAttCode)
  469. {
  470. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  471. }
  472. foreach($aSearchFields as $index => $sDummy)
  473. {
  474. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  475. }
  476. $aDisplayFilters = array();
  477. if ($bSimulate)
  478. {
  479. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsWillStayUnchanged');
  480. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWillBeModified');
  481. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWillBeAdded');
  482. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsWillHaveErrors');
  483. }
  484. else
  485. {
  486. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsRemainedUnchanged');
  487. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWereModified');
  488. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWereAdded');
  489. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsHadErrors');
  490. }
  491. $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;');
  492. $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;');
  493. $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;');
  494. $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>');
  495. $oPage->add('<div class="white" style="display:inline-block">');
  496. $oPage->add($sHtml);
  497. $oPage->add('</div> <!-- end of preview -->');
  498. $oPage->add('<p>');
  499. if($bSimulate)
  500. {
  501. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Restart').'" onClick="CSVRestart()"/>&nbsp;&nbsp;');
  502. }
  503. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  504. $bShouldConfirm = false;
  505. if ($bSimulate)
  506. {
  507. // if there are *too many* changes, we should ask the user for a confirmation
  508. if (count($aRes) >= MetaModel::GetConfig()->Get('csv_import_min_object_confirmation'))
  509. {
  510. $fErrorsPercentage = (100.0*$iErrors)/count($aRes);
  511. if ($fErrorsPercentage >= MetaModel::GetConfig()->Get('csv_import_errors_percentage'))
  512. {
  513. $sMessage = Dict::Format('UI:CSVReport-Stats-Errors', $fErrorsPercentage);
  514. $bShouldConfirm = true;
  515. }
  516. $fCreatedPercentage = (100.0*$iCreated)/count($aRes);
  517. if ($fCreatedPercentage >= MetaModel::GetConfig()->Get('csv_import_creations_percentage'))
  518. {
  519. $sMessage = Dict::Format('UI:CSVReport-Stats-Created', $fCreatedPercentage);
  520. $bShouldConfirm = true;
  521. }
  522. $fModifiedPercentage = (100.0*$iModified)/count($aRes);
  523. if ($fModifiedPercentage >= MetaModel::GetConfig()->Get('csv_import_modifications_percentage'))
  524. {
  525. $sMessage = Dict::Format('UI:CSVReport-Stats-Modified', $fModifiedPercentage);
  526. $bShouldConfirm = true;
  527. }
  528. }
  529. $iCount = count($aRes);
  530. //$oPage->add('<input type="submit" value="'.Dict::S('UI:Button:DoImport').'" onClick="$(\'#wizForm\').block();"/></p>');
  531. $sConfirm = $bShouldConfirm ? 'true' : 'false';
  532. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:DoImport')."\" onClick=\"return DoSubmit($sConfirm);\"/></p>");
  533. }
  534. else
  535. {
  536. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Done').'"/></p>');
  537. }
  538. $oPage->add('</form>');
  539. $oPage->add('</div> <!-- end of wizForm -->');
  540. if ($bShouldConfirm)
  541. {
  542. $oPage->add('<div id="dlg_confirmation" title="Please confirm the operation">');
  543. $oPage->add('<p style="text-align:center"><b>'.$sMessage.'</b></p>');
  544. $oPage->add('<p style="text-align:center">Are you sure you want to do this ?</p>');
  545. $oPage->add('<div id="confirmation_chart"></div>');
  546. $oPage->add('</div> <!-- end of dlg_confirmation -->');
  547. $oPage->add_ready_script(
  548. <<<EOF
  549. $('#dlg_confirmation').dialog(
  550. {
  551. height: 'auto',
  552. width: 500,
  553. modal:true,
  554. autoOpen: false,
  555. buttons:
  556. {
  557. 'Yes': RunImport,
  558. 'No': CancelImport
  559. }
  560. });
  561. swfobject.embedSWF( "../images/open-flash-chart.swf",
  562. "confirmation_chart",
  563. "100%", "300","9.0.0",
  564. "expressInstall.swf",
  565. {},
  566. {'wmode': 'transparent'}
  567. );
  568. EOF
  569. );
  570. }
  571. $oPage->add_script(
  572. <<< EOF
  573. function CSVGoBack()
  574. {
  575. $('input[name=step]').val($iCurrentStep-1);
  576. $('#wizForm').submit();
  577. }
  578. function CSVRestart()
  579. {
  580. $('input[name=step]').val(1);
  581. $('#wizForm').submit();
  582. }
  583. function ToggleRows(sCSSClass)
  584. {
  585. $('.'+sCSSClass).toggle();
  586. }
  587. function DoSubmit(bConfirm)
  588. {
  589. if (bConfirm) //Ask for a confirmation
  590. {
  591. $('#dlg_confirmation').dialog('open');
  592. }
  593. else
  594. {
  595. // Submit the form
  596. $('#wizForm').block();
  597. $('#wizForm').submit();
  598. }
  599. return false;
  600. }
  601. function CancelImport()
  602. {
  603. $('#dlg_confirmation').dialog('close');
  604. }
  605. function RunImport()
  606. {
  607. $('#dlg_confirmation').dialog('close');
  608. // Submit the form
  609. $('#wizForm').block();
  610. $('#wizForm').submit();
  611. }
  612. function open_flash_chart_data()
  613. {
  614. var iErrors = $iErrors;
  615. var iModified = $iModified;
  616. var iCreated = $iCreated;
  617. var iUnchanged = $iUnchanged;
  618. var fAlpha = 0.9;
  619. var oResult = {
  620. "elements": [
  621. {
  622. "type": "pie",
  623. "tip": "#label# (#percent#)",
  624. "gradient-fill": true,
  625. "font-size": 14,
  626. "colours":[],
  627. "values": [],
  628. "animate":[
  629. {
  630. "type": "fade"
  631. }
  632. ]
  633. }
  634. ],
  635. "x_axis": null,
  636. "font-size": 14,
  637. "bg_colour": "#EEEEEE"
  638. };
  639. if (iErrors > 0)
  640. {
  641. var oErrors =
  642. {
  643. "value": iErrors,
  644. "label": "Errors: "+iErrors,
  645. "alpha": fAlpha,
  646. "label-colour": "#CC3333",
  647. };
  648. oResult.elements[0].values.push(oErrors);
  649. oResult.elements[0].colours.push('#FF6666');
  650. }
  651. if (iModified > 0)
  652. {
  653. var oModified =
  654. {
  655. "value": iModified,
  656. "label": "Modified: "+iModified,
  657. "alpha": fAlpha,
  658. "label-colour": "#3333CC",
  659. };
  660. oResult.elements[0].values.push(oModified);
  661. oResult.elements[0].colours.push('#6666FF');
  662. }
  663. if (iCreated > 0)
  664. {
  665. var oCreated =
  666. {
  667. "value": iCreated,
  668. "label": "Created: "+iCreated,
  669. "alpha": fAlpha,
  670. "label-colour": "#33CC33",
  671. };
  672. oResult.elements[0].values.push(oCreated);
  673. oResult.elements[0].colours.push('#66FF66');
  674. }
  675. if (iUnchanged > 0)
  676. {
  677. var oUnchanged =
  678. {
  679. "value": iUnchanged,
  680. "label": "Unchanged: "+iUnchanged,
  681. "alpha": fAlpha,
  682. "label-colour": "#333333",
  683. };
  684. oResult.elements[0].values.push(oUnchanged);
  685. oResult.elements[0].colours.push('#666666');
  686. }
  687. return JSON.stringify(oResult);
  688. }
  689. EOF
  690. );
  691. if ($iErrors > 0)
  692. {
  693. return $aResult;
  694. }
  695. else
  696. {
  697. return null;
  698. }
  699. }
  700. /**
  701. * Perform the actual load of the CSV data and display the results
  702. * @param WebPage $oPage The web page to display the wizard
  703. * @return void
  704. */
  705. function LoadData(WebPage $oPage)
  706. {
  707. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep5').'</h2>');
  708. $aResult = ProcessCSVData($oPage, false /* simulate = false */);
  709. if (is_array($aResult))
  710. {
  711. $oPage->StartCollapsibleSection(Dict::S('UI:CSVImport:LinesNotImported'), false);
  712. $oPage->p(Dict::S('UI:CSVImport:LinesNotImported+'));
  713. $oPage->add('<textarea rows="30" cols="100">');
  714. $oPage->add(htmlentities(implode("\n", $aResult), ENT_QUOTES, 'UTF-8'));
  715. $oPage->add('</textarea>');
  716. $oPage->EndCollapsibleSection();
  717. }
  718. }
  719. /**
  720. * Simulate the load of the CSV data and display the results
  721. * @param WebPage $oPage The web page to display the wizard
  722. * @return void
  723. */
  724. function Preview(WebPage $oPage)
  725. {
  726. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep4').'</h2>');
  727. ProcessCSVData($oPage, true /* simulate */);
  728. }
  729. /**
  730. * Select the mapping between the CSV column and the fields of the objects
  731. * @param WebPage $oPage The web page to display the wizard
  732. * @return void
  733. */
  734. function SelectMapping(WebPage $oPage)
  735. {
  736. $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data');
  737. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '', false, 'raw_data');
  738. $sSeparator = utils::ReadParam('separator', ',', false, 'raw_data');
  739. if ($sSeparator == 'tab') $sSeparator = "\t";
  740. if ($sSeparator == 'other')
  741. {
  742. $sSeparator = utils::ReadParam('other_separator', ',', false, 'raw_data');
  743. }
  744. $sTextQualifier = utils::ReadParam('text_qualifier', '"', false, 'raw_data');
  745. if ($sTextQualifier == 'other')
  746. {
  747. $sTextQualifier = utils::ReadParam('other_qualifier', '"', false, 'raw_data');
  748. }
  749. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  750. $sClassName = utils::ReadParam('class_name', '', false, 'class');
  751. $bAdvanced = utils::ReadParam('advanced', 0);
  752. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  753. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  754. if (!empty($sSynchroScope))
  755. {
  756. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  757. $sClassName = $oSearch->GetClass(); // If a synchronization scope is set, then the class is fixed !
  758. $oSet = new DBObjectSet($oSearch);
  759. $iCount = $oSet->Count();
  760. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  761. $sClassesSelect = "<select id=\"select_class_name\" name=\"class_name\"><option value=\"$sClassName\" selected>".MetaModel::GetName($sClassName)."</option>";
  762. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  763. }
  764. else
  765. {
  766. $sClassesSelect = GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY);
  767. }
  768. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep3').'</h2>');
  769. $oPage->add('<div class="wizContainer">');
  770. $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').' ');
  771. $oPage->add($sClassesSelect);
  772. $oPage->add('</td><td style="text-align:right"><input type="checkbox" name="advanced" value="1" '.IsChecked($bAdvanced, 1).' onClick="DoMapping()">&nbsp;'.Dict::S('UI:CSVImport:AdvancedMode').'</td></tr></table>');
  773. $oPage->add('<div style="padding:1em;display:none" id="advanced_help" style="display:none">'.Dict::S('UI:CSVImport:AdvancedMode+').'</div>');
  774. $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>');
  775. $oPage->add('<input type="hidden" name="step" value="4"/>');
  776. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  777. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  778. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  779. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>');
  780. $oPage->add('<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>');
  781. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  782. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  783. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'">');
  784. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'">');
  785. if (!empty($sSynchroScope))
  786. {
  787. foreach($aSynchroUpdate as $sKey => $value)
  788. {
  789. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  790. }
  791. }
  792. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Restart').'" onClick="CSVRestart()"/>&nbsp;&nbsp;');
  793. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  794. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:SimulateImport').'"/></p>');
  795. $oPage->add('</form>');
  796. $oPage->add('</div>');
  797. $sAlertIncompleteMapping = Dict::S('UI:CSVImport:AlertIncompleteMapping');
  798. $sAlertNoSearchCriteria = Dict::S('UI:CSVImport:AlertNoSearchCriteria');
  799. $oPage->add_ready_script(
  800. <<<EOF
  801. $('#select_class_name').change( function(ev) { DoMapping(); } );
  802. EOF
  803. );
  804. if ($sClassName != '')
  805. {
  806. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  807. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  808. $sFieldsMapping = addslashes(json_encode($aFieldsMapping));
  809. $sSearchFields = addslashes(json_encode($aSearchFields));
  810. $oPage->add_ready_script("DoMapping('$sFieldsMapping', '$sSearchFields');"); // There is already a class selected, run the mapping
  811. }
  812. $oPage->add_script(
  813. <<<EOF
  814. var aDefaultKeys = new Array();
  815. function CSVGoBack()
  816. {
  817. $('input[name=step]').val(2);
  818. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  819. $('#wizForm').submit();
  820. }
  821. function CSVRestart()
  822. {
  823. $('input[name=step]').val(1);
  824. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  825. $('#wizForm').submit();
  826. }
  827. var ajax_request = null;
  828. function DoMapping(sInitFieldsMapping, sInitSearchFields)
  829. {
  830. var class_name = $('select[name=class_name]').val();
  831. var advanced = $('input[name=advanced]:checked').val();
  832. if (advanced != 1)
  833. {
  834. $('#advanced_help').hide();
  835. }
  836. else
  837. {
  838. $('#advanced_help').show();
  839. }
  840. if (class_name != '')
  841. {
  842. var separator = $('input[name=separator]').val();
  843. var text_qualifier = $('input[name=text_qualifier]').val();
  844. var header_line = $('input[name=header_line]').val();
  845. var do_skip_lines = 0;
  846. if ($('input[name=box_skiplines]').val() == '1')
  847. {
  848. do_skip_lines = $('input[name=nb_skipped_lines]').val();
  849. }
  850. var csv_data = $('input[name=csvdata]').val();
  851. var encoding = $('input[name=encoding]').val();
  852. if (advanced != 1)
  853. {
  854. advanced = 0;
  855. }
  856. $('#mapping').block();
  857. // Make sure that we cancel any pending request before issuing another
  858. // since responses may arrive in arbitrary order
  859. if (ajax_request != null)
  860. {
  861. ajax_request.abort();
  862. ajax_request = null;
  863. }
  864. var aParams = { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator,
  865. qualifier: text_qualifier, do_skip_lines: do_skip_lines, header_line: header_line, class_name: class_name,
  866. advanced: advanced, encoding: encoding };
  867. if (sInitFieldsMapping != undefined)
  868. {
  869. aParams.init_field_mapping = sInitFieldsMapping;
  870. aParams.init_search_field = sInitSearchFields;
  871. }
  872. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  873. aParams,
  874. function(data) {
  875. $('#mapping').empty();
  876. $('#mapping').append(data);
  877. $('#mapping').unblock();
  878. }
  879. );
  880. }
  881. }
  882. function CheckValues()
  883. {
  884. bResult = true;
  885. bMappingOk = true;
  886. bSearchOk = false;
  887. $('select[name^=field]').each( function() {
  888. if ($(this).val() == '')
  889. {
  890. $(this).parent().css({'border': '2px #D81515 solid'});
  891. bMappingOk = false;
  892. bResult = false;
  893. }
  894. else
  895. {
  896. $(this).parent().css({'border': '0'});
  897. }
  898. });
  899. // At least one search field must be checked
  900. $('input[name^=search]:checked').each( function() {
  901. bSearchOk = true;
  902. });
  903. if (!bMappingOk)
  904. {
  905. alert("$sAlertIncompleteMapping");
  906. }
  907. if (!bSearchOk)
  908. {
  909. bResult = false;
  910. alert("$sAlertNoSearchCriteria");
  911. }
  912. if (bResult)
  913. {
  914. $('#mapping').block();
  915. // Re-enable all search_xxx checkboxes so that their value gets posted
  916. $('input[name^=search]').each(function() {
  917. $(this).attr('disabled', false);
  918. });
  919. }
  920. return bResult;
  921. }
  922. function DoCheckMapping()
  923. {
  924. // Check if there is a field mapped to 'id'
  925. // In which case, it's the only possible search key
  926. var idSelected = 0;
  927. var nbSearchKeys = $('input[name^=search]:checked').length;
  928. var nbMappings = $('select[name^=field]').length;
  929. for(index=1; index <= nbMappings; index++)
  930. {
  931. var selectedValue = $('#mapping_'+index).val();
  932. if (selectedValue == 'id')
  933. {
  934. idSelected = index;
  935. }
  936. }
  937. for (index=1; index <= nbMappings; index++)
  938. {
  939. sMappingValue = $('#mapping_'+index).val();
  940. if ((sMappingValue == '') || (sMappingValue == ':none:'))
  941. {
  942. // Non-mapped field, uncheck and disabled
  943. $('#search_'+index).attr('checked', false);
  944. $('#search_'+index).attr('disabled', true);
  945. }
  946. else if (index == idSelected)
  947. {
  948. // The 'id' field was mapped, it's the only possible reconciliation key
  949. $('#search_'+index).attr('checked', true);
  950. $('#search_'+index).attr('disabled', true);
  951. }
  952. else
  953. {
  954. if (idSelected > 0)
  955. {
  956. // The 'id' field was mapped, it's the only possible reconciliation key
  957. $('#search_'+index).attr('checked', false);
  958. $('#search_'+index).attr('disabled', true);
  959. }
  960. else
  961. {
  962. $('#search_'+index).attr('disabled', false);
  963. if (nbSearchKeys == 0)
  964. {
  965. // No search key was selected, select the default ones
  966. for(j =0; j < aDefaultKeys.length; j++)
  967. {
  968. if (sMappingValue == aDefaultKeys[j])
  969. {
  970. $('#search_'+index).attr('checked', true);
  971. }
  972. }
  973. }
  974. }
  975. }
  976. }
  977. }
  978. EOF
  979. );
  980. }
  981. /**
  982. * Select the options of the CSV load and check for CSV parsing errors
  983. * @param WebPage $oPage The current web page
  984. * @return void
  985. */
  986. function SelectOptions(WebPage $oPage)
  987. {
  988. $sOperation = utils::ReadParam('operation', 'csv_data');
  989. $sCSVData = '';
  990. switch($sOperation)
  991. {
  992. case 'file_upload':
  993. $oDocument = utils::ReadPostedDocument('csvdata');
  994. if (!$oDocument->IsEmpty())
  995. {
  996. $sCSVData = $oDocument->GetData();
  997. }
  998. break;
  999. default:
  1000. $sCSVData = utils::ReadPostedParam('csvdata', '', 'raw_data');
  1001. }
  1002. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  1003. // Compute a subset of the data set, now that we know the charset
  1004. if ($sEncoding == 'UTF-8')
  1005. {
  1006. // Remove the BOM if any
  1007. if (substr($sCSVData, 0, 3) == UTF8_BOM)
  1008. {
  1009. $sCSVData = substr($sCSVData, 3);
  1010. }
  1011. // Clean the input
  1012. // Todo: warn the user if some characters are lost/substituted
  1013. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  1014. }
  1015. else
  1016. {
  1017. $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  1018. }
  1019. $aGuesses = GuessParameters($sUTF8Data); // Try to predict the parameters, based on the input data
  1020. $sSeparator = utils::ReadParam('separator', '', false, 'raw_data');
  1021. if ($sSeparator == '') // May be set to an empty value by the previous page
  1022. {
  1023. $sSeparator = $aGuesses['separator'];
  1024. }
  1025. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  1026. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  1027. if ($sSeparator == 'tab') $sSeparator = "\t";
  1028. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  1029. $sTextQualifier = utils::ReadParam('text_qualifier', '', false, 'raw_data');
  1030. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  1031. {
  1032. $sTextQualifier = $aGuesses['qualifier'];
  1033. }
  1034. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  1035. $bHeaderLine = utils::ReadParam('header_line', 0);
  1036. $sClassName = utils::ReadParam('class_name', '', false, 'class');
  1037. $bAdvanced = utils::ReadParam('advanced', 0);
  1038. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  1039. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  1040. // Create a truncated version of the data used for the fast preview
  1041. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  1042. $iMaxLen = strlen($sUTF8Data);
  1043. if ($iMaxLen > 0)
  1044. {
  1045. $iMaxLines = 20;
  1046. $iCurPos = true;
  1047. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  1048. {
  1049. $pos = strpos($sUTF8Data, "\n", $iCurPos);
  1050. if ($pos !== false)
  1051. {
  1052. $iCurPos = 1+$pos;
  1053. }
  1054. else
  1055. {
  1056. $iCurPos = strlen($sUTF8Data);
  1057. $iMaxLines = 1;
  1058. }
  1059. $iMaxLines--;
  1060. }
  1061. $sCSVDataTruncated = substr($sUTF8Data, 0, $iCurPos);
  1062. }
  1063. else
  1064. {
  1065. $sCSVDataTruncated = '';
  1066. }
  1067. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  1068. if (!empty($sSynchroScope))
  1069. {
  1070. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1071. $sClassName = $oSearch->GetClass();
  1072. $oSet = new DBObjectSet($oSearch);
  1073. $iCount = $oSet->Count();
  1074. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1075. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1076. }
  1077. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep2').'</h2>');
  1078. $oPage->add('<div class="wizContainer">');
  1079. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;">');
  1080. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  1081. $oPage->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  1082. $oPage->add('<p><input type="radio" name="separator" value="," onClick="DoPreview()"'.IsChecked($sSeparator, ',').'/> '.Dict::S('UI:CSVImport:SeparatorComma+').'<br/>');
  1083. $oPage->add('<input type="radio" name="separator" value=";" onClick="DoPreview()"'.IsChecked($sSeparator, ';').'/> '.Dict::S('UI:CSVImport:SeparatorSemicolon+').'<br/>');
  1084. $oPage->add('<input type="radio" name="separator" value="tab" onClick="DoPreview()"'.IsChecked($sSeparator, "\t").'/> '.Dict::S('UI:CSVImport:SeparatorTab+').'<br/>');
  1085. $oPage->add('<input type="radio" name="separator" value="other" onClick="DoPreview()"'.IsChecked($sOtherSeparator, '', true).'/> '.Dict::S('UI:CSVImport:SeparatorOther').' <input type="text" size="3" maxlength="1" name="other_separator" id="other_separator" value="'.$sOtherSeparator.'" onClick="DoPreview()"/>');
  1086. $oPage->add('</p>');
  1087. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;">');
  1088. $oPage->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  1089. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onClick="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> '.Dict::S('UI:CSVImport:QualifierDoubleQuote+').'<br/>');
  1090. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onClick="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> '.Dict::S('UI:CSVImport:QualifierSimpleQuote+').'<br/>');
  1091. $oPage->add('<input type="radio" name="text_qualifier" value="other" onClick="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()"/>');
  1092. $oPage->add('</p>');
  1093. $oPage->add('</td><td style="vertical-align:top;">');
  1094. $oPage->add('<h3>'.Dict::S('UI:CSVImport:CommentsAndHeader').'</h3>');
  1095. $oPage->add('<p><input type="checkbox" name="header_line" id="box_header" value="1" onClick="DoPreview()"'.IsChecked($bHeaderLine, 1).'/> '.Dict::S('UI:CSVImport:TreatFirstLineAsHeader').'<p>');
  1096. $oPage->add('<p><input type="checkbox" name="box_skiplines" value="1" id="box_skiplines" onClick="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>');
  1097. $oPage->add('</td></tr></table>');
  1098. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  1099. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sUTF8Data, ENT_QUOTES, 'UTF-8').'"/>');
  1100. // The encoding has changed, keep that information within the wizard
  1101. $oPage->add('<input type="hidden" name="encoding" value="UTF-8">');
  1102. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  1103. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  1104. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  1105. foreach($aFieldsMapping as $iNumber => $sAttCode)
  1106. {
  1107. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  1108. }
  1109. foreach($aSearchFields as $index => $sDummy)
  1110. {
  1111. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  1112. }
  1113. $oPage->add('<input type="hidden" name="step" value="3"/>');
  1114. if (!empty($sSynchroScope))
  1115. {
  1116. foreach($aSynchroUpdate as $sKey => $value)
  1117. {
  1118. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  1119. }
  1120. }
  1121. $oPage->add('<div id="preview">');
  1122. $oPage->add('<p style="text-align:center">'.Dict::S('UI:CSVImport:CSVDataPreview').'</p>');
  1123. $oPage->add('</div>');
  1124. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="GoBack()"/>');
  1125. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Next').'"/>');
  1126. $oPage->add('</form>');
  1127. $oPage->add('</div>');
  1128. $oPage->add_script(
  1129. <<<EOF
  1130. function GoBack()
  1131. {
  1132. $('input[name=step]').val(1);
  1133. $('#wizForm').submit();
  1134. }
  1135. var ajax_request = null;
  1136. function DoPreview()
  1137. {
  1138. var separator = $('input[name=separator]:checked').val();
  1139. if (separator == 'other')
  1140. {
  1141. separator = $('#other_separator').val();
  1142. }
  1143. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  1144. if (text_qualifier == 'other')
  1145. {
  1146. text_qualifier = $('#other_qualifier').val();
  1147. }
  1148. var do_skip_lines = 0;
  1149. if ($('#box_skiplines:checked').val() != null)
  1150. {
  1151. do_skip_lines = $('#nb_skipped_lines').val();
  1152. }
  1153. var header_line = 0;
  1154. if ($('#box_header:checked').val() != null)
  1155. {
  1156. header_line = 1;
  1157. }
  1158. var encoding = $('input[name=encoding]').val();
  1159. $('#preview').block();
  1160. // Make sure that we cancel any pending request before issuing another
  1161. // since responses may arrive in arbitrary order
  1162. if (ajax_request != null)
  1163. {
  1164. ajax_request.abort();
  1165. ajax_request = null;
  1166. }
  1167. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  1168. { operation: 'parser_preview', enctype: 'multipart/form-data', csvdata: $("#csvdata_truncated").val(), separator: separator, qualifier: text_qualifier, do_skip_lines: do_skip_lines, header_line: header_line, encoding: encoding },
  1169. function(data) {
  1170. $('#preview').empty();
  1171. $('#preview').append(data);
  1172. $('#preview').unblock();
  1173. }
  1174. );
  1175. }
  1176. EOF
  1177. );
  1178. $oPage->add_ready_script('DoPreview();');
  1179. }
  1180. /**
  1181. * Prompt for the data to be loaded (either via a file or a copy/paste)
  1182. * @param WebPage $oPage The current web page
  1183. * @return void
  1184. */
  1185. function Welcome(iTopWebPage $oPage)
  1186. {
  1187. // Encodings supported:
  1188. // ICONV_CODE => Display Name
  1189. // Each iconv installation supports different encodings
  1190. // Some reasonably common and useful encodnings are listed here
  1191. $aPossibleEncodings = array(
  1192. 'UTF-8' => 'Unicode (UTF-8)',
  1193. 'ISO-8859-1' => 'Western (ISO-8859-1)',
  1194. 'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
  1195. 'WINDOWS-1252' => 'Western (Windows 1252)',
  1196. 'ISO-8859-15' => 'Western (ISO-8859-15)',
  1197. );
  1198. // Some more encodings can be specified in the config file
  1199. $aExtraCharsets = MetaModel::GetConfig()->GetCSVImportCharsets();
  1200. $aPossibleEncodings = array_merge($aPossibleEncodings, $aExtraCharsets);
  1201. asort($aPossibleEncodings);
  1202. $sSynchroScope = utils::ReadParam('synchro_scope', '', false, 'raw_data');
  1203. if (!empty($sSynchroScope))
  1204. {
  1205. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1206. $sClassName = $oSearch->GetClass();
  1207. $oSet = new DBObjectSet($oSearch);
  1208. $iCount = $oSet->Count();
  1209. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1210. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1211. }
  1212. else
  1213. {
  1214. $aSynchroUpdate = null;
  1215. }
  1216. $oPage->add("<div><p><h1>".Dict::S('UI:Title:BulkImport+')."</h1></p></div>\n");
  1217. $oPage->AddTabContainer('tabs1');
  1218. $sSeparator = utils::ReadParam('separator', '', false, 'raw_data');
  1219. $sTextQualifier = utils::ReadParam('text_qualifier', '', false, 'raw_data');
  1220. $bHeaderLine = utils::ReadParam('header_line', true);
  1221. $sClassName = utils::ReadParam('class_name', '');
  1222. $bAdvanced = utils::ReadParam('advanced', 0);
  1223. $sEncoding = utils::ReadParam('encoding', '');
  1224. if ($sEncoding == '')
  1225. {
  1226. $sEncoding = MetaModel::GetConfig()->Get('csv_file_default_charset');
  1227. }
  1228. $aFieldsMapping = utils::ReadParam('field', array(), false, 'raw_data');
  1229. $aSearchFields = utils::ReadParam('search_field', array(), false, 'field_name');
  1230. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:SelectFile').'</p>'.
  1231. '<p><input type="file" name="csvdata"/></p>';
  1232. $sFileLoadHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1233. $sFileLoadHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE 8 has some troubles if the font is different
  1234. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1235. {
  1236. $sSelected = '';
  1237. if ($sEncoding == $sIconvCode)
  1238. {
  1239. $sSelected = ' selected';
  1240. }
  1241. $sFileLoadHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1242. }
  1243. $sFileLoadHtml .= '</select></p>';
  1244. $sFileLoadHtml .= '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1245. '<input type="hidden" name="step" value="2"/>'.
  1246. '<input type="hidden" name="operation" value="file_upload"/>'.
  1247. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1248. '<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>'.
  1249. '<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>'.
  1250. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1251. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1252. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1253. if (!empty($sSynchroScope))
  1254. {
  1255. foreach($aSynchroUpdate as $sKey => $value)
  1256. {
  1257. $sFileLoadHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1258. }
  1259. }
  1260. foreach($aFieldsMapping as $iNumber => $sAttCode)
  1261. {
  1262. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  1263. }
  1264. foreach($aSearchFields as $index => $sDummy)
  1265. {
  1266. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  1267. }
  1268. $sFileLoadHtml .= '</form></div>';
  1269. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:LoadFromFile'), $sFileLoadHtml);
  1270. $sCSVData = utils::ReadParam('csvdata', '', false, 'raw_data');
  1271. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:PasteData').'</p>'.
  1272. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>';
  1273. $sPasteDataHtml .= '<hidden name="encoding" value="UTF-8">';
  1274. $sPasteDataHtml .=
  1275. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1276. '<input type="hidden" name="step" value="2"/>'.
  1277. '<input type="hidden" name="operation" value="csv_data"/>'.
  1278. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  1279. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  1280. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1281. '<input type="hidden" name="nb_skipped_lines" value="'.utils::ReadParam('nb_skipped_lines', '0').'"/>'.
  1282. '<input type="hidden" name="box_skiplines" value="'.utils::ReadParam('box_skiplines', '0').'"/>'.
  1283. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1284. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1285. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1286. if (!empty($sSynchroScope))
  1287. {
  1288. foreach($aSynchroUpdate as $sKey => $value)
  1289. {
  1290. $sPasteDataHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1291. }
  1292. }
  1293. foreach($aFieldsMapping as $iNumber => $sAttCode)
  1294. {
  1295. $sPasteDataHtml .= '<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>';
  1296. }
  1297. foreach($aSearchFields as $index => $sDummy)
  1298. {
  1299. $sPasteDataHtml .= '<input type="hidden" name="search_field['.$index.']" value="1"/>';
  1300. }
  1301. $sPasteDataHtml .= '</form></div>';
  1302. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'), $sPasteDataHtml);
  1303. if (!empty($sCSVData))
  1304. {
  1305. // When there are some data, activate the 'copy & paste' tab by default
  1306. $oPage->SelectTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'));
  1307. }
  1308. $sTemplateHtml = '<div><p>'.Dict::S('UI:CSVImport:PickClassForTemplate').' ';
  1309. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  1310. $sTemplateHtml .= '</div>';
  1311. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  1312. $sTemplateHtml .= '</div>';
  1313. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:Templates'), $sTemplateHtml);
  1314. $oPage->add_script(
  1315. <<<EOF
  1316. var ajax_request = null;
  1317. function DisplayTemplate(sClassName) {
  1318. $('#template').block();
  1319. // Make sure that we cancel any pending request before issuing another
  1320. // since responses may arrive in arbitrary order
  1321. if (ajax_request != null)
  1322. {
  1323. ajax_request.abort();
  1324. ajax_request = null;
  1325. }
  1326. ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.csvimport.php',
  1327. { operation: 'get_csv_template', class_name: sClassName },
  1328. function(data) {
  1329. $('#template').empty();
  1330. $('#template').append(data);
  1331. $('#template').unblock();
  1332. }
  1333. );
  1334. }
  1335. EOF
  1336. );
  1337. $oPage->add_ready_script(
  1338. <<<EOF
  1339. $('#select_template_class').change( function() {
  1340. DisplayTemplate(this.value);
  1341. });
  1342. EOF
  1343. );
  1344. if (Utils::GetConfig()->Get('csv_import_history_display'))
  1345. {
  1346. $oPage->SetCurrentTabContainer('tabs1');
  1347. $oPage->SetCurrentTab(Dict::S('UI:History:BulkImports'));
  1348. BulkChange::DisplayImportHistory($oPage);
  1349. }
  1350. }
  1351. switch($iStep)
  1352. {
  1353. case 10:
  1354. // Case generated by BulkChange::DisplayImportHistory
  1355. $iChange = (int)utils::ReadParam('changeid', 0);
  1356. BulkChange::DisplayImportHistoryDetails($oPage, $iChange);
  1357. break;
  1358. case 5:
  1359. LoadData($oPage);
  1360. break;
  1361. case 4:
  1362. Preview($oPage);
  1363. break;
  1364. case 3:
  1365. SelectMapping($oPage);
  1366. break;
  1367. case 2:
  1368. SelectOptions($oPage);
  1369. break;
  1370. case 1:
  1371. case 6: // Loop back here when we are done
  1372. default:
  1373. Welcome($oPage);
  1374. }
  1375. $oPage->output();
  1376. }
  1377. catch(CoreException $e)
  1378. {
  1379. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1380. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1381. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1382. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1383. $oP->output();
  1384. if (MetaModel::IsLogEnabledIssue())
  1385. {
  1386. if (MetaModel::IsValidClass('EventIssue'))
  1387. {
  1388. $oLog = new EventIssue();
  1389. $oLog->Set('message', $e->getMessage());
  1390. $oLog->Set('userinfo', '');
  1391. $oLog->Set('issue', $e->GetIssue());
  1392. $oLog->Set('impact', 'Page could not be displayed');
  1393. $oLog->Set('callstack', $e->getTrace());
  1394. $oLog->Set('data', $e->getContextData());
  1395. $oLog->DBInsertNoReload();
  1396. }
  1397. IssueLog::Error($e->getMessage());
  1398. }
  1399. // For debugging only
  1400. //throw $e;
  1401. }
  1402. catch(Exception $e)
  1403. {
  1404. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1405. $oP = new SetupPage(Dict::S('UI:PageTitle:FatalError'));
  1406. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1407. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1408. $oP->output();
  1409. if (MetaModel::IsLogEnabledIssue())
  1410. {
  1411. if (MetaModel::IsValidClass('EventIssue'))
  1412. {
  1413. $oLog = new EventIssue();
  1414. $oLog->Set('message', $e->getMessage());
  1415. $oLog->Set('userinfo', '');
  1416. $oLog->Set('issue', 'PHP Exception');
  1417. $oLog->Set('impact', 'Page could not be displayed');
  1418. $oLog->Set('callstack', $e->getTrace());
  1419. $oLog->Set('data', array());
  1420. $oLog->DBInsertNoReload();
  1421. }
  1422. IssueLog::Error($e->getMessage());
  1423. }
  1424. }
  1425. ?>