csvimport.php 58 KB

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