csvimport.php 53 KB

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