csvimport.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  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. $sHtml .= '</table>';
  490. $oPage->add('<div class="wizContainer">');
  491. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post">');
  492. $oPage->add('<input type="hidden" name="step" value="'.($iCurrentStep+1).'"/>');
  493. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  494. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  495. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  496. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  497. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  498. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  499. $oPage->add('<input type="hidden" name="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  500. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  501. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  502. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'"/>');
  503. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  504. if (!empty($sSynchroScope))
  505. {
  506. foreach($aSynchroUpdate as $sKey => $value)
  507. {
  508. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  509. }
  510. }
  511. foreach($aFieldsMapping as $iNumber => $sAttCode)
  512. {
  513. $oPage->add('<input type="hidden" name="field['.$iNumber.']" value="'.$sAttCode.'"/>');
  514. }
  515. foreach($aSearchFields as $index => $sDummy)
  516. {
  517. $oPage->add('<input type="hidden" name="search_field['.$index.']" value="1"/>');
  518. }
  519. $aFieldsMapping = utils::ReadParam('field', array());
  520. $aSearchFields = utils::ReadParam('search_field', array());
  521. $aDisplayFilters = array();
  522. if ($bSimulate)
  523. {
  524. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsWillStayUnchanged');
  525. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWillBeModified');
  526. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWillBeAdded');
  527. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsWillHaveErrors');
  528. }
  529. else
  530. {
  531. $aDisplayFilters['unchanged'] = Dict::S('UI:CSVImport:ObjectsRemainedUnchanged');
  532. $aDisplayFilters['modified'] = Dict::S('UI:CSVImport:ObjectsWereModified');
  533. $aDisplayFilters['added'] = Dict::S('UI:CSVImport:ObjectsWereAdded');
  534. $aDisplayFilters['errors'] = Dict::S('UI:CSVImport:ObjectsHadErrors');
  535. }
  536. $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;');
  537. $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;');
  538. $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;');
  539. $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>');
  540. $oPage->add('<div style="overflow-y:auto" class="white">');
  541. $oPage->add($sHtml);
  542. $oPage->add('</div> <!-- end of preview -->');
  543. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  544. if ($bSimulate)
  545. {
  546. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:DoImport').'" onClick="$(\'#wizForm\').block();"/></p>');
  547. }
  548. else
  549. {
  550. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Done').'"/></p>');
  551. }
  552. $oPage->add('</form>');
  553. $oPage->add('</div> <!-- end of wizForm -->');
  554. $oPage->add_script(
  555. <<< EOF
  556. function CSVGoBack()
  557. {
  558. $('input[name=step]').val($iCurrentStep-1);
  559. $('#wizForm').submit();
  560. }
  561. function ToggleRows(sCSSClass)
  562. {
  563. $('.'+sCSSClass).toggle();
  564. }
  565. EOF
  566. );
  567. if ($iErrors > 0)
  568. {
  569. return $aResult;
  570. }
  571. else
  572. {
  573. return null;
  574. }
  575. }
  576. /**
  577. * Perform the actual load of the CSV data and display the results
  578. * @param WebPage $oPage The web page to display the wizard
  579. * @return void
  580. */
  581. function LoadData(WebPage $oPage)
  582. {
  583. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep5').'</h2>');
  584. $aResult = ProcessCSVData($oPage, false /* simulate = false */);
  585. if (is_array($aResult))
  586. {
  587. $oPage->StartCollapsibleSection(Dict::S('UI:CSVImport:LinesNotImported'), false);
  588. $oPage->p(Dict::S('UI:CSVImport:LinesNotImported+'));
  589. $oPage->add('<textarea rows="30" cols="100">');
  590. $oPage->add(htmlentities(implode("\n", $aResult), ENT_QUOTES, 'UTF-8'));
  591. $oPage->add('</textarea>');
  592. $oPage->EndCollapsibleSection();
  593. }
  594. }
  595. /**
  596. * Simulate the load of the CSV data and display the results
  597. * @param WebPage $oPage The web page to display the wizard
  598. * @return void
  599. */
  600. function Preview(WebPage $oPage)
  601. {
  602. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep4').'</h2>');
  603. ProcessCSVData($oPage, true /* simulate */);
  604. }
  605. /**
  606. * Select the mapping between the CSV column and the fields of the objects
  607. * @param WebPage $oPage The web page to display the wizard
  608. * @return void
  609. */
  610. function SelectMapping(WebPage $oPage)
  611. {
  612. $sCSVData = utils::ReadParam('csvdata', '');
  613. $sCSVDataTruncated = utils::ReadParam('csvdata_truncated', '');;
  614. $sSeparator = utils::ReadParam('separator', ',');
  615. if ($sSeparator == 'tab') $sSeparator = "\t";
  616. if ($sSeparator == 'other')
  617. {
  618. $sSeparator = utils::ReadParam('other_separator', ',');
  619. }
  620. $sTextQualifier = utils::ReadParam('text_qualifier', '"');
  621. if ($sTextQualifier == 'other')
  622. {
  623. $sTextQualifier = utils::ReadParam('other_qualifier', '"');
  624. }
  625. $bHeaderLine = (utils::ReadParam('header_line', '0') == 1);
  626. $iSkippedLines = 0;
  627. if (utils::ReadParam('box_skiplines', '0') == 1)
  628. {
  629. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '0');
  630. }
  631. $sClassName = utils::ReadParam('class_name', '');
  632. $bAdvanced = utils::ReadParam('advanced', 0);
  633. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  634. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  635. if (!empty($sSynchroScope))
  636. {
  637. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  638. $sClassName = $oSearch->GetClass(); // If a synchronization scope is set, then the class is fixed !
  639. $oSet = new DBObjectSet($oSearch);
  640. $iCount = $oSet->Count();
  641. $sSynchroClass = 'Server';
  642. DisplaySynchroBanner($oPage, $sSynchroClass, $iCount);
  643. $sClassesSelect = "<select id=\"select_class_name\" name=\"class_name\"><option value=\"$sClassName\" selected>".MetaModel::GetName($sClassName)."</option>";
  644. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  645. }
  646. else
  647. {
  648. $sClassesSelect = GetClassesSelect('class_name', $sClassName, 300, UR_ACTION_BULK_MODIFY);
  649. }
  650. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep3').'</h2>');
  651. $oPage->add('<div class="wizContainer">');
  652. $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').' ');
  653. $oPage->add($sClassesSelect);
  654. $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>');
  655. $oPage->add('<div style="padding:1em;display:none" id="advanced_help" style="display:none">'.Dict::S('UI:CSVImport:AdvancedMode+').'</div>');
  656. $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>');
  657. $oPage->add('<input type="hidden" name="step" value="4"/>');
  658. $oPage->add('<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>');
  659. $oPage->add('<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>');
  660. $oPage->add('<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>');
  661. $oPage->add('<input type="hidden" name="box_skiplines" value="'.(($iSkippedLines > 0) ? 1 : 0).'"/>');
  662. $oPage->add('<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>');
  663. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  664. $oPage->add('<input type="hidden" name="csvdata" value="'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'"/>');
  665. $oPage->add('<input type="hidden" name="encoding" value="'.$sEncoding.'">');
  666. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'">');
  667. if (!empty($sSynchroScope))
  668. {
  669. foreach($aSynchroUpdate as $sKey => $value)
  670. {
  671. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  672. }
  673. }
  674. $oPage->add('<p><input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="CSVGoBack()"/>&nbsp;&nbsp;');
  675. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:SimulateImport').'"/></p>');
  676. $oPage->add('</form>');
  677. $oPage->add('</div>');
  678. $sAlertIncompleteMapping = Dict::S('UI:CSVImport:AlertIncompleteMapping');
  679. $sAlertNoSearchCriteria = Dict::S('UI:CSVImport:AlertNoSearchCriteria');
  680. $oPage->add_ready_script(
  681. <<<EOF
  682. $('#select_class_name').change( DoMapping );
  683. EOF
  684. );
  685. if ($sClassName != '')
  686. {
  687. $oPage->add_ready_script("DoMapping();"); // There is already a class selected, run the mapping
  688. }
  689. $oPage->add_script(
  690. <<<EOF
  691. var aDefaultKeys = new Array();
  692. function CSVGoBack()
  693. {
  694. $('input[name=step]').val(2);
  695. $('#wizForm').removeAttr('onsubmit'); // No need to perform validation checks when going back
  696. $('#wizForm').submit();
  697. }
  698. var ajax_request = null;
  699. function DoMapping()
  700. {
  701. var class_name = $('select[name=class_name]').val();
  702. var advanced = $('input[name=advanced]:checked').val();
  703. if (advanced != 1)
  704. {
  705. $('#advanced_help').hide();
  706. }
  707. else
  708. {
  709. $('#advanced_help').show();
  710. }
  711. if (class_name != '')
  712. {
  713. var separator = $('input[name=separator]').val();
  714. var text_qualifier = $('input[name=text_qualifier]').val();
  715. var header_line = $('input[name=header_line]').val();
  716. var nb_lines_skipped = $('input[name=nb_skipped_lines]').val();
  717. var csv_data = $('input[name=csvdata]').val();
  718. var encoding = $('input[name=encoding]').val();
  719. if (advanced != 1)
  720. {
  721. advanced = 0;
  722. }
  723. $('#mapping').block();
  724. // Make sure that we cancel any pending request before issuing another
  725. // since responses may arrive in arbitrary order
  726. if (ajax_request != null)
  727. {
  728. ajax_request.abort();
  729. ajax_request = null;
  730. }
  731. ajax_request = $.post('ajax.csvimport.php',
  732. { operation: 'display_mapping_form', enctype: 'multipart/form-data', csvdata: csv_data, separator: separator,
  733. qualifier: text_qualifier, nb_lines_skipped: nb_lines_skipped, header_line: header_line, class_name: class_name,
  734. advanced: advanced, encoding: encoding },
  735. function(data) {
  736. $('#mapping').empty();
  737. $('#mapping').append(data);
  738. $('#mapping').unblock();
  739. }
  740. );
  741. }
  742. }
  743. function CheckValues()
  744. {
  745. bResult = true;
  746. bMappingOk = true;
  747. bSearchOk = false;
  748. $('select[name^=field]').each( function() {
  749. if ($(this).val() == '')
  750. {
  751. $(this).parent().css({'border': '2px #D81515 solid'});
  752. bMappingOk = false;
  753. bResult = false;
  754. }
  755. else
  756. {
  757. $(this).parent().css({'border': '0'});
  758. }
  759. });
  760. // At least one search field must be checked
  761. $('input[name^=search]:checked').each( function() {
  762. bSearchOk = true;
  763. });
  764. if (!bMappingOk)
  765. {
  766. alert("$sAlertIncompleteMapping");
  767. }
  768. if (!bSearchOk)
  769. {
  770. bResult = false;
  771. alert("$sAlertNoSearchCriteria");
  772. }
  773. if (bResult)
  774. {
  775. $('#mapping').block();
  776. // Re-enable all search_xxx checkboxes so that their value gets posted
  777. $('input[name^=search]').each(function() {
  778. $(this).attr('disabled', false);
  779. });
  780. }
  781. return bResult;
  782. }
  783. function DoCheckMapping()
  784. {
  785. // Check if there is a field mapped to 'id'
  786. // In which case, it's the only possible search key
  787. var idSelected = 0;
  788. var nbSearchKeys = $('input[name^=search]:checked').length;
  789. var nbMappings = $('select[name^=field]').length;
  790. for(index=1; index <= nbMappings; index++)
  791. {
  792. var selectedValue = $('#mapping_'+index).val();
  793. if (selectedValue == 'id')
  794. {
  795. idSelected = index;
  796. }
  797. }
  798. for (index=1; index <= nbMappings; index++)
  799. {
  800. sMappingValue = $('#mapping_'+index).val();
  801. if ((sMappingValue == '') || (sMappingValue == ':none:'))
  802. {
  803. // Non-mapped field, uncheck and disabled
  804. $('#search_'+index).attr('checked', false);
  805. $('#search_'+index).attr('disabled', true);
  806. }
  807. else if (index == idSelected)
  808. {
  809. // The 'id' field was mapped, it's the only possible reconciliation key
  810. $('#search_'+index).attr('checked', true);
  811. $('#search_'+index).attr('disabled', true);
  812. }
  813. else
  814. {
  815. if (idSelected > 0)
  816. {
  817. // The 'id' field was mapped, it's the only possible reconciliation key
  818. $('#search_'+index).attr('checked', false);
  819. $('#search_'+index).attr('disabled', true);
  820. }
  821. else
  822. {
  823. $('#search_'+index).attr('disabled', false);
  824. if (nbSearchKeys == 0)
  825. {
  826. // No search key was selected, select the default ones
  827. for(j =0; j < aDefaultKeys.length; j++)
  828. {
  829. if (sMappingValue == aDefaultKeys[j])
  830. {
  831. $('#search_'+index).attr('checked', true);
  832. }
  833. }
  834. }
  835. }
  836. }
  837. }
  838. }
  839. EOF
  840. );
  841. }
  842. /**
  843. * Select the options of the CSV load and check for CSV parsing errors
  844. * @param WebPage $oPage The current web page
  845. * @return void
  846. */
  847. function SelectOptions(WebPage $oPage)
  848. {
  849. $sOperation = utils::ReadParam('operation', 'csv_data');
  850. $sCSVData = '';
  851. switch($sOperation)
  852. {
  853. case 'file_upload':
  854. $oDocument = utils::ReadPostedDocument('csvdata');
  855. if (!$oDocument->IsEmpty())
  856. {
  857. $sCSVData = $oDocument->GetData();
  858. }
  859. break;
  860. default:
  861. $sCSVData = utils::ReadPostedParam('csvdata', '');
  862. }
  863. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  864. // Compute a subset of the data set, now that we know the charset
  865. if ($sEncoding == 'UTF-8')
  866. {
  867. $sUTF8Data = iconv('UTF-8', 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  868. }
  869. else
  870. {
  871. $sUTF8Data = iconv($sEncoding, 'UTF-8//IGNORE//TRANSLIT', $sCSVData);
  872. }
  873. $aGuesses = GuessParameters($sUTF8Data); // Try to predict the parameters, based on the input data
  874. $sSeparator = utils::ReadParam('separator', '');
  875. if ($sSeparator == '') // May be set to an empty value by the previous page
  876. {
  877. $sSeparator = $aGuesses['separator'];
  878. }
  879. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  880. $bBoxSkipLines = utils::ReadParam('box_skiplines', 0);
  881. if ($sSeparator == 'tab') $sSeparator = "\t";
  882. $sOtherSeparator = in_array($sSeparator, array(',', ';', "\t")) ? '' : $sSeparator;
  883. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  884. if ($sTextQualifier == '') // May be set to an empty value by the previous page
  885. {
  886. $sTextQualifier = $aGuesses['qualifier'];
  887. }
  888. $sOtherTextQualifier = in_array($sTextQualifier, array('"', "'")) ? '' : $sTextQualifier;
  889. $bHeaderLine = utils::ReadParam('header_line', 0);
  890. $sClassName = utils::ReadParam('class_name', '');
  891. $bAdvanced = utils::ReadParam('advanced', 0);
  892. // Create a truncated version of the data used for the fast preview
  893. // Take about 20 lines of data... knowing that some lines may contain carriage returns
  894. $iMaxLines = 20;
  895. $iMaxLen = strlen($sUTF8Data);
  896. $iCurPos = true;
  897. while ( ($iCurPos > 0) && ($iMaxLines > 0))
  898. {
  899. $pos = strpos($sUTF8Data, "\n", $iCurPos);
  900. if ($pos !== false)
  901. {
  902. $iCurPos = 1+$pos;
  903. }
  904. else
  905. {
  906. $iCurPos = strlen($sUTF8Data);
  907. $iMaxLines = 1;
  908. }
  909. $iMaxLines--;
  910. }
  911. $sCSVDataTruncated = substr($sUTF8Data, 0, $iCurPos);
  912. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  913. if (!empty($sSynchroScope))
  914. {
  915. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  916. $sSynchroClass = $oSearch->GetClass();
  917. $oSet = new DBObjectSet($oSearch);
  918. $iCount = $oSet->Count();
  919. $sSynchroClass = 'Server';
  920. DisplaySynchroBanner($oPage, $sSynchroClass, $iCount);
  921. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  922. }
  923. $oPage->add('<h2>'.Dict::S('UI:Title:CSVImportStep2').'</h2>');
  924. $oPage->add('<div class="wizContainer">');
  925. $oPage->add('<table><tr><td style="vertical-align:top;padding-right:50px;">');
  926. $oPage->add('<form enctype="multipart/form-data" id="wizForm" method="post" id="csv_options">');
  927. $oPage->add('<h3>'.Dict::S('UI:CSVImport:SeparatorCharacter').'</h3>');
  928. $oPage->add('<p><input type="radio" name="separator" value="," onClick="DoPreview()"'.IsChecked($sSeparator, ',').'/> '.Dict::S('UI:CSVImport:SeparatorComma+').'<br/>');
  929. $oPage->add('<input type="radio" name="separator" value=";" onClick="DoPreview()"'.IsChecked($sSeparator, ';').'/> '.Dict::S('UI:CSVImport:SeparatorSemicolon+').'<br/>');
  930. $oPage->add('<input type="radio" name="separator" value="tab" onClick="DoPreview()"'.IsChecked($sSeparator, "\t").'/> '.Dict::S('UI:CSVImport:SeparatorTab+').'<br/>');
  931. $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()"/>');
  932. $oPage->add('</p>');
  933. $oPage->add('</td><td style="vertical-align:top;padding-right:50px;">');
  934. $oPage->add('<h3>'.Dict::S('UI:CSVImport:TextQualifierCharacter').'</h3>');
  935. $oPage->add('<p><input type="radio" name="text_qualifier" value="&#34;" onClick="DoPreview()"'.IsChecked($sTextQualifier, '"').'/> '.Dict::S('UI:CSVImport:QualifierDoubleQuote+').'<br/>');
  936. $oPage->add('<input type="radio" name="text_qualifier" value="&#39;" onClick="DoPreview()"'.IsChecked($sTextQualifier, "'").'/> '.Dict::S('UI:CSVImport:QualifierSimpleQuote+').'<br/>');
  937. $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()"/>');
  938. $oPage->add('</p>');
  939. $oPage->add('</td><td style="vertical-align:top;">');
  940. $oPage->add('<h3>'.Dict::S('UI:CSVImport:CommentsAndHeader').'</h3>');
  941. $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>');
  942. $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>');
  943. $oPage->add('</td></tr></table>');
  944. $oPage->add('<input type="hidden" name="csvdata_truncated" id="csvdata_truncated" value="'.htmlentities($sCSVDataTruncated, ENT_QUOTES, 'UTF-8').'"/>');
  945. $oPage->add('<input type="hidden" name="csvdata" id="csvdata" value="'.htmlentities($sUTF8Data, ENT_QUOTES, 'UTF-8').'"/>');
  946. $oPage->add('<input type="hidden" name="class_name" value="'.$sClassName.'"/>');
  947. $oPage->add('<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>');
  948. $oPage->add('<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>');
  949. $oPage->add('<input type="hidden" name="step" value="3"/>');
  950. if (!empty($sSynchroScope))
  951. {
  952. foreach($aSynchroUpdate as $sKey => $value)
  953. {
  954. $oPage->add('<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>');
  955. }
  956. }
  957. $oPage->add('<div id="preview">');
  958. $oPage->add('<p style="text-align:center">'.Dict::S('UI:CSVImport:CSVDataPreview').'</p>');
  959. $oPage->add('</div>');
  960. $oPage->add('<input type="button" value="'.Dict::S('UI:Button:Back').'" onClick="GoBack()"/>');
  961. $oPage->add('<input type="submit" value="'.Dict::S('UI:Button:Next').'"/>');
  962. $oPage->add('</form>');
  963. $oPage->add('</div>');
  964. $oPage->add_script(
  965. <<<EOF
  966. function GoBack()
  967. {
  968. $('input[name=step]').val(1);
  969. $('#wizForm').submit();
  970. }
  971. var ajax_request = null;
  972. function DoPreview()
  973. {
  974. var separator = $('input[name=separator]:checked').val();
  975. if (separator == 'other')
  976. {
  977. separator = $('#other_separator').val();
  978. }
  979. var text_qualifier = $('input[name=text_qualifier]:checked').val();
  980. if (text_qualifier == 'other')
  981. {
  982. text_qualifier = $('#other_qualifier').val();
  983. }
  984. var nb_lines_skipped = 0;
  985. if ($('#box_skiplines:checked').val() != null)
  986. {
  987. nb_lines_skipped = $('#nb_skipped_lines').val();
  988. }
  989. var header_line = 0;
  990. if ($('#box_header:checked').val() != null)
  991. {
  992. header_line = 1;
  993. }
  994. var encoding = $('input[name=encoding]').val();
  995. $('#preview').block();
  996. // Make sure that we cancel any pending request before issuing another
  997. // since responses may arrive in arbitrary order
  998. if (ajax_request != null)
  999. {
  1000. ajax_request.abort();
  1001. ajax_request = null;
  1002. }
  1003. ajax_request = $.post('ajax.csvimport.php',
  1004. { 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 },
  1005. function(data) {
  1006. $('#preview').empty();
  1007. $('#preview').append(data);
  1008. $('#preview').unblock();
  1009. }
  1010. );
  1011. }
  1012. EOF
  1013. );
  1014. $oPage->add_ready_script('DoPreview();');
  1015. }
  1016. /**
  1017. * Prompt for the data to be loaded (either via a file or a copy/paste)
  1018. * @param WebPage $oPage The current web page
  1019. * @return void
  1020. */
  1021. function Welcome(iTopWebPage $oPage)
  1022. {
  1023. // Encodings supported:
  1024. // ICONV_CODE => Display Name
  1025. // Each iconv installation supports different encodings
  1026. // Some reasonably common and useful encodnings are listed here
  1027. $aPossibleEncodings = array(
  1028. 'UTF-8' => 'Unicode (UTF-8)',
  1029. 'ISO-8859-1' => 'Western (ISO-8859-1)',
  1030. 'WINDOWS-1251' => 'Cyrilic (Windows 1251)',
  1031. 'WINDOWS-1252' => 'Western (Windows 1252)',
  1032. 'ISO-8859-15' => 'Western (ISO-8859-15)',
  1033. );
  1034. // Some more encodings can be specified in the config file
  1035. $aExtraCharsets = utils::GetConfig()->GetCSVImportCharsets();
  1036. $aPossibleEncodings = array_merge($aPossibleEncodings, $aExtraCharsets);
  1037. asort($aPossibleEncodings);
  1038. $sSynchroScope = utils::ReadParam('synchro_scope', '');
  1039. if (!empty($sSynchroScope))
  1040. {
  1041. $oSearch = DBObjectSearch::FromOQL($sSynchroScope);
  1042. $sSynchroClass = $oSearch->GetClass();
  1043. $oSet = new DBObjectSet($oSearch);
  1044. $iCount = $oSet->Count();
  1045. $sSynchroClass = 'Server';
  1046. DisplaySynchroBanner($oPage, $sSynchroClass, $iCount);
  1047. $aSynchroUpdate = utils::ReadParam('synchro_update', array());
  1048. }
  1049. else
  1050. {
  1051. $aSynchroUpdate = null;
  1052. }
  1053. $oPage->add("<div><p><h1>".Dict::S('UI:Title:BulkImport+')."</h1></p></div>\n");
  1054. $oPage->AddTabContainer('tabs1');
  1055. $sSeparator = utils::ReadParam('separator', '');
  1056. $sTextQualifier = utils::ReadParam('text_qualifier', '');
  1057. $bHeaderLine = utils::ReadParam('header_line', true);
  1058. $iSkippedLines = utils::ReadParam('nb_skipped_lines', '');
  1059. $sClassName = utils::ReadParam('class_name', '');
  1060. $bAdvanced = utils::ReadParam('advanced', 0);
  1061. $sEncoding = utils::ReadParam('encoding', 'UTF-8');
  1062. $sFileLoadHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:SelectFile').'</p>'.
  1063. '<p><input type="file" name="csvdata"/></p>';
  1064. $sFileLoadHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1065. $sFileLoadHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE 8 has some troubles if the font is different
  1066. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1067. {
  1068. $sSelected = '';
  1069. if ($sEncoding == $sIconvCode)
  1070. {
  1071. $sSelected = ' selected';
  1072. }
  1073. $sFileLoadHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1074. }
  1075. $sFileLoadHtml .= '</select></p>';
  1076. $sFileLoadHtml .= '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1077. '<input type="hidden" name="step" value="2"/>'.
  1078. '<input type="hidden" name="operation" value="file_upload"/>'.
  1079. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1080. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  1081. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1082. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1083. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1084. if (!empty($sSynchroScope))
  1085. {
  1086. foreach($aSynchroUpdate as $sKey => $value)
  1087. {
  1088. $sFileLoadHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1089. }
  1090. }
  1091. $sFileLoadHtml .= '</form></div>';
  1092. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:LoadFromFile'), $sFileLoadHtml);
  1093. $sCSVData = utils::ReadParam('csvdata', '');
  1094. $sPasteDataHtml = '<div><form enctype="multipart/form-data" method="post"><p>'.Dict::S('UI:CSVImport:PasteData').'</p>'.
  1095. '<p><textarea cols="100" rows="30" name="csvdata">'.htmlentities($sCSVData, ENT_QUOTES, 'UTF-8').'</textarea></p>';
  1096. $sPasteDataHtml .= '<p>'.Dict::S('UI:CSVImport:Encoding').': ';
  1097. $sPasteDataHtml .= '<select name="encoding" style="font-family:Arial,Helvetica,Sans-serif"/>'; // IE8 has some troubles if the font is different
  1098. foreach($aPossibleEncodings as $sIconvCode => $sDisplayName )
  1099. {
  1100. $sSelected = '';
  1101. if ($sEncoding == $sIconvCode)
  1102. {
  1103. $sSelected = ' selected';
  1104. }
  1105. $sPasteDataHtml .= '<option value="'.$sIconvCode.'"'.$sSelected.'>'.$sDisplayName.'</option>';
  1106. }
  1107. $sPasteDataHtml .= '</select></p>'.
  1108. '<p><input type="submit" value="'.Dict::S('UI:Button:Next').'"/></p>'.
  1109. '<input type="hidden" name="step" value="2"/>'.
  1110. '<input type="hidden" name="operation" value="csv_data"/>'.
  1111. '<input type="hidden" name="separator" value="'.htmlentities($sSeparator, ENT_QUOTES, 'UTF-8').'"/>'.
  1112. '<input type="hidden" name="text_qualifier" value="'.htmlentities($sTextQualifier, ENT_QUOTES, 'UTF-8').'"/>'.
  1113. '<input type="hidden" name="header_line" value="'.$bHeaderLine.'"/>'.
  1114. '<input type="hidden" name="nb_skipped_lines" value="'.$iSkippedLines.'"/>'.
  1115. '<input type="hidden" name="class_name" value="'.$sClassName.'"/>'.
  1116. '<input type="hidden" name="advanced" value="'.$bAdvanced.'"/>'.
  1117. '<input type="hidden" name="synchro_scope" value="'.$sSynchroScope.'"/>';
  1118. if (!empty($sSynchroScope))
  1119. {
  1120. foreach($aSynchroUpdate as $sKey => $value)
  1121. {
  1122. $sPasteDataHtml .= '<input type="hidden" name="synchro_update['.$sKey.']" value="'.$value.'"/>';
  1123. }
  1124. }
  1125. $sPasteDataHtml .= '</form></div>';
  1126. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'), $sPasteDataHtml);
  1127. if (!empty($sCSVData))
  1128. {
  1129. // When there are some data, activate the 'copy & paste' tab by default
  1130. $oPage->SelectTab('tabs1', Dict::S('UI:CSVImport:Tab:CopyPaste'));
  1131. }
  1132. $sTemplateHtml = '<div><p>'.Dict::S('UI:CSVImport:PickClassForTemplate').' ';
  1133. $sTemplateHtml .= GetClassesSelect('template_class', '', 300, UR_ACTION_BULK_MODIFY);
  1134. $sTemplateHtml .= '</div>';
  1135. $sTemplateHtml .= '<div id="template" style="text-align:center">';
  1136. $sTemplateHtml .= '</div>';
  1137. $oPage->AddToTab('tabs1', Dict::S('UI:CSVImport:Tab:Templates'), $sTemplateHtml);
  1138. $oPage->add_script(
  1139. <<<EOF
  1140. var ajax_request = null;
  1141. function DisplayTemplate(sClassName) {
  1142. $('#template').block();
  1143. // Make sure that we cancel any pending request before issuing another
  1144. // since responses may arrive in arbitrary order
  1145. if (ajax_request != null)
  1146. {
  1147. ajax_request.abort();
  1148. ajax_request = null;
  1149. }
  1150. ajax_request = $.post('ajax.csvimport.php',
  1151. { operation: 'get_csv_template', class_name: sClassName },
  1152. function(data) {
  1153. $('#template').empty();
  1154. $('#template').append(data);
  1155. $('#template').unblock();
  1156. }
  1157. );
  1158. }
  1159. EOF
  1160. );
  1161. $oPage->add_ready_script(
  1162. <<<EOF
  1163. $('#select_template_class').change( function() {
  1164. DisplayTemplate(this.value);
  1165. });
  1166. EOF
  1167. );
  1168. }
  1169. switch($iStep)
  1170. {
  1171. case 5:
  1172. LoadData($oPage);
  1173. break;
  1174. case 4:
  1175. Preview($oPage);
  1176. break;
  1177. case 3:
  1178. SelectMapping($oPage);
  1179. break;
  1180. case 2:
  1181. SelectOptions($oPage);
  1182. break;
  1183. case 1:
  1184. case 6: // Loop back here when we are done
  1185. default:
  1186. Welcome($oPage);
  1187. }
  1188. $oPage->output();
  1189. }
  1190. catch(CoreException $e)
  1191. {
  1192. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1193. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1194. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1195. $oP->error(Dict::Format('UI:Error_Details', $e->getHtmlDesc()));
  1196. $oP->output();
  1197. if (MetaModel::IsLogEnabledIssue())
  1198. {
  1199. if (MetaModel::IsValidClass('EventIssue'))
  1200. {
  1201. $oLog = new EventIssue();
  1202. $oLog->Set('message', $e->getMessage());
  1203. $oLog->Set('userinfo', '');
  1204. $oLog->Set('issue', $e->GetIssue());
  1205. $oLog->Set('impact', 'Page could not be displayed');
  1206. $oLog->Set('callstack', $e->getTrace());
  1207. $oLog->Set('data', $e->getContextData());
  1208. $oLog->DBInsertNoReload();
  1209. }
  1210. IssueLog::Error($e->getMessage());
  1211. }
  1212. // For debugging only
  1213. //throw $e;
  1214. }
  1215. catch(Exception $e)
  1216. {
  1217. require_once(APPROOT.'/setup/setuppage.class.inc.php');
  1218. $oP = new SetupWebPage(Dict::S('UI:PageTitle:FatalError'));
  1219. $oP->add("<h1>".Dict::S('UI:FatalErrorMessage')."</h1>\n");
  1220. $oP->error(Dict::Format('UI:Error_Details', $e->getMessage()));
  1221. $oP->output();
  1222. if (MetaModel::IsLogEnabledIssue())
  1223. {
  1224. if (MetaModel::IsValidClass('EventIssue'))
  1225. {
  1226. $oLog = new EventIssue();
  1227. $oLog->Set('message', $e->getMessage());
  1228. $oLog->Set('userinfo', '');
  1229. $oLog->Set('issue', 'PHP Exception');
  1230. $oLog->Set('impact', 'Page could not be displayed');
  1231. $oLog->Set('callstack', $e->getTrace());
  1232. $oLog->Set('data', array());
  1233. $oLog->DBInsertNoReload();
  1234. }
  1235. IssueLog::Error($e->getMessage());
  1236. }
  1237. }
  1238. ?>