FOSSology  4.7.1
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 require_once("$LIBEXECDIR/dbmigrate_legacy-license-names.php");
299 Migrate_Legacy_License_Names($dbManager, $Verbose);
300 
301 /* initialize the license_ref table */
302 if ($UpdateLiceneseRef)
303 {
304  if (version_compare($release, '4.8.0', '<')) {
305  /* Normalize legacy all-caps values before per-license update runs. */
306  $dbManager->queryOnce(
307  "UPDATE license_ref SET rf_licensetype='Unknown'
308  WHERE rf_licensetype IN ('UNKNOWN', 'PERMISSIVE')",
309  'migrate.rf_licensetype.case');
310  }
311  $row = $dbManager->getSingleRow("SELECT count(*) FROM license_ref",array(),'license_ref.count');
312  if ($row['count'] > 0) {
313  print "Update reference licenses\n";
314  initLicenseRefTable(false);
315  }
316  else if ($row['count'] == 0) {
317  insertInToLicenseRefTableUsingJson('license_ref');
318 
319  $row_max = $dbManager->getSingleRow("SELECT max(rf_pk) from license_ref",array(),'license_ref.max.rf_pk');
320  $current_license_ref_rf_pk_seq = $row_max['max'];
321  $dbManager->getSingleRow("SELECT setval('license_ref_rf_pk_seq', $current_license_ref_rf_pk_seq)",array(),
322  'set next license_ref_rf_pk_seq value');
323 
324  print "fresh install, import licenseRef.json \n";
325  }
326 }
327 
328 if(!$isUpdating || $sysconfig['Release'] == '2.6')
329 {
330  if(!$dbManager->existsTable('license_candidate'))
331  {
332  $dbManager->queryOnce("CREATE TABLE license_candidate (group_fk integer) INHERITS (license_ref)");
333  }
334  if ($isUpdating && array_key_exists('clearing_pk', $currSchema['TABLE']['clearing_decision']))
335  {
336  require_once("$LIBEXECDIR/dbmigrate_clearing-event.php");
337  $libschema->dropColumnsFromTable(array('reportinfo','clearing_pk','type_fk','comment'), 'clearing_decision');
338  }
339  $sysconfig['Release'] = '2.6.3';
340 }
341 
342 if($sysconfig['Release'] == '2.6.3')
343 {
344  require_once("$LIBEXECDIR/dbmigrate_real-parent.php");
345 }
346 
347 $expiredDbReleases = array('2.6.3', '2.6.3.1', '2.6.3.2');
348 if($isUpdating && (empty($sysconfig['Release']) || in_array($sysconfig['Release'], $expiredDbReleases)))
349 {
350  require_once("$LIBEXECDIR/fo_mapping_license.php");
351  print "Rename license (using $LIBEXECDIR) for SPDX validity\n";
353 }
354 
355 $expiredDbReleases[] = '2.6.3.3';
356 $expiredDbReleases[] = '3.0.0';
357 if($isUpdating && (empty($sysconfig['Release']) || in_array($sysconfig['Release'], $expiredDbReleases)))
358 {
359  require_once("$LIBEXECDIR/dbmigrate_bulk_license.php");
360 }
361 
362 if(in_array($sysconfig['Release'], $expiredDbReleases))
363 {
364  $sysconfig['Release'] = '3.0.1';
365 }
366 
367 // Update '3dfx' licence shortname to 'Glide'. Since shortname is used as an
368 // identifier, this is not done as part of the licenseref updates.
369 if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == '3.0.1'))
370 {
371  $dbManager->begin();
372  $row = $dbManager->getSingleRow("
373  SELECT rf1.rf_pk AS id_3dfx,
374  rf2.rf_pk AS id_glide
375  FROM license_ref rf1
376  INNER JOIN license_ref rf2 USING (rf_fullname)
377  WHERE rf1.rf_shortname='3DFX'
378  AND rf2.rf_shortname='Glide'
379  LIMIT 1", array(), 'old.3dfx.rf_pk');
380  if (!empty($row))
381  {
382  $id_3dfx = intval($row['id_3dfx']);
383  $id_glide = intval($row['id_glide']);
384  $dbManager->queryOnce("DELETE FROM license_ref WHERE rf_pk=$id_glide");
385  $dbManager->queryOnce("UPDATE license_ref SET rf_shortname='Glide' WHERE rf_pk=$id_3dfx");
386  }
387  $dbManager->commit();
388 
389  $sysconfig['Release'] = "3.0.2";
390 }
391 
392 if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == '3.0.2'))
393 {
394  require_once("$LIBEXECDIR/dbmigrate_multiple_copyright_decisions.php");
395 
396  $sysconfig['Release'] = "3.1.0";
397 }
398 
399 // fix release-version datamodel-version missmatch
400 if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == "3.1.0")) {
401  $sysconfig['Release'] = "3.3.0";
402 }
403 
404 // Handle idempotency of this script by checking if the Release variable is set
405 $new_version = $SysConf["BUILD"]["VERSION"] ?? '';
406 if ($new_version !==''){
407  $dbManager->begin();
408  $dbManager->getSingleRow("DELETE FROM sysconfig WHERE variablename=$1",array('Release'),'drop.sysconfig.release');
409  $dbManager->insertTableRow('sysconfig',
410  array('variablename'=>'Release','conf_value'=>$SysConf["BUILD"]["VERSION"],
411  'ui_label'=>'Release','vartype'=>2,'group_name'=>'Release','description'=>'')
412  );
413  $dbManager->commit();
414 }
415 
416 /* email/url/author data migration to other table */
417 require_once("$LIBEXECDIR/dbmigrate_copyright-author.php");
418 
419 // Migration script to move candidate licenses in obligations
420 require_once("$LIBEXECDIR/dbmigrate_3.6-3.7.php");
421 Migrate_36_37($dbManager, $Verbose);
422 
423 /* instance uuid */
424 require_once("$LIBEXECDIR/instance_uuid.php");
425 
426 // Migration script for 3.7 => 3.8
427 require_once("$LIBEXECDIR/dbmigrate_3.7-3.8.php");
428 Migrate_37_38($dbManager, $MODDIR);
429 
430 // Migration script for 4.0 => 4.1
431 require_once("$LIBEXECDIR/dbmigrate_4.0-4.1.php");
432 Migrate_40_41($dbManager);
433 
434 // Migration script for copyright_event table
435 require_once("$LIBEXECDIR/dbmigrate_copyright-event.php");
437 
438 /* sanity check */
439 require_once ("$LIBEXECDIR/sanity_check.php");
440 $checker = new SanityChecker($dbManager,$Verbose);
441 $errors = $checker->check();
442 
443 require_once("$LIBEXECDIR/dbmigrate_licensedb_compatibility.php");
445 
446 require_once("$LIBEXECDIR/dbmigrate_token.php");
447 Token_timestamp_migration();
448 
449 require_once("$LIBEXECDIR/dbmigrate_kotoba_candidate_licenses.php");
451 
452 if($errors>0)
453 {
454  echo "ERROR: $errors sanity check".($errors>1?'s':'')." failed\n";
455 }
456 if (! empty($FAILED_LICENSE_IMPORT)) {
457  $failedInsert = array_filter($FAILED_LICENSE_IMPORT,
458  function ($x){
459  return $x[1] == "INSERT";
460  });
461  $failedUpdate = array_filter($FAILED_LICENSE_IMPORT,
462  function ($x){
463  return $x[1] == "UPDATE";
464  });
465  $failedPromote = array_filter($FAILED_LICENSE_IMPORT,
466  function ($x){
467  return $x[1] == "CANPROMOTE";
468  });
469  if (! empty($failedInsert)) {
470  echo "*** Failed to insert following licenses ***\n";
471  echo implode(",", array_map(function ($x) {
472  return $x[0];
473  }, $failedInsert)) . "\n";
474  }
475  if (! empty($failedUpdate)) {
476  echo "*** Failed to update following licenses ***\n";
477  echo implode(",", array_map(function ($x) {
478  return $x[0];
479  }, $failedUpdate)) . "\n";
480  }
481  if (! empty($failedPromote)) {
482  echo "*** Failed to move following licenses from candidate table ***\n";
483  echo implode(",", array_map(function ($x) {
484  return $x[0];
485  }, $failedPromote)) . "\n";
486  }
487 }
489 exit($errors);
490 
493 {
494  global $dbManager;
495 
496  $rows = $dbManager->getRows(
497  "SELECT DISTINCT rf_licensetype FROM license_ref
498  WHERE rf_licensetype IS NOT NULL AND rf_licensetype <> ''
499  ORDER BY rf_licensetype",
500  array(), 'updateLicenseTypesConfig.fetchTypes');
501 
502  if (empty($rows)) {
503  return;
504  }
505  $dbTypes = array();
506  foreach ($rows as $row) {
507  $dbTypes[$row['rf_licensetype']] = true;
508  }
509 
510  $confRow = $dbManager->getSingleRow(
511  "SELECT conf_value FROM sysconfig WHERE variablename=$1",
512  array('LicenseTypes'), 'updateLicenseTypesConfig.fetchConf');
513 
514  if ($confRow === false || $confRow === null) {
515  return;
516  }
517 
518  $existingTypes = array();
519  $existingTypesLower = array();
520  if (!empty($confRow['conf_value'])) {
521  foreach (explode(',', $confRow['conf_value']) as $t) {
522  $trimmed = trim($t);
523  if ($trimmed !== '') {
524  $existingTypes[$trimmed] = true;
525  $existingTypesLower[strtolower($trimmed)] = true;
526  }
527  }
528  }
529 
530  $newTypes = array();
531  foreach ($dbTypes as $type => $_) {
532  if (!isset($existingTypesLower[strtolower($type)])) {
533  $newTypes[] = $type;
534  }
535  }
536  if (empty($newTypes)) {
537  return;
538  }
539 
540  $merged = array_merge(array_keys($existingTypes), $newTypes);
541  $newValue = implode(', ', $merged);
542 
543  $dbManager->getRows(
544  "UPDATE sysconfig SET conf_value=$1 WHERE variablename=$2",
545  array($newValue, 'LicenseTypes'), 'updateLicenseTypesConfig.update');
546 
547  print "LicenseTypes updated: $newValue\n";
548 }
549 
556 {
557  global $LIBEXECDIR;
558  global $dbManager;
559 
560  if (!is_dir($LIBEXECDIR)) {
561  print "FATAL: Directory '$LIBEXECDIR' does not exist.\n";
562  return (1);
563  }
564 
565  if (!is_readable($LIBEXECDIR)) {
566  print "FATAL: Unable to access '$LIBEXECDIR'.\n";
567  return (1);
568  }
569  $dbManager->begin();
570  if ($tableName === 'license_ref_2') {
571  $dbManager->queryOnce("DROP TABLE IF EXISTS license_ref_2",
572  __METHOD__.'.dropAncientBackUp');
573  $dbManager->queryOnce("CREATE TABLE license_ref_2 (LIKE license_ref INCLUDING DEFAULTS)",
574  __METHOD__.'.backUpData');
575  }
577  $keysToBeChanged = array(
578  'rf_OSIapproved' => '"rf_OSIapproved"',
579  'rf_FSFfree'=> '"rf_FSFfree"',
580  'rf_GPLv2compatible' => '"rf_GPLv2compatible"',
581  'rf_GPLv3compatible'=> '"rf_GPLv3compatible"',
582  'rf_Fedora' => '"rf_Fedora"'
583  );
584  $keysToReplicate = [
585  "rf_spdx_id" => "rf_shortname",
586  ];
587  $keysToRemove = [
588  "rf_spdx_compatible"
589  ];
590 
591  $jsonData = json_decode(file_get_contents("$LIBEXECDIR/licenseRef.json"), true);
592  foreach($jsonData as $licenseArray) {
593  foreach ($keysToReplicate as $duplicateKey => $originalKey) {
594  if ($licenseArray['rf_spdx_compatible'] == 't') {
595  $licenseArray[$duplicateKey] = $licenseArray[$originalKey];
596  } else {
597  $licenseArray[$duplicateKey] = "";
598  }
599  }
600  foreach ($keysToRemove as $key) {
601  unset($licenseArray[$key]);
602  }
603  ksort($licenseArray);
604  $arrayKeys = array_keys($licenseArray);
605  $arrayValues = array_values($licenseArray);
606  $keys = strtr(implode(",", $arrayKeys), $keysToBeChanged);
607  $statementName = __METHOD__ . '.insertInTo' . $tableName . '.' . md5($tableName . $keys);
608  $valuePlaceHolders = "$" . join(",$",range(1, count($arrayKeys)));
609  $md5PlaceHolder = "$". (count($arrayKeys) + 1);
610  $arrayValues[] = $licenseArray['rf_text'];
611  $SQL = "INSERT INTO $tableName ( $keys,rf_md5 ) " .
612  "VALUES ($valuePlaceHolders,md5($md5PlaceHolder));";
613  $dbManager->prepare($statementName, $SQL);
614  $dbManager->execute($statementName, $arrayValues);
615  }
616  $dbManager->commit();
617  return (0);
618 }
619 
628 function initLicenseRefTable($Verbose)
629 {
633  global $dbManager;
634 
635  $dbManager->begin();
636  insertInToLicenseRefTableUsingJson('license_ref_2');
637  $dbManager->prepare(__METHOD__.".newLic", "SELECT * FROM license_ref_2");
638  $result_new = $dbManager->execute(__METHOD__.".newLic");
639 
640  $dbManager->prepare(__METHOD__.'.licenseRefByShortname',
641  'SELECT *,md5(rf_text) AS hash FROM license_ref WHERE rf_shortname=$1');
642 
644  while ($row = pg_fetch_assoc($result_new))
645  {
646  $rf_shortname = $row['rf_shortname'];
647  $result_check = $dbManager->execute(__METHOD__.'.licenseRefByShortname', array($rf_shortname));
648  $count = pg_num_rows($result_check);
649 
650  $rf_text = $row['rf_text'];
651  $rf_url = $row['rf_url'];
652  $rf_fullname = $row['rf_fullname'];
653  $rf_notes = $row['rf_notes'];
654  $rf_active = $row['rf_active'];
655  $marydone = $row['marydone'];
656  $rf_text_updatable = $row['rf_text_updatable'];
657  $rf_detector_type = $row['rf_detector_type'];
658  $rf_flag = $row['rf_flag'];
659  $rf_spdx_id = $row['rf_spdx_id'];
660  $rf_licensetype = $row['rf_licensetype'];
661 
662  if ($count) // update when it is existing
663  {
664  $row_check = pg_fetch_assoc($result_check);
665  pg_free_result($result_check);
666  $params = array();
667  $rf_text_check = $row_check['rf_text'];
668  $rf_url_check = $row_check['rf_url'];
669  $rf_fullname_check = $row_check['rf_fullname'];
670  $rf_notes_check = $row_check['rf_notes'];
671  $rf_active_check = $row_check['rf_active'];
672  $marydone_check = $row_check['marydone'];
673  $rf_text_updatable_check = $row_check['rf_text_updatable'];
674  $rf_detector_type_check = $row_check['rf_detector_type'];
675  $rf_flag_check = $row_check['rf_flag'];
676  $rf_spdx_id_check = $row_check['rf_spdx_id'];
677  $rf_licensetype_check = $row_check['rf_licensetype'];
678 
679  $candidateLicense = isLicenseExists($dbManager, $rf_shortname, true);
680  if ($candidateLicense) {
681  mergeCandidateLicense($dbManager, $candidateLicense);
682  }
683 
684  $statement = __METHOD__ . ".updateLicenseRef";
685  $sql = "UPDATE license_ref SET ";
686  if (($rf_flag_check == 1 && $rf_flag == 1) &&
687  ($rf_text_check != $rf_text && !empty($rf_text) &&
688  !(stristr($rf_text, 'License by Nomos')) &&
689  !(stristr($rf_text, 'License by OJO')))) {
690  $params[] = $rf_text;
691  $position = "$" . count($params);
692  $sql .= "rf_text=$position,rf_md5=md5($position),rf_flag=1,";
693  $statement .= ".insertT";
694  }
695  if ($rf_url_check != $rf_url && !empty($rf_url)) {
696  $params[] = $rf_url;
697  $position = "$" . count($params);
698  $sql .= "rf_url=$position,";
699  $statement .= ".url";
700  }
701  if ($rf_fullname_check != $rf_fullname && !empty($rf_fullname)) {
702  $params[] = $rf_fullname;
703  $position = "$" . count($params);
704  $sql .= "rf_fullname=$position,";
705  $statement .= ".name";
706  }
707  if ($rf_notes_check != $rf_notes && !empty($rf_notes)) {
708  $params[] = $rf_notes;
709  $position = "$" . count($params);
710  $sql .= "rf_notes=$position,";
711  $statement .= ".notes";
712  }
713  if ($rf_active_check != $rf_active && !empty($rf_active)) {
714  $params[] = $rf_active;
715  $position = "$" . count($params);
716  $sql .= "rf_active=$position,";
717  $statement .= ".active";
718  }
719  if ($marydone_check != $marydone && !empty($marydone)) {
720  $params[] = $marydone;
721  $position = "$" . count($params);
722  $sql .= "marydone=$position,";
723  $statement .= ".marydone";
724  }
725  if ($rf_text_updatable_check != $rf_text_updatable && !empty($rf_text_updatable)) {
726  $params[] = $rf_text_updatable;
727  $position = "$" . count($params);
728  $sql .= "rf_text_updatable=$position,";
729  $statement .= ".tUpdate";
730  }
731  if ($rf_detector_type_check != $rf_detector_type && !empty($rf_detector_type)) {
732  $params[] = $rf_detector_type;
733  $position = "$" . count($params);
734  $sql .= "rf_detector_type=$position,";
735  $statement .= ".dType";
736  }
737  if (empty($rf_spdx_id_check) && !empty($rf_spdx_id) &&
738  $rf_spdx_id_check != $rf_spdx_id) {
739  $params[] = $rf_spdx_id;
740  $position = "$" . count($params);
741  $sql .= "rf_spdx_id=$position,";
742  $statement .= ".spdxId";
743  }
744  if (!empty($rf_licensetype) && $rf_licensetype_check != $rf_licensetype) {
745  $params[] = $rf_licensetype;
746  $position = "$" . count($params);
747  $sql .= "rf_licensetype=$position,";
748  $statement .= ".licType";
749  }
750  $sql = substr_replace($sql, "", -1);
751 
752  if ($sql != "UPDATE license_ref SET") { // check if we have something to update
753  $params[] = $rf_shortname;
754  $position = "$" . count($params);
755  $sql .= " WHERE rf_shortname=$position;";
756  try {
757  $dbManager->getSingleRow($sql, $params, $statement);
758  } catch (\Exception $e) {
759  global $FAILED_LICENSE_IMPORT;
760  $FAILED_LICENSE_IMPORT[] = array($rf_shortname, "UPDATE");
761  }
762  }
763  } else { // insert when it is new
764  pg_free_result($result_check);
765  $params = array();
766  $params['rf_shortname'] = $rf_shortname;
767  $params['rf_text'] = $rf_text;
768  $params['rf_url'] = $rf_url;
769  $params['rf_fullname'] = $rf_fullname;
770  $params['rf_notes'] = $rf_notes;
771  $params['rf_active'] = $rf_active;
772  $params['rf_text_updatable'] = $rf_text_updatable;
773  $params['rf_detector_type'] = $rf_detector_type;
774  $params['marydone'] = $marydone;
775  $params['rf_spdx_id'] = $rf_spdx_id;
776  $params['rf_licensetype'] = $rf_licensetype;
777  insertNewLicense($dbManager, $params);
778  }
779  }
780  pg_free_result($result_new);
781 
782  $dbManager->queryOnce("DROP TABLE IF EXISTS license_ref_2");
783  $dbManager->commit();
784 
785  return (0);
786 } // initLicenseRefTable()
787 
796 function isLicenseExists($dbManager, $rf_shortname, $isCandidate = true)
797 {
798  $tableName = "license_ref";
799  if ($isCandidate) {
800  $tableName = "license_candidate";
801  }
802  $statement = __METHOD__ . ".$tableName";
803  $sql = "SELECT * FROM ONLY $tableName WHERE rf_shortname = $1;";
804  $licenseRow = $dbManager->getSingleRow($sql, array($rf_shortname),
805  $statement);
806  if (! empty($licenseRow)) {
807  return $licenseRow;
808  } else {
809  return false;
810  }
811 }
812 
820 function mergeCandidateLicense($dbManager, $candidateLicense)
821 {
822  $mainLicense = isLicenseExists($dbManager, $candidateLicense['rf_shortname'],
823  false);
824  $statement = __METHOD__ . ".md5Exists";
825  $sql = "SELECT rf_pk FROM ONLY license_ref WHERE md5(rf_text) = md5($1);";
826  $licenseRow = $dbManager->getSingleRow($sql,
827  array($candidateLicense['rf_text']), $statement);
828  if (! empty($licenseRow)) {
829  $md5Exists = true;
830  } else {
831  $md5Exists = false;
832  }
833  if ($mainLicense !== false && $md5Exists) {
834  $dbManager->begin();
835  $updateStatements = __METHOD__ . ".updateCandidateToMain";
836  $updateCeSql = "UPDATE clearing_event SET rf_fk = $1 WHERE rf_fk = $2;";
837  $updateCeSt = $updateStatements . ".ce";
838  $updateLsbSql = "UPDATE license_set_bulk SET rf_fk = $1 WHERE rf_fk = $2;";
839  $updateLsbSt = $updateStatements . ".lsb";
840  $updateUclSql = "UPDATE upload_clearing_license SET rf_fk = $1 " .
841  "WHERE rf_fk = $2;";
842  $updateUclSt = $updateStatements . ".ucl";
843  $deleteOcmSql = "DELETE FROM obligation_candidate_map WHERE rf_fk = $1;";
844  $deleteOcmSt = $updateStatements . ".ocm";
845 
846  $dbManager->getSingleRow($updateCeSql,
847  array($mainLicense['rf_pk'], $candidateLicense['rf_pk']), $updateCeSt);
848  $dbManager->getSingleRow($updateLsbSql,
849  array($mainLicense['rf_pk'], $candidateLicense['rf_pk']), $updateLsbSt);
850  $dbManager->getSingleRow($updateUclSql,
851  array($mainLicense['rf_pk'], $candidateLicense['rf_pk']), $updateUclSt);
852  $dbManager->getSingleRow($deleteOcmSql, array($candidateLicense['rf_pk']),
853  $deleteOcmSt);
854  $dbManager->commit();
855  } elseif ($mainLicense !== false || $md5Exists) {
856  // Short name exists and MD5 does not match
857  // Or short name does not exists by MD5 match
858  return -1;
859  }
860  $dbManager->begin();
861  $deleteSql = "DELETE FROM license_candidate WHERE rf_pk = $1;";
862  $deleteStatement = __METHOD__ . ".deleteCandidte";
863  $dbManager->prepare($deleteStatement, $deleteSql);
864  $dbManager->execute($deleteStatement, array($candidateLicense['rf_pk']));
865  if ($mainLicense === false && $md5Exists === false) {
866  // License does not exists
867  insertNewLicense($dbManager, $candidateLicense, true);
868  }
869  $dbManager->commit();
870 }
871 
881 function insertNewLicense($dbManager, $license, $wasCandidate = false)
882 {
883  $insertStatement = __METHOD__ . ".insertNewLicense";
884  $sql = "INSERT INTO license_ref (";
885  if ($wasCandidate) {
886  $sql .= "rf_pk, ";
887  $insertStatement .= ".wasCandidate";
888  }
889  $sql .= "rf_shortname, rf_text, rf_url, rf_fullname, rf_notes, rf_active, " .
890  "rf_text_updatable, rf_detector_type, marydone, rf_spdx_id, rf_licensetype, " .
891  "rf_md5, rf_add_date) VALUES (";
892  $params = array();
893  if ($wasCandidate) {
894  $params[] = $license['rf_pk'];
895  }
896  $params[] = $license['rf_shortname'];
897  $params[] = $license['rf_text'];
898  $params[] = $license['rf_url'];
899  $params[] = $license['rf_fullname'];
900  $params[] = $license['rf_notes'];
901  $params[] = $license['rf_active'];
902  $params[] = $license['rf_text_updatable'];
903  $params[] = $license['rf_detector_type'];
904  $params[] = $license['marydone'];
905  $params[] = $license['rf_spdx_id'];
906  $params[] = !empty($license['rf_licensetype']) ? $license['rf_licensetype'] : 'Unknown';
907 
908  for ($i = 1; $i <= count($params); $i++) {
909  $sql .= "$" . $i . ",";
910  }
911 
912  $params[] = $license['rf_text'];
913  $textPos = "$" . count($params);
914 
915  $sql .= "md5($textPos),now())";
916  $rfPk = -1;
917  try {
918  $rfPk = $dbManager->insertPreparedAndReturn($insertStatement, $sql, $params,
919  "rf_pk");
920  } catch (\Exception $e) {
921  global $FAILED_LICENSE_IMPORT;
922  $type = "INSERT";
923  if ($wasCandidate) {
924  $type = "CANPROMOTE";
925  }
926  $FAILED_LICENSE_IMPORT[] = array($license['rf_shortname'], $type);
927  }
928  return $rfPk;
929 }
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)
Migrate_Legacy_License_Names(DbManager $dbManager, $verbose=false)
if(!function_exists('resolve_config_value')) $Options
Definition: fo_dbcheck.php:51
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:555
mergeCandidateLicense($dbManager, $candidateLicense)
Definition: fossinit.php:820
isLicenseExists($dbManager, $rf_shortname, $isCandidate=true)
Definition: fossinit.php:796
updateLicenseTypesConfig()
Append new rf_licensetype values found in license_ref to the LicenseTypes sysconfig entry.
Definition: fossinit.php:492
insertNewLicense($dbManager, $license, $wasCandidate=false)
Definition: fossinit.php:881
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