csvimport.php 56 KB

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