FOSSology  4.6.0
Open Source License Compliance by Open Source Software
fossinit.php
Go to the documentation of this file.
1 #!/usr/bin/php
2 <?php
3 /*
4  SPDX-FileCopyrightText: © 2008-2015 Hewlett-Packard Development Company, L.P.
5  SPDX-FileCopyrightText: © 2014-2015, 2019 Siemens AG
6 
7  SPDX-License-Identifier: GPL-2.0-only
8 */
9 
13 function explainUsage()
14 {
15  global $argv;
16 
17  $usage = "Usage: " . basename($argv[0]) . " [options]
18  Update FOSSology database. This should be used immediately after an install or update. Options are:
19  -c path to fossology configuration files
20  -d {database name} default is 'fossology'
21  -f {file} update the schema with file generated by schema-export.php
22  -l update the license_ref table with fossology supplied licenses
23  -r {prefix} drop database with name starts with prefix
24  -v enable verbose preview (prints sql that would happen, but does not execute it, DB is not updated)
25  --force-decision force recalculation of SHA256 for decision tables
26  --force-pfile force recalculation of SHA256 for pfile entries
27  --force-encode force recode of copyright and sister tables
28  -h this help usage";
29  print "$usage\n";
30  exit(0);
31 }
32 
33 
43 
44 /* Note: php 5 getopt() ignores options not specified in the function call, so add
45  * dummy options in order to catch invalid options.
46  */
47 $AllPossibleOpts = "abc:d:ef:ghijklmnopqr:stuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
48 $longOpts = [
49  "force-decision",
50  "force-pfile",
51  "force-encode"
52 ];
53 
54 /* defaults */
55 $Verbose = false;
56 $DatabaseName = "fossology";
57 $UpdateLiceneseRef = false;
58 $sysconfdir = '';
59 $delDbPattern = 'the option -rfosstest will drop data bases with datname like "fosstest%"';
60 $forceDecision = false;
61 $forcePfile = false;
62 
63 /* command-line options */
64 $Options = getopt($AllPossibleOpts, $longOpts);
65 foreach($Options as $optKey => $optVal)
66 {
67  switch($optKey)
68  {
69  case 'c': /* set SYSCONFIDR */
70  $sysconfdir = $optVal;
71  break;
72  case 'd': /* optional database name */
73  $DatabaseName = $optVal;
74  break;
75  case 'f': /* schema file */
76  $SchemaFilePath = $optVal;
77  break;
78  case 'h': /* help */
79  explainUsage();
80  case 'l': /* update the license_ref table */
81  $UpdateLiceneseRef = true;
82  break;
83  case 'v': /* verbose */
84  $Verbose = true;
85  break;
86  case 'r':
87  $delDbPattern = $optVal ? "$optVal%" : "fosstest%";
88  break;
89  case "force-decision":
90  $forceDecision = true;
91  break;
92  case "force-pfile":
93  $forcePfile = true;
94  break;
95  case "force-encode":
96  putenv('FOSSENCODING=1');
97  break;
98  default:
99  echo "Invalid Option \"$optKey\".\n";
100  explainUsage();
101  }
102 }
103 
104 require_once 'fossinit-common.php';
105 
106 /* Set SYSCONFDIR and set global (for backward compatibility) */
107 $SysConf = bootstrap($sysconfdir);
108 $SysConf["DBCONF"]["dbname"] = $DatabaseName;
109 $GLOBALS["SysConf"] = array_merge($GLOBALS["SysConf"], $SysConf);
110 $projectGroup = $SysConf['DIRECTORIES']['PROJECTGROUP'] ?: 'fossy';
111 $gInfo = posix_getgrnam($projectGroup);
112 posix_setgid($gInfo['gid']);
113 $groups = `groups`;
114 if (!preg_match("/\s$projectGroup\s/",$groups) && (posix_getgid() != $gInfo['gid']))
115 {
116  print "FATAL: You must be in group '$projectGroup'.\n";
117  exit(1);
118 }
119 
120 require_once("$MODDIR/vendor/autoload.php");
121 require_once("$MODDIR/lib/php/common-db.php");
122 require_once("$MODDIR/lib/php/common-container.php");
123 require_once("$MODDIR/lib/php/common-cache.php");
124 require_once("$MODDIR/lib/php/common-sysconfig.php");
125 require_once("$MODDIR/lib/php/fossdash-config.php");
126 
127 /* Initialize global system configuration variables $SysConfig[] */
128 $GLOBALS["PG_CONN"] = get_pg_conn($SYSCONFDIR, $SysConf);
129 
130 /* Initialize fossdash configuration variables */
131 FossdashConfigInit($SYSCONFDIR, $SysConf);
132 
140 if (empty($SchemaFilePath)) {
141  $SchemaFilePath = "$MODDIR/www/ui/core-schema.dat";
142 }
143 
144 if (!file_exists($SchemaFilePath))
145 {
146  print "FAILED: Schema data file ($SchemaFilePath) not found.\n";
147  exit(1);
148 }
149 
150 require_once("$MODDIR/lib/php/libschema.php");
151 $pgDriver = new Postgres($PG_CONN);
152 $libschema->setDriver($pgDriver);
153 $previousSchema = $libschema->getCurrSchema();
154 $isUpdating = array_key_exists('TABLE', $previousSchema) && array_key_exists('users', $previousSchema['TABLE']);
156 if ($dbManager->existsTable('sysconfig'))
157 {
158  $sysconfig = $dbManager->createMap('sysconfig', 'variablename', 'conf_value');
159  if(!array_key_exists('Release', $sysconfig))
160  {
161  $sysconfig['Release'] = 0;
162  }
163  print "Old release was $sysconfig[Release]\n";
164 }
165 
166 $migrateColumns = array('clearing_decision'=>array('reportinfo','clearing_pk','type_fk','comment'),
167  'license_ref_bulk'=>array('rf_fk','removing'));
168 if($isUpdating && !empty($sysconfig) && $sysconfig['Release'] == '2.6.3.1')
169 {
170  $dbManager->queryOnce('begin;
171  CREATE TABLE uploadtree_b AS (SELECT * FROM uploadtree_a);
172  DROP TABLE uploadtree_a;
173  CREATE TABLE uploadtree_a () INHERITS (uploadtree);
174  ALTER TABLE uploadtree_a ADD CONSTRAINT uploadtree_a_pkey PRIMARY KEY (uploadtree_pk);
175  INSERT INTO uploadtree_a SELECT * FROM uploadtree_b;
176  DROP TABLE uploadtree_b;
177  COMMIT;',__FILE__.'.rebuild.uploadtree_a');
178 }
179 
180 if($dbManager->existsTable("author"))
181 {
182  require_once("$LIBEXECDIR/resequence_author_table.php"); // If table exists, clean up for Schema
183 }
184 
185 // Migration script to clear tables for new constraints
186 require_once("$LIBEXECDIR/dbmigrate_3.3-3.4.php");
187 Migrate_33_34($dbManager, $Verbose);
188 
189 $FailMsg = $libschema->applySchema($SchemaFilePath, $Verbose, $DatabaseName, $migrateColumns);
190 if ($FailMsg)
191 {
192  print "ApplySchema failed: $FailMsg\n";
193  exit(1);
194 }
195 
196 // Populate sysconfig table
199 
200 $Filename = "$MODDIR/www/ui/init.ui";
201 $flagRemoved = !file_exists($Filename);
202 if (!$flagRemoved)
203 {
204  if ($Verbose)
205  {
206  print "Removing flag '$Filename'\n";
207  }
208  if (is_writable("$MODDIR/www/ui/"))
209  {
210  $flagRemoved = unlink($Filename);
211  }
212 }
213 if (!$flagRemoved)
214 {
215  print "Failed to remove $Filename\n";
216  print "Remove this file to complete the initialization.\n";
217 }
218 else
219 {
220  print "Database schema update completed successfully.\n";
221 }
222 
223 $FAILED_LICENSE_IMPORT = array();
224 
225 if (array_key_exists('r', $Options))
226 {
227  $dbManager->prepare(__METHOD__.".getDelDbNames",'SELECT datname FROM pg_database WHERE datistemplate = false and datname like $1');
228  $resDelDbNames = $dbManager->execute(__METHOD__.".getDelDbNames",array($delDbPattern));
229  $delDbNames=pg_fetch_all($resDelDbNames);
230  pg_free_result($resDelDbNames);
231  foreach ($delDbNames as $deleteDatabaseName)
232  {
233  $dbManager->queryOnce("DROP DATABASE $deleteDatabaseName[datname]");
234  }
235  if ($Verbose)
236  {
237  echo "dropped " . count($delDbNames) . " databases ";
238  }
239 }
240 
241 /* migration */
242 $currSchema = $libschema->getCurrSchema();
243 $sysconfig = $dbManager->createMap('sysconfig','variablename','conf_value');
244 global $LIBEXECDIR;
245 if($isUpdating && empty($sysconfig['Release'])) {
246  require_once("$LIBEXECDIR/dbmigrate_2.0-2.1.php"); // this is needed for all new installs from 2.0 on
247  Migrate_20_21($Verbose);
248  require_once("$LIBEXECDIR/dbmigrate_2.1-2.2.php");
249  print "Migrate data from 2.1 to 2.2 in $LIBEXECDIR\n";
250  Migrate_21_22($Verbose);
251  if($dbManager->existsTable('license_file_audit') && array_key_exists('clearing_pk', $currSchema['TABLE']['clearing_decision']))
252  {
253  require_once("$LIBEXECDIR/dbmigrate_2.5-2.6.php");
254  migrate_25_26($Verbose);
255  }
256  if(!array_key_exists('clearing_pk', $currSchema['TABLE']['clearing_decision']) && $isUpdating)
257  {
258  $timeoutSec = 20;
259  echo "Missing column clearing_decision.clearing_pk, you should update to version 2.6.2 before migration\n";
260  echo "Enter 'i' within $timeoutSec seconds to ignore this warning and run the risk of losing clearing decisions: ";
261  $handle = fopen ("php://stdin","r");
262  stream_set_blocking($handle,0);
263  for($s=0;$s<$timeoutSec;$s++)
264  {
265  sleep(1);
266  $line = fread($handle,1);
267  if ($line) {
268  break;
269  }
270  }
271  if(trim($line) != 'i')
272  {
273  echo "ABORTING!\n";
274  exit(26);
275  }
276  }
277  $sysconfig['Release'] = '2.6';
278 }
279 if (! $isUpdating) {
280  require_once ("$LIBEXECDIR/dbmigrate_2.1-2.2.php");
281  print "Creating default user\n";
282  Migrate_21_22($Verbose);
283 } else {
284  require_once ("$LIBEXECDIR/dbmigrate_3.5-3.6.php");
285  migrate_35_36($dbManager, $forceDecision);
286  updatePfileSha256($dbManager, $forcePfile);
287 }
288 
289 $release = array_key_exists('Release', $sysconfig) ? $sysconfig['Release'] : 0;
290 if (version_compare($release, '4.3.0', '<')) {
291  require_once("$LIBEXECDIR/dbmigrate_4.2-4.3.php");
292  Migrate_42_43($Verbose);
293 }
294 
295 require_once("$LIBEXECDIR/dbmigrate_cmu-mach.php");
296 Migrate_Cmu_Mach($dbManager, $Verbose);
297 
298 /* initialize the license_ref table */
299 if ($UpdateLiceneseRef)
300 {
301  $row = $dbManager->getSingleRow("SELECT count(*) FROM license_ref",array(),'license_ref.count');
302  if ($row['count'] > 0) {
303  print "Update reference licenses\n";
304  initLicenseRefTable(false);
305  }
306  else if ($row['count'] == 0) {
307  insertInToLicenseRefTableUsingJson('license_ref');
308 
309  $row_max = $dbManager->getSingleRow("SELECT max(rf_pk) from license_ref",array(),'license_ref.max.rf_pk');
310  $current_license_ref_rf_pk_seq = $row_max['max'];
311  $dbManager->getSingleRow("SELECT setval('license_ref_rf_pk_seq', $current_license_ref_rf_pk_seq)",array(),
312  'set next license_ref_rf_pk_seq value');
313 
314  print "fresh install, import licenseRef.json \n";
315  }
316 }
317 
318 if(!$isUpdating || $sysconfig['Release'] == '2.6')
319 {
320  if(!$dbManager->existsTable('license_candidate'))
321  {
322  $dbManager->queryOnce("CREATE TABLE license_candidate (group_fk integer) INHERITS (license_ref)");
323  }
324  if ($isUpdating && array_key_exists('clearing_pk', $currSchema['TABLE']['clearing_decision']))
325  {
326  require_once("$LIBEXECDIR/dbmigrate_clearing-event.php");
327  $libschema->dropColumnsFromTable(array('reportinfo','clearing_pk','type_fk','comment'), 'clearing_decision');
328  }
329  $sysconfig['Release'] = '2.6.3';
330 }
331 
332 if($sysconfig['Release'] == '2.6.3')
333 {
334  require_once("$LIBEXECDIR/dbmigrate_real-parent.php");
335 }
336 
337 $expiredDbReleases = array('2.6.3', '2.6.3.1', '2.6.3.2');
338 if($isUpdating && (empty($sysconfig['Release']) || in_array($sysconfig['Release'], $expiredDbReleases)))
339 {
340  require_once("$LIBEXECDIR/fo_mapping_license.php");
341  print "Rename license (using $LIBEXECDIR) for SPDX validity\n";
343 }
344 
345 $expiredDbReleases[] = '2.6.3.3';
346 $expiredDbReleases[] = '3.0.0';
347 if($isUpdating && (empty($sysconfig['Release']) || in_array($sysconfig['Release'], $expiredDbReleases)))
348 {
349  require_once("$LIBEXECDIR/dbmigrate_bulk_license.php");
350 }
351 
352 if(in_array($sysconfig['Release'], $expiredDbReleases))
353 {
354  $sysconfig['Release'] = '3.0.1';
355 }
356 
357 // Update '3dfx' licence shortname to 'Glide'. Since shortname is used as an
358 // identifier, this is not done as part of the licenseref updates.
359 if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == '3.0.1'))
360 {
361  $dbManager->begin();
362  $row = $dbManager->getSingleRow("
363  SELECT rf1.rf_pk AS id_3dfx,
364  rf2.rf_pk AS id_glide
365  FROM license_ref rf1
366  INNER JOIN license_ref rf2 USING (rf_fullname)
367  WHERE rf1.rf_shortname='3DFX'
368  AND rf2.rf_shortname='Glide'
369  LIMIT 1", array(), 'old.3dfx.rf_pk');
370  if (!empty($row))
371  {
372  $id_3dfx = intval($row['id_3dfx']);
373  $id_glide = intval($row['id_glide']);
374  $dbManager->queryOnce("DELETE FROM license_ref WHERE rf_pk=$id_glide");
375  $dbManager->queryOnce("UPDATE license_ref SET rf_shortname='Glide' WHERE rf_pk=$id_3dfx");
376  }
377  $dbManager->commit();
378 
379  $sysconfig['Release'] = "3.0.2";
380 }
381 
382 if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == '3.0.2'))
383 {
384  require_once("$LIBEXECDIR/dbmigrate_multiple_copyright_decisions.php");
385 
386  $sysconfig['Release'] = "3.1.0";
387 }
388 
389 // fix release-version datamodel-version missmatch
390 if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == "3.1.0")) {
391  $sysconfig['Release'] = "3.3.0";
392 }
393 
394 $dbManager->begin();
395 $dbManager->getSingleRow("DELETE FROM sysconfig WHERE variablename=$1",array('Release'),'drop.sysconfig.release');
396 $dbManager->insertTableRow('sysconfig',
397  array('variablename'=>'Release','conf_value'=>$SysConf["BUILD"]["VERSION"],
398  'ui_label'=>'Release','vartype'=>2,'group_name'=>'Release','description'=>'')
399 );
400 $dbManager->commit();
401 /* email/url/author data migration to other table */
402 require_once("$LIBEXECDIR/dbmigrate_copyright-author.php");
403 
404 // Migration script to move candidate licenses in obligations
405 require_once("$LIBEXECDIR/dbmigrate_3.6-3.7.php");
406 Migrate_36_37($dbManager, $Verbose);
407 
408 /* instance uuid */
409 require_once("$LIBEXECDIR/instance_uuid.php");
410 
411 // Migration script for 3.7 => 3.8
412 require_once("$LIBEXECDIR/dbmigrate_3.7-3.8.php");
413 Migrate_37_38($dbManager, $MODDIR);
414 
415 // Migration script for 4.0 => 4.1
416 require_once("$LIBEXECDIR/dbmigrate_4.0-4.1.php");
417 Migrate_40_41($dbManager);
418 
419 // Migration script for copyright_event table
420 require_once("$LIBEXECDIR/dbmigrate_copyright-event.php");
422 
423 /* sanity check */
424 require_once ("$LIBEXECDIR/sanity_check.php");
425 $checker = new SanityChecker($dbManager,$Verbose);
426 $errors = $checker->check();
427 
428 if($errors>0)
429 {
430  echo "ERROR: $errors sanity check".($errors>1?'s':'')." failed\n";
431 }
432 if (! empty($FAILED_LICENSE_IMPORT)) {
433  $failedInsert = array_filter($FAILED_LICENSE_IMPORT,
434  function ($x){
435  return $x[1] == "INSERT";
436  });
437  $failedUpdate = array_filter($FAILED_LICENSE_IMPORT,
438  function ($x){
439  return $x[1] == "UPDATE";
440  });
441  $failedPromote = array_filter($FAILED_LICENSE_IMPORT,
442  function ($x){
443  return $x[1] == "CANPROMOTE";
444  });
445  if (! empty($failedInsert)) {
446  echo "*** Failed to insert following licenses ***\n";
447  echo implode(",", array_map(function ($x) {
448  return $x[0];
449  }, $failedInsert)) . "\n";
450  }
451  if (! empty($failedUpdate)) {
452  echo "*** Failed to update following licenses ***\n";
453  echo implode(",", array_map(function ($x) {
454  return $x[0];
455  }, $failedUpdate)) . "\n";
456  }
457  if (! empty($failedPromote)) {
458  echo "*** Failed to move following licenses from candidate table ***\n";
459  echo implode(",", array_map(function ($x) {
460  return $x[0];
461  }, $failedPromote)) . "\n";
462  }
463 }
464 exit($errors);
465 
472 {
473  global $LIBEXECDIR;
474  global $dbManager;
475 
476  if (!is_dir($LIBEXECDIR)) {
477  print "FATAL: Directory '$LIBEXECDIR' does not exist.\n";
478  return (1);
479  }
480 
481  $dir = opendir($LIBEXECDIR);
482  if (!$dir) {
483  print "FATAL: Unable to access '$LIBEXECDIR'.\n";
484  return (1);
485  }
486  $dbManager->begin();
487  if ($tableName === 'license_ref_2') {
488  $dbManager->queryOnce("DROP TABLE IF EXISTS license_ref_2",
489  __METHOD__.'.dropAncientBackUp');
490  $dbManager->queryOnce("CREATE TABLE license_ref_2 (LIKE license_ref INCLUDING DEFAULTS)",
491  __METHOD__.'.backUpData');
492  }
494  $keysToBeChanged = array(
495  'rf_OSIapproved' => '"rf_OSIapproved"',
496  'rf_FSFfree'=> '"rf_FSFfree"',
497  'rf_GPLv2compatible' => '"rf_GPLv2compatible"',
498  'rf_GPLv3compatible'=> '"rf_GPLv3compatible"',
499  'rf_Fedora' => '"rf_Fedora"'
500  );
501  $keysToReplicate = [
502  "rf_spdx_id" => "rf_shortname",
503  ];
504  $keysToRemove = [
505  "rf_spdx_compatible"
506  ];
507 
508  $jsonData = json_decode(file_get_contents("$LIBEXECDIR/licenseRef.json"), true);
509  $statementName = __METHOD__.'.insertInTo'.$tableName;
510  foreach($jsonData as $licenseArray) {
511  foreach ($keysToReplicate as $duplicateKey => $originalKey) {
512  if ($licenseArray['rf_spdx_compatible'] == 't') {
513  $licenseArray[$duplicateKey] = $licenseArray[$originalKey];
514  } else {
515  $licenseArray[$duplicateKey] = "";
516  }
517  }
518  foreach ($keysToRemove as $key) {
519  unset($licenseArray[$key]);
520  }
521  ksort($licenseArray);
522  $arrayKeys = array_keys($licenseArray);
523  $arrayValues = array_values($licenseArray);
524  $keys = strtr(implode(",", $arrayKeys), $keysToBeChanged);
525  $valuePlaceHolders = "$" . join(",$",range(1, count($arrayKeys)));
526  $md5PlaceHolder = "$". (count($arrayKeys) + 1);
527  $arrayValues[] = $licenseArray['rf_text'];
528  $SQL = "INSERT INTO $tableName ( $keys,rf_md5 ) " .
529  "VALUES ($valuePlaceHolders,md5($md5PlaceHolder));";
530  $dbManager->prepare($statementName, $SQL);
531  $dbManager->execute($statementName, $arrayValues);
532  }
533  $dbManager->commit();
534  return (0);
535 }
536 
545 function initLicenseRefTable($Verbose)
546 {
550  global $dbManager;
551 
552  $dbManager->begin();
553  insertInToLicenseRefTableUsingJson('license_ref_2');
554  $dbManager->prepare(__METHOD__.".newLic", "SELECT * FROM license_ref_2");
555  $result_new = $dbManager->execute(__METHOD__.".newLic");
556 
557  $dbManager->prepare(__METHOD__.'.licenseRefByShortname',
558  'SELECT *,md5(rf_text) AS hash FROM license_ref WHERE rf_shortname=$1');
559 
561  while ($row = pg_fetch_assoc($result_new))
562  {
563  $rf_shortname = $row['rf_shortname'];
564  $result_check = $dbManager->execute(__METHOD__.'.licenseRefByShortname', array($rf_shortname));
565  $count = pg_num_rows($result_check);
566 
567  $rf_text = $row['rf_text'];
568  $rf_url = $row['rf_url'];
569  $rf_fullname = $row['rf_fullname'];
570  $rf_notes = $row['rf_notes'];
571  $rf_active = $row['rf_active'];
572  $marydone = $row['marydone'];
573  $rf_text_updatable = $row['rf_text_updatable'];
574  $rf_detector_type = $row['rf_detector_type'];
575  $rf_flag = $row['rf_flag'];
576  $rf_spdx_id = $row['rf_spdx_id'];
577 
578  if ($count) // update when it is existing
579  {
580  $row_check = pg_fetch_assoc($result_check);
581  pg_free_result($result_check);
582  $params = array();
583  $rf_text_check = $row_check['rf_text'];
584  $rf_url_check = $row_check['rf_url'];
585  $rf_fullname_check = $row_check['rf_fullname'];
586  $rf_notes_check = $row_check['rf_notes'];
587  $rf_active_check = $row_check['rf_active'];
588  $marydone_check = $row_check['marydone'];
589  $rf_text_updatable_check = $row_check['rf_text_updatable'];
590  $rf_detector_type_check = $row_check['rf_detector_type'];
591  $rf_flag_check = $row_check['rf_flag'];
592  $rf_spdx_id_check = $row_check['rf_spdx_id'];
593 
594  $candidateLicense = isLicenseExists($dbManager, $rf_shortname, true);
595  if ($candidateLicense) {
596  mergeCandidateLicense($dbManager, $candidateLicense);
597  }
598 
599  $statement = __METHOD__ . ".updateLicenseRef";
600  $sql = "UPDATE license_ref SET ";
601  if (($rf_flag_check == 1 && $rf_flag == 1) &&
602  ($rf_text_check != $rf_text && !empty($rf_text) &&
603  !(stristr($rf_text, 'License by Nomos')))) {
604  $params[] = $rf_text;
605  $position = "$" . count($params);
606  $sql .= "rf_text=$position,rf_md5=md5($position),rf_flag=1,";
607  $statement .= ".insertT";
608  }
609  if ($rf_url_check != $rf_url && !empty($rf_url)) {
610  $params[] = $rf_url;
611  $position = "$" . count($params);
612  $sql .= "rf_url=$position,";
613  $statement .= ".url";
614  }
615  if ($rf_fullname_check != $rf_fullname && !empty($rf_fullname)) {
616  $params[] = $rf_fullname;
617  $position = "$" . count($params);
618  $sql .= "rf_fullname=$position,";
619  $statement .= ".name";
620  }
621  if ($rf_notes_check != $rf_notes && !empty($rf_notes)) {
622  $params[] = $rf_notes;
623  $position = "$" . count($params);
624  $sql .= "rf_notes=$position,";
625  $statement .= ".notes";
626  }
627  if ($rf_active_check != $rf_active && !empty($rf_active)) {
628  $params[] = $rf_active;
629  $position = "$" . count($params);
630  $sql .= "rf_active=$position,";
631  $statement .= ".active";
632  }
633  if ($marydone_check != $marydone && !empty($marydone)) {
634  $params[] = $marydone;
635  $position = "$" . count($params);
636  $sql .= "marydone=$position,";
637  $statement .= ".marydone";
638  }
639  if ($rf_text_updatable_check != $rf_text_updatable && !empty($rf_text_updatable)) {
640  $params[] = $rf_text_updatable;
641  $position = "$" . count($params);
642  $sql .= "rf_text_updatable=$position,";
643  $statement .= ".tUpdate";
644  }
645  if ($rf_detector_type_check != $rf_detector_type && !empty($rf_detector_type)) {
646  $params[] = $rf_detector_type;
647  $position = "$" . count($params);
648  $sql .= "rf_detector_type=$position,";
649  $statement .= ".dType";
650  }
651  if (empty($rf_spdx_id_check) && !empty($rf_spdx_id) &&
652  $rf_spdx_id_check != $rf_spdx_id) {
653  $params[] = $rf_spdx_id;
654  $position = "$" . count($params);
655  $sql .= "rf_spdx_id=$position,";
656  $statement .= ".spdxId";
657  }
658  $sql = substr_replace($sql, "", -1);
659 
660  if ($sql != "UPDATE license_ref SET") { // check if we have something to update
661  $params[] = $rf_shortname;
662  $position = "$" . count($params);
663  $sql .= " WHERE rf_shortname=$position;";
664  try {
665  $dbManager->getSingleRow($sql, $params, $statement);
666  } catch (\Exception $e) {
667  global $FAILED_LICENSE_IMPORT;
668  $FAILED_LICENSE_IMPORT[] = array($rf_shortname, "UPDATE");
669  }
670  }
671  } else { // insert when it is new
672  pg_free_result($result_check);
673  $params = array();
674  $params['rf_shortname'] = $rf_shortname;
675  $params['rf_text'] = $rf_text;
676  $params['rf_url'] = $rf_url;
677  $params['rf_fullname'] = $rf_fullname;
678  $params['rf_notes'] = $rf_notes;
679  $params['rf_active'] = $rf_active;
680  $params['rf_text_updatable'] = $rf_text_updatable;
681  $params['rf_detector_type'] = $rf_detector_type;
682  $params['marydone'] = $marydone;
683  $params['rf_spdx_id'] = $rf_spdx_id;
684  insertNewLicense($dbManager, $params);
685  }
686  }
687  pg_free_result($result_new);
688 
689  $dbManager->queryOnce("DROP TABLE IF EXISTS license_ref_2");
690  $dbManager->commit();
691 
692  return (0);
693 } // initLicenseRefTable()
694 
703 function isLicenseExists($dbManager, $rf_shortname, $isCandidate = true)
704 {
705  $tableName = "license_ref";
706  if ($isCandidate) {
707  $tableName = "license_candidate";
708  }
709  $statement = __METHOD__ . ".$tableName";
710  $sql = "SELECT * FROM ONLY $tableName WHERE rf_shortname = $1;";
711  $licenseRow = $dbManager->getSingleRow($sql, array($rf_shortname),
712  $statement);
713  if (! empty($licenseRow)) {
714  return $licenseRow;
715  } else {
716  return false;
717  }
718 }
719 
727 function mergeCandidateLicense($dbManager, $candidateLicense)
728 {
729  $mainLicense = isLicenseExists($dbManager, $candidateLicense['rf_shortname'],
730  false);
731  $statement = __METHOD__ . ".md5Exists";
732  $sql = "SELECT rf_pk FROM ONLY license_ref WHERE md5(rf_text) = md5($1);";
733  $licenseRow = $dbManager->getSingleRow($sql,
734  array($candidateLicense['rf_text']), $statement);
735  if (! empty($licenseRow)) {
736  $md5Exists = true;
737  } else {
738  $md5Exists = false;
739  }
740  if ($mainLicense !== false && $md5Exists) {
741  $dbManager->begin();
742  $updateStatements = __METHOD__ . ".updateCandidateToMain";
743  $updateCeSql = "UPDATE clearing_event SET rf_fk = $1 WHERE rf_fk = $2;";
744  $updateCeSt = $updateStatements . ".ce";
745  $updateLsbSql = "UPDATE license_set_bulk SET rf_fk = $1 WHERE rf_fk = $2;";
746  $updateLsbSt = $updateStatements . ".lsb";
747  $updateUclSql = "UPDATE upload_clearing_license SET rf_fk = $1 " .
748  "WHERE rf_fk = $2;";
749  $updateUclSt = $updateStatements . ".ucl";
750  $deleteOcmSql = "DELETE FROM obligation_candidate_map WHERE rf_fk = $1;";
751  $deleteOcmSt = $updateStatements . ".ocm";
752 
753  $dbManager->getSingleRow($updateCeSql,
754  array($mainLicense['rf_pk'], $candidateLicense['rf_pk']), $updateCeSt);
755  $dbManager->getSingleRow($updateLsbSql,
756  array($mainLicense['rf_pk'], $candidateLicense['rf_pk']), $updateLsbSt);
757  $dbManager->getSingleRow($updateUclSql,
758  array($mainLicense['rf_pk'], $candidateLicense['rf_pk']), $updateUclSt);
759  $dbManager->getSingleRow($deleteOcmSql, array($candidateLicense['rf_pk']),
760  $deleteOcmSt);
761  $dbManager->commit();
762  } elseif ($mainLicense !== false || $md5Exists) {
763  // Short name exists and MD5 does not match
764  // Or short name does not exists by MD5 match
765  return -1;
766  }
767  $dbManager->begin();
768  $deleteSql = "DELETE FROM license_candidate WHERE rf_pk = $1;";
769  $deleteStatement = __METHOD__ . ".deleteCandidte";
770  $dbManager->prepare($deleteStatement, $deleteSql);
771  $dbManager->execute($deleteStatement, array($candidateLicense['rf_pk']));
772  if ($mainLicense === false && $md5Exists === false) {
773  // License does not exists
774  insertNewLicense($dbManager, $candidateLicense, true);
775  }
776  $dbManager->commit();
777 }
778 
788 function insertNewLicense($dbManager, $license, $wasCandidate = false)
789 {
790  $insertStatement = __METHOD__ . ".insertNewLicense";
791  $sql = "INSERT INTO license_ref (";
792  if ($wasCandidate) {
793  $sql .= "rf_pk, ";
794  $insertStatement .= ".wasCandidate";
795  }
796  $sql .= "rf_shortname, rf_text, rf_url, rf_fullname, rf_notes, rf_active, " .
797  "rf_text_updatable, rf_detector_type, marydone, rf_spdx_id, rf_md5, " .
798  "rf_add_date) VALUES (";
799  $params = array();
800  if ($wasCandidate) {
801  $params[] = $license['rf_pk'];
802  }
803  $params[] = $license['rf_shortname'];
804  $params[] = $license['rf_text'];
805  $params[] = $license['rf_url'];
806  $params[] = $license['rf_fullname'];
807  $params[] = $license['rf_notes'];
808  $params[] = $license['rf_active'];
809  $params[] = $license['rf_text_updatable'];
810  $params[] = $license['rf_detector_type'];
811  $params[] = $license['marydone'];
812  $params[] = $license['rf_spdx_id'];
813 
814  for ($i = 1; $i <= count($params); $i++) {
815  $sql .= "$" . $i . ",";
816  }
817 
818  $params[] = $license['rf_text'];
819  $textPos = "$" . count($params);
820 
821  $sql .= "md5($textPos),now())";
822  $rfPk = -1;
823  try {
824  $rfPk = $dbManager->insertPreparedAndReturn($insertStatement, $sql, $params,
825  "rf_pk");
826  } catch (\Exception $e) {
827  global $FAILED_LICENSE_IMPORT;
828  $type = "INSERT";
829  if ($wasCandidate) {
830  $type = "CANPROMOTE";
831  }
832  $FAILED_LICENSE_IMPORT[] = array($license['rf_shortname'], $type);
833  }
834  return $rfPk;
835 }
setDriver(Driver &$dbDriver)
Definition: DbManager.php:36
Populate_sysconfig()
Populate the sysconfig table with core variables.
get_pg_conn($sysconfdir, &$SysConf, $exitOnDbFail=true)
populate_from_sysconfig($conn, &$SysConf)
Migrate_20_21($DryRun)
Migrate to the uploadtree_a table.
Migrate_21_22($Verbose)
Create new groups, group_user_member, perm_upload and perm_folder records to support 2....
migrate_25_26($verbose)
Migrate_33_34($dbManager, $dryRun)
migrate_35_36($dbManager, $force=false)
Migrate_36_37($dbManager, $verbose)
Migrate_37_38($dbManager, $MODDIR)
Migrate_40_41($dbManager)
Migrate_42_43(bool $verbose)
Migrate_Cmu_Mach(DbManager $dbManager, $verbose=false)
renameLicensesForSpdxValidation($verbose)
Create map of old_shortname to new_shortname for SPDX and call renameLicenses.
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690
FossdashConfigInit($sysconfdir, &$SysConf)
Initialize the fossdash configuration after bootstrap().
insertInToLicenseRefTableUsingJson($tableName)
insert into license_ref table using json file.
Definition: fossinit.php:471
mergeCandidateLicense($dbManager, $candidateLicense)
Definition: fossinit.php:727
isLicenseExists($dbManager, $rf_shortname, $isCandidate=true)
Definition: fossinit.php:703
insertNewLicense($dbManager, $license, $wasCandidate=false)
Definition: fossinit.php:788
explainUsage()
Print Usage statement.
Definition: fossinit.php:13
foreach($Options as $Option=> $OptVal) if(0==$reference_flag &&0==$nomos_flag) $PG_CONN
bootstrap($sysconfdir="")
Bootstrap the fossology php library.
Definition: migratetest.php:82