csvimport.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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').submit();
  863. }
  864. var ajax_request = null;
  865. function DoMapping()
  866. {
  867. var class_name = $('select[name=class_name]').val();
  868. var advanced = $('input[name=advanced]:checked').val();
  869. if (advanced != 1)
  870. {
  871. $('#advanced_help').hide();
  872. }
  873. else
  874. {
  875. $('#advanced_help').show();
  876. }
  877. if (class_name != '')
  878. {
  879. var separator = $('input[name=separator]').val();
  880. var text_qualifier = $('input[name=text_qualifier]').val();
  881. var header_line = $('input[name=header_line]').val();
  882. var nb_lines_skipped = $('input[name=nb_skipped_lines]').val();
  883. var csv_data = $('input[name=csvdata]').val();
  884. var encoding = $('input[name=encoding]').val();
  885. if (advanced != 1)
  886. {
  887. advanced = 0;
  888. }
  889. $('#mapping').block();
  890. // Make sure that we cancel any pending request before issuing another
  891. // since responses may arrive in arbitrary order
  892. if (ajax_request != null)
  893. {
  894. ajax_request.abort();
  895. ajax_request = null;
  896. }
  897. ajax_request = $.post('ajax.csvimport.php',
  898. { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator,
  899. qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, class_name: class_name,
  900. advanced: advanced, encoding: encoding },
  901. function(data) {
  902. $('#mapping').empty();
  903. $('#mapping').append(data);
  904. $('#mapping').unblock();
  905. }
  906. );
  907. }
  908. }
  909. function CheckValues()
  910. {
  911. bResult = true;
  912. bMappingOk = true;
  913. bSearchOk = false;
  914. $('select[name^=field]').each( function() {
  915. if ($(this).val() == '')
  916. {
  917. $(this).parent().css({'border': '2px #D81515 solid'});
  918. bMappingOk = false;
  919. bResult = false;
  920. }
  921. else
  922. {
  923. $(this).parent().css({'border': '0'});
  924. }
  925. });
  926. // At least one search field must be checked
  927. $('input[name^=search]:checked').each( function() {
  928. bSearchOk = true;
  929. });
  930. if (!bMappingOk)
  931. {
  932. alert("$sAlertIncompleteMapping");
  933. }
  934. if (!bSearchOk)
  935. {
  936. bResult = false;
  937. alert("$sAlertNoSearchCriteria");
  938. }
  939. if (bResult)
  940. {
  941. $('#mapping').block();
  942. // Re-enable all search_xxx checkboxes so that their value gets posted
  943. $('input[name^=search]').each(function() {
  944. $(this).attr('disabled', false);
  945. });
  946. }
  947. return bResult;
  948. }
  949. function DoCheckMapping()
  950. {
  951. // Check if there is a field mapped to 'id'
  952. // In which case, it's the only possible search key
  953. var idSelected = 0;
  954. var nbSearchKeys = $('input[name^=search]:checked').length;
  955. var nbMappings = $('select[name^=field]').length;
  956. for(index=1; index <= nbMappings; index++)
  957. {
  958. var selectedValue = $('#mapping_'+index).val();
  959. if (selectedValue == 'id')
  960. {
  961. idSelected = index;
  962. }
  963. }
  964. for (index=1; index <= nbMappings; index++)
  965. {
  966. sMappingValue = $('#mapping_'+index).val();
  967. if ((sMappingValue == '') || (sMappingValue == ':none:'))
  968. {
  969. // Non-mapped field, uncheck and disabled
  970. $('#search_'+index).attr('checked', false);
  971. $('#search_'+index).attr('disabled', true);
  972. }
  973. else if (index == idSelected)
  974. {
  975. // The 'id' field was mapped, it's the only possible reconciliation key
  976. $('#search_'+index).attr('checked', true);
  977. $('#search_'+index).attr('disabled', true);
  978. }
  979. else
  980. {
  981. if (idSelected > 0)
  982. {
  983. // The 'id' field was mapped, it's the only possible reconciliation key
  984. $('#search_'+index).attr('checked', false);
  985. $('#search_'+index).attr('disabled', true);
  986. }
  987. else
  988. {
  989. $('#search_'+index).attr('disabled', false);
  990. if (nbSearchKeys == 0)
  991. {
  992. // No search key was selected, select the default ones
  993. for(j =0; j < aDefaultKeys.length; j++)
  994. {
  995. if (sMappingValue == aDefaultKeys[j])
  996. {
  997. $('#search_'+index).attr('checked', true);
  998. }
  999. }
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. EOF
  1006. );
  1007. }
  1008. /**
  1009. * Select the options of the CSV load and check for CSV parsing errors
  1010. * @param WebPage $oPage The current web page
  1011. * @return void
  1012. */
  1013. function SelectOptions(WebPage $oPage)
  1014. {
  1015. $sOperation = utils::ReadParam('operation', 'csv_data');
  1016. $sCSVData = '';
  1017. switch($sOperation)
  1018. {
  1019. case 'file_upload':
  1020. $oDocument = utils::ReadPostedDocument('csvdata');
  1021. if (!$oDocument->IsEmpty())
  1022. {
  1023. $sCSVData = $oDocument->GetData();
  1024. }
  1025. break;
  1026. default:
  1027. $sCSVData = utils::ReadPostedParam('csvdata', '');
  1028. }
  1029. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  1030. // Compute a subset of the data set, now that we know the charset
  1031. if ($sEncoding == 'UTF-8')
  1032. {
  1033. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  1034. }
  1035. else
  1036. {
  1037. $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  1038. }
  1039. $aGuesses = GuessParameters($sUTF8Data); // Try to predict the parameters, based on the input data
  1040. $sSeparator = utils::ReadParam('separator', '');
  1041. if ($sSeparator == '') // May be set to an empty value by the previous page
  1042. {
  1043. $sSeparator = $aGuesses['separator'];
  1044. }
  1045. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  1046. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  1047. if ($sSeparator == 'tab') $sSeparator = "\t";
  1048. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  1049. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  1050. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  1051. {
  1052. $sTextQualifier = $aGuesses['qualifier'];
  1053. }
  1054. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  1055. $bHeaderLine = utils::ReadParam('header_line', 0);
  1056. $sClassName = utils::ReadParam('class_name', '');
  1057. $bAdvanced = utils::ReadParam('advanced', 0);
  1058. // Create a truncated version of the data used for the fast preview
  1059. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  1060. $iMaxLines = 20;
  1061. $iMaxLen = strlen($sUTF8Data);
  1062. $iCurPos = true;
  1063. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  1064. {
  1065. $pos = strpos($sUTF8Data, "\n", $iCurPos);
  1066. if ($pos !== false)
  1067. {
  1068. $iCurPos = 1+$pos;
  1069. }
  1070. else
  1071. {
  1072. $iCurPos = strlen($sUTF8Data);
  1073. $iMaxLines = 1;
  1074. }
  1075. $iMaxLines--;
  1076. }
  1077. $sCSVDataTruncated = substr($sUTF8Data, 0, $iCurPos);
  1078. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  1079. if (!empty($sSynchroScope))
  1080. {
  1081. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1082. $sClassName = $oSearch->GetClass();
  1083. $oSet = new DBObjectSet($oSearch);
  1084. $iCount = $oSet->Count();
  1085. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1086. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1087. }
  1088. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep2').'</h2>');
  1089. $oPage->add('<div class="wizContainer">');
  1090. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;">');
  1091. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  1092. $oPage->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  1093. $oPage->add('<p><input type="radio" name="separator" value="," onClick="DoPreview()"'.IsChecked($sSeparator, ',').'/> '.Dict::S('UI:CSVImport:SeparatorComma+').'<br/>');
  1094. $oPage->add('<input type="radio" name="separator" value=";" onClick="DoPreview()"'.IsChecked($sSeparator, ';').'/> '.Dict::S('UI:CSVImport:SeparatorSemicolon+').'<br/>');
  1095. $oPage->add('<input type="radio" name="separator" value="tab" onClick="DoPreview()"'.IsChecked($sSeparator, "\t").'/> '.Dict::S('UI:CSVImport:SeparatorTab+').'<br/>');
  1096. $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()"/>');
  1097. $oPage->add('</p>');
  1098. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;">');
  1099. $oPage->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  1100. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onClick="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> '.Dict::S('UI:CSVImport:QualifierDoubleQuote+').'<br/>');
  1101. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onClick="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> '.Dict::S('UI:CSVImport:QualifierSimpleQuote+').'<br/>');
  1102. $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()"/>');
  1103. $oPage->add('</p>');
  1104. $oPage->add('</td><td style="vertical-align:top;">');
  1105. $oPage->add('<h3>'.Dict::S('UI:CSVImport:CommentsAndHeader').'</h3>');
  1106. $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>');
  1107. $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>');
  1108. $oPage->add('</td></tr></table>');
  1109. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  1110. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sUTF8Data, ENT_QUOTES, 'UTF-8').'"/>');
  1111. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  1112. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  1113. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  1114. $oPage->add('<input type="hidden" name="step" value="3"/>');
  1115. if (!empty($sSynchroScope))
  1116. {
  1117. foreach($aSynchroUpdate as $sKey => $value)
  1118. {
  1119. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  1120. }
  1121. }
  1122. $oPage->add('<div id="preview">');
  1123. $oPage->add('<p style="text-align:center">'.Dict::S('UI:CSVImport:CSVDataPreview').'</p>');
  1124. $oPage->add('</div>');
  1125. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="GoBack()"/>');
  1126. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Next').'"/>');
  1127. $oPage->add('</form>');
  1128. $oPage->add('</div>');
  1129. $oPage->add_script(
  1130. <<<EOF
  1131. function GoBack()
  1132. {
  1133. $('input[name=step]').val(1);
  1134. $('#wizForm').submit();
  1135. }
  1136. var ajax_request = null;
  1137. function DoPreview()
  1138. {
  1139. var separator = $('input[name=separator]:checked').val();
  1140. if (separator == 'other')
  1141. {
  1142. separator = $('#other_separator').val();
  1143. }
  1144. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  1145. if (text_qualifier == 'other')
  1146. {
  1147. text_qualifier = $('#other_qualifier').val();
  1148. }
  1149. var nb_lines_skipped = 0;
  1150. if ($('#box_skiplines:checked').val() != null)
  1151. {
  1152. nb_lines_skipped = $('#nb_skipped_lines').val();
  1153. }
  1154. var header_line = 0;
  1155. if ($('#box_header:checked').val() != null)
  1156. {
  1157. header_line = 1;
  1158. }
  1159. var encoding = $('input[name=encoding]').val();
  1160. $('#preview').block();
  1161. // Make sure that we cancel any pending request before issuing another
  1162. // since responses may arrive in arbitrary order
  1163. if (ajax_request != null)
  1164. {
  1165. ajax_request.abort();
  1166. ajax_request = null;
  1167. }
  1168. ajax_request = $.post('ajax.csvimport.php',
  1169. { 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 },
  1170. function(data) {
  1171. $('#preview').empty();
  1172. $('#preview').append(data);
  1173. $('#preview').unblock();
  1174. }
  1175. );
  1176. }
  1177. EOF
  1178. );
  1179. $oPage->add_ready_script('DoPreview();');
  1180. }
  1181. /**
  1182. * Prompt for the data to be loaded (either via a file or a copy/paste)
  1183. * @param WebPage $oPage The current web page
  1184. * @return void
  1185. */
  1186. function Welcome(iTopWebPage $oPage)
  1187. {
  1188. // Encodings supported:
  1189. // ICONV_CODE => Display Name
  1190. // Each iconv installation supports different encodings
  1191. // Some reasonably common and useful encodnings are listed here
  1192. $aPossibleEncodings = array(
  1193. 'UTF-8' => 'Unicode (UTF-8)',
  1194. 'ISO-8859-1' => 'Western (ISO-8859-1)',
  1195. 'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
  1196. 'WINDOWS-1252' => 'Western (Windows 1252)',
  1197. 'ISO-8859-15' => 'Western (ISO-8859-15)',
  1198. );
  1199. // Some more encodings can be specified in the config file
  1200. $aExtraCharsets = MetaModel::GetConfig()->GetCSVImportCharsets();
  1201. $aPossibleEncodings = array_merge($aPossibleEncodings, $aExtraCharsets);
  1202. asort($aPossibleEncodings);
  1203. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  1204. if (!empty($sSynchroScope))
  1205. {
  1206. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1207. $sClassName = $oSearch->GetClass();
  1208. $oSet = new DBObjectSet($oSearch);
  1209. $iCount = $oSet->Count();
  1210. DisplaySynchroBanner($oPage, $sClassName, $iCount);
  1211. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1212. }
  1213. else
  1214. {
  1215. $aSynchroUpdate = null;
  1216. }
  1217. $oPage->add("<div><p><h1>".Dict::S('UI:Title:BulkImport+')."</h1></p></div>\n");
  1218. $oPage->AddTabContainer('tabs1');
  1219. $sSeparator = utils::ReadParam('separator', '');
  1220. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  1221. $bHeaderLine = utils::ReadParam('header_line', true);
  1222. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  1223. $sClassName = utils::ReadParam('class_name', '');
  1224. $bAdvanced = utils::ReadParam('advanced', 0);
  1225. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  1226. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:SelectFile').'</p>'.
  1227. '<p><input type="file" name="csvdata"/></p>';
  1228. $sFileLoadHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1229. $sFileLoadHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE 8 has some troubles if the font is different
  1230. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1231. {
  1232. $sSelected = '';
  1233. if ($sEncoding == $sIconvCode)
  1234. {
  1235. $sSelected = ' selected';
  1236. }
  1237. $sFileLoadHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1238. }
  1239. $sFileLoadHtml .= '</select></p>';
  1240. $sFileLoadHtml .= '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1241. '<input type="hidden" name="step" value="2"/>'.
  1242. '<input type="hidden" name="operation" value="file_upload"/>'.
  1243. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1244. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  1245. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1246. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1247. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1248. if (!empty($sSynchroScope))
  1249. {
  1250. foreach($aSynchroUpdate as $sKey => $value)
  1251. {
  1252. $sFileLoadHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1253. }
  1254. }
  1255. $sFileLoadHtml .= '</form></div>';
  1256. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:LoadFromFile'), $sFileLoadHtml);
  1257. $sCSVData = utils::ReadParam('csvdata', '');
  1258. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:PasteData').'</p>'.
  1259. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>';
  1260. $sPasteDataHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1261. $sPasteDataHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE8 has some troubles if the font is different
  1262. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1263. {
  1264. $sSelected = '';
  1265. if ($sEncoding == $sIconvCode)
  1266. {
  1267. $sSelected = ' selected';
  1268. }
  1269. $sPasteDataHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1270. }
  1271. $sPasteDataHtml .= '</select></p>'.
  1272. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1273. '<input type="hidden" name="step" value="2"/>'.
  1274. '<input type="hidden" name="operation" value="csv_data"/>'.
  1275. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  1276. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  1277. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1278. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  1279. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1280. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1281. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1282. if (!empty($sSynchroScope))
  1283. {
  1284. foreach($aSynchroUpdate as $sKey => $value)
  1285. {
  1286. $sPasteDataHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1287. }
  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('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. $oPage->SetCurrentTabContainer('tabs1');
  1333. $oPage->SetCurrentTab(Dict::S('UI:History:BulkImports'));
  1334. BulkChange::DisplayImportHistory($oPage);
  1335. }
  1336. switch($iStep)
  1337. {
  1338. case 10:
  1339. $iChange = (int)utils::ReadParam('changeid', 0);
  1340. BulkChange::DisplayImportHistoryDetails($oPage, $iChange);
  1341. break;
  1342. case 5:
  1343. LoadData($oPage);
  1344. break;
  1345. case 4:
  1346. Preview($oPage);
  1347. break;
  1348. case 3:
  1349. SelectMapping($oPage);
  1350. break;
  1351. case 2:
  1352. SelectOptions($oPage);
  1353. break;
  1354. case 1:
  1355. case 6: // Loop back here when we are done
  1356. default:
  1357. Welcome($oPage);
  1358. }
  1359. $oPage->output();
  1360. }
  1361. catch(CoreException $e)
  1362. {
  1363. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1364. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1365. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1366. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1367. $oP->output();
  1368. if (MetaModel::IsLogEnabledIssue())
  1369. {
  1370. if (MetaModel::IsValidClass('EventIssue'))
  1371. {
  1372. $oLog = new EventIssue();
  1373. $oLog->Set('message', $e->getMessage());
  1374. $oLog->Set('userinfo', '');
  1375. $oLog->Set('issue', $e->GetIssue());
  1376. $oLog->Set('impact', 'Page could not be displayed');
  1377. $oLog->Set('callstack', $e->getTrace());
  1378. $oLog->Set('data', $e->getContextData());
  1379. $oLog->DBInsertNoReload();
  1380. }
  1381. IssueLog::Error($e->getMessage());
  1382. }
  1383. // For debugging only
  1384. //throw $e;
  1385. }
  1386. catch(Exception $e)
  1387. {
  1388. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1389. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1390. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1391. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1392. $oP->output();
  1393. if (MetaModel::IsLogEnabledIssue())
  1394. {
  1395. if (MetaModel::IsValidClass('EventIssue'))
  1396. {
  1397. $oLog = new EventIssue();
  1398. $oLog->Set('message', $e->getMessage());
  1399. $oLog->Set('userinfo', '');
  1400. $oLog->Set('issue', 'PHP Exception');
  1401. $oLog->Set('impact', 'Page could not be displayed');
  1402. $oLog->Set('callstack', $e->getTrace());
  1403. $oLog->Set('data', array());
  1404. $oLog->DBInsertNoReload();
  1405. }
  1406. IssueLog::Error($e->getMessage());
  1407. }
  1408. }
  1409. ?>