csvimport.php 52 KB

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