fossinit.php 20.4 KB
Newer Older
1 2 3
#!/usr/bin/php
<?php
/***********************************************************
4
 Copyright (C) 2008-2015 Hewlett-Packard Development Company, L.P.
5
 Copyright (C) 2014-2015,2019 Siemens AG
6 7 8 9 10 11 12 13 14 15 16 17 18

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 version 2 as published by the Free Software Foundation.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along
 with this program; if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19
 ***********************************************************/
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/** \brief Print Usage statement.
 *  \return No return, this calls exit.
 **/
function explainUsage()
{
  global $argv;

  $usage = "Usage: " . basename($argv[0]) . " [options]
  Update FOSSology database. This should be used immediately after an install or update. Options are:
  -c  path to fossology configuration files
  -d  {database name} default is 'fossology'
  -f  {file} update the schema with file generated by schema-export.php
  -l  update the license_ref table with fossology supplied licenses
  -r  {prefix} drop database with name starts with prefix
  -v  enable verbose preview (prints sql that would happen, but does not execute it, DB is not updated)
  -h  this help usage";
  print "$usage\n";
  exit(0);
}


42
/**
Robert Gobeille's avatar
Robert Gobeille committed
43 44 45 46
 * @file fossinit.php
 * @brief This program applies core-schema.dat to the database (which
 *        must exist) and updates the license_ref table.
 * @return 0 for success, 1 for failure.
47
 **/
48

Steffen Weber's avatar
Steffen Weber committed
49
use Fossology\Lib\Db\DbManager;
50
use Fossology\Lib\Db\Driver\Postgres;
51

52 53 54
/* Note: php 5 getopt() ignores options not specified in the function call, so add
 * dummy options in order to catch invalid options.
 */
55
$AllPossibleOpts = "abc:d:ef:ghijklmnopqr:stuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
56 57 58 59 60

/* defaults */
$Verbose = false;
$DatabaseName = "fossology";
$UpdateLiceneseRef = false;
61
$sysconfdir = '';
62
$delDbPattern = 'the option -rfosstest will drop data bases with datname like "fosstest%"';
63 64 65

/* command-line options */
$Options = getopt($AllPossibleOpts);
66
foreach($Options as $optKey => $optVal)
67
{
68
  switch($optKey)
69
  {
70
    case 'c': /* set SYSCONFIDR */
71
      $sysconfdir = $optVal;
72
      break;
73
    case 'd': /* optional database name */
74
      $DatabaseName = $optVal;
75 76
      break;
    case 'f': /* schema file */
77
      $SchemaFilePath = $optVal;
78 79
      break;
    case 'h': /* help */
80
      explainUsage();
81 82 83 84 85 86
    case 'l': /* update the license_ref table */
      $UpdateLiceneseRef = true;
      break;
    case 'v': /* verbose */
      $Verbose = true;
      break;
87 88 89
    case 'r':
      $delDbPattern = $optVal ? "$optVal%" : "fosstest%";
      break;
90
    default:
91 92
      echo "Invalid Option \"$optKey\".\n";
      explainUsage();
93 94 95
  }
}

96 97
/* Set SYSCONFDIR and set global (for backward compatibility) */
$SysConf = bootstrap($sysconfdir);
98 99
$SysConf["DBCONF"]["dbname"] = $DatabaseName;
$GLOBALS["SysConf"] = array_merge($GLOBALS["SysConf"], $SysConf);
100 101 102 103 104 105 106 107 108 109
$projectGroup = $SysConf['DIRECTORIES']['PROJECTGROUP'] ?: 'fossy';
$gInfo = posix_getgrnam($projectGroup);
posix_setgid($gInfo['gid']);
$groups = `groups`;
if (!preg_match("/\s$projectGroup\s/",$groups) && (posix_getgid() != $gInfo['gid']))
{
  print "FATAL: You must be in group '$projectGroup'.\n";
  exit(1);
}

110 111 112 113 114
require_once("$MODDIR/vendor/autoload.php");
require_once("$MODDIR/lib/php/common-db.php");
require_once("$MODDIR/lib/php/common-container.php");
require_once("$MODDIR/lib/php/common-cache.php");
require_once("$MODDIR/lib/php/common-sysconfig.php");
115 116 117 118

/* Initialize global system configuration variables $SysConfig[] */
ConfigInit($SYSCONFDIR, $SysConf);

119 120
/** delete from copyright where pfile_fk not in (select pfile_pk from pfile) */
/** add foreign constraint on copyright pfile_fk if not exist */
121 122 123 124
/** comment out for 2.5.0
require_once("$LIBEXECDIR/dbmigrate_2.0-2.5-pre.php");
Migrate_20_25($Verbose);
*/
125

126 127 128
if (empty($SchemaFilePath)) {
  $SchemaFilePath = "$MODDIR/www/ui/core-schema.dat";
}
129

130
if (!file_exists($SchemaFilePath))
131
{
132
  print "FAILED: Schema data file ($SchemaFilePath) not found.\n";
133
  exit(1);
134 135
}

136
require_once("$MODDIR/lib/php/libschema.php");
137 138
$pgDriver = new Postgres($PG_CONN);
$libschema->setDriver($pgDriver);
139 140
$previousSchema = $libschema->getCurrSchema();
$isUpdating = array_key_exists('TABLE', $previousSchema) && array_key_exists('users', $previousSchema['TABLE']);
Steffen Weber's avatar
Steffen Weber committed
141 142 143 144
/* @var $dbManager DbManager */
if ($dbManager->existsTable('sysconfig'))
{
  $sysconfig = $dbManager->createMap('sysconfig', 'variablename', 'conf_value');
145 146 147 148
  if(!array_key_exists('Release', $sysconfig))
  {
    $sysconfig['Release'] = 0;
  }
Steffen Weber's avatar
Steffen Weber committed
149 150
  print "Old release was $sysconfig[Release]\n";
}
151

152 153
$migrateColumns = array('clearing_decision'=>array('reportinfo','clearing_pk','type_fk','comment'),
        'license_ref_bulk'=>array('rf_fk','removing'));
154
if($isUpdating && !empty($sysconfig) && $sysconfig['Release'] == '2.6.3.1')
Steffen Weber's avatar
Steffen Weber committed
155
{
156
  $dbManager->queryOnce('begin;
Steffen Weber's avatar
Steffen Weber committed
157 158 159 160 161 162 163 164 165
    CREATE TABLE uploadtree_b AS (SELECT * FROM uploadtree_a);
    DROP TABLE uploadtree_a;
    CREATE TABLE uploadtree_a () INHERITS (uploadtree);
    ALTER TABLE uploadtree_a ADD CONSTRAINT uploadtree_a_pkey PRIMARY KEY (uploadtree_pk);
    INSERT INTO uploadtree_a SELECT * FROM uploadtree_b;
    DROP TABLE uploadtree_b;
    COMMIT;',__FILE__.'.rebuild.uploadtree_a');
}

166 167 168 169 170
if($dbManager->existsTable("author"))
{
  require_once("$LIBEXECDIR/resequence_author_table.php"); // If table exists, clean up for Schema
}

171 172 173 174
// Migration script to clear tables for new constraints
require_once("$LIBEXECDIR/dbmigrate_3.3-3.4.php");
Migrate_33_34($dbManager, $Verbose);

175
$FailMsg = $libschema->applySchema($SchemaFilePath, $Verbose, $DatabaseName, $migrateColumns);
176
if ($FailMsg)
177
{
178 179 180
  print "ApplySchema failed: $FailMsg\n";
  exit(1);
}
181 182 183
$Filename = "$MODDIR/www/ui/init.ui";
$flagRemoved = !file_exists($Filename);
if (!$flagRemoved)
184
{
185
  if ($Verbose)
186
  {
187
    print "Removing flag '$Filename'\n";
188
  }
189
  if (is_writable("$MODDIR/www/ui/"))
190
  {
191
    $flagRemoved = unlink($Filename);
192
  }
193
}
194 195 196 197 198 199 200 201 202
if (!$flagRemoved)
{
  print "Failed to remove $Filename\n";
  print "Remove this file to complete the initialization.\n";
}
else
{
  print "Database schema update completed successfully.\n";
}
203

204
/* initialize the license_ref table */
205
if ($UpdateLiceneseRef)
206
{
207
  $row = $dbManager->getSingleRow("SELECT count(*) FROM license_ref",array(),'license_ref.count');
208
  if ($row['count'] >  0) {
209 210
    print "Update reference licenses\n";
    initLicenseRefTable(false);
211 212
  }
  else if ($row['count'] ==  0) {
213
    insertInToLicenseRefTableUsingJson('license_ref');
214

215
    $row_max = $dbManager->getSingleRow("SELECT max(rf_pk) from license_ref",array(),'license_ref.max.rf_pk');
216
    $current_license_ref_rf_pk_seq = $row_max['max'];
217 218
    $dbManager->getSingleRow("SELECT setval('license_ref_rf_pk_seq', $current_license_ref_rf_pk_seq)",array(),
            'set next license_ref_rf_pk_seq value');
219

220
    print "fresh install, import licenseRef.json \n";
221
  }
222 223
}

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
if (array_key_exists('r', $Options))
{
  $dbManager->prepare(__METHOD__.".getDelDbNames",'SELECT datname FROM pg_database WHERE datistemplate = false and datname like $1');
  $resDelDbNames = $dbManager->execute(__METHOD__.".getDelDbNames",array($delDbPattern));
  $delDbNames=pg_fetch_all($resDelDbNames);
  pg_free_result($resDelDbNames);
  foreach ($delDbNames as $deleteDatabaseName)
  {
    $dbManager->queryOnce("DROP DATABASE $deleteDatabaseName[datname]");
  }
  if ($Verbose)
  {
    echo "dropped " . count($delDbNames) . " databases ";
  }
}

240
/* migration */
241
$currSchema = $libschema->getCurrSchema();
242
$sysconfig = $dbManager->createMap('sysconfig','variablename','conf_value');
243
global $LIBEXECDIR;
244
if($isUpdating && empty($sysconfig['Release'])) {
245 246 247 248 249
  require_once("$LIBEXECDIR/dbmigrate_2.0-2.1.php");  // this is needed for all new installs from 2.0 on
  Migrate_20_21($Verbose);
  require_once("$LIBEXECDIR/dbmigrate_2.1-2.2.php");
  print "Migrate data from 2.1 to 2.2 in $LIBEXECDIR\n";
  Migrate_21_22($Verbose);
250
  if($dbManager->existsTable('license_file_audit') && array_key_exists('clearing_pk', $currSchema['TABLE']['clearing_decision']))
Steffen Weber's avatar
Steffen Weber committed
251 252 253 254
  {
    require_once("$LIBEXECDIR/dbmigrate_2.5-2.6.php");
    migrate_25_26($Verbose);
  }
255
  if(!array_key_exists('clearing_pk', $currSchema['TABLE']['clearing_decision']) && $isUpdating)
256
  {
257
    $timeoutSec = 20;
258
    echo "Missing column clearing_decision.clearing_pk, you should update to version 2.6.2 before migration\n";
259
    echo "Enter 'i' within $timeoutSec seconds to ignore this warning and run the risk of losing clearing decisions: ";
260
    $handle = fopen ("php://stdin","r");
261 262 263 264 265
    stream_set_blocking($handle,0);
    for($s=0;$s<$timeoutSec;$s++)
    {
      sleep(1);
      $line = fread($handle,1);
266 267 268
      if ($line) {
        break;
      }
269 270 271
    }
    if(trim($line) != 'i')
    {
272 273 274
     echo "ABORTING!\n";
     exit(26);
    }
275
  }
276 277
  $sysconfig['Release'] = '2.6';
}
278 279 280 281 282 283
if(!$isUpdating)
{
  require_once("$LIBEXECDIR/dbmigrate_2.1-2.2.php");
  print "Creating default user\n";
  Migrate_21_22($Verbose);
}
284

285
if(!$isUpdating || $sysconfig['Release'] == '2.6')
286
{
287
  if(!$dbManager->existsTable('license_candidate'))
288
  {
289
    $dbManager->queryOnce("CREATE TABLE license_candidate (group_fk integer) INHERITS (license_ref)");
290
  }
291
  if ($isUpdating && array_key_exists('clearing_pk', $currSchema['TABLE']['clearing_decision']))
292 293 294 295
  {
    require_once("$LIBEXECDIR/dbmigrate_clearing-event.php");
    $libschema->dropColumnsFromTable(array('reportinfo','clearing_pk','type_fk','comment'), 'clearing_decision');
  }
296 297 298 299 300 301
  $sysconfig['Release'] = '2.6.3';
}

if($sysconfig['Release'] == '2.6.3')
{
  require_once("$LIBEXECDIR/dbmigrate_real-parent.php");
Steffen Weber's avatar
Steffen Weber committed
302
}
303

304 305
$expiredDbReleases = array('2.6.3', '2.6.3.1', '2.6.3.2');
if($isUpdating && (empty($sysconfig['Release']) || in_array($sysconfig['Release'], $expiredDbReleases)))
306 307 308 309 310 311
{
  require_once("$LIBEXECDIR/fo_mapping_license.php");
  print "Rename license (using $LIBEXECDIR) for SPDX validity\n";
  renameLicensesForSpdxValidation($Verbose);
}

312 313 314
$expiredDbReleases[] = '2.6.3.3';
$expiredDbReleases[] = '3.0.0';
if($isUpdating && (empty($sysconfig['Release']) || in_array($sysconfig['Release'], $expiredDbReleases)))
Steffen Weber's avatar
Steffen Weber committed
315
{
316 317 318 319 320 321
  require_once("$LIBEXECDIR/dbmigrate_bulk_license.php");
}

if(in_array($sysconfig['Release'], $expiredDbReleases))
{
  $sysconfig['Release'] = '3.0.1';
322 323
}

324 325 326 327 328 329 330 331 332 333 334 335 336
// Update '3dfx' licence shortname to 'Glide'. Since shortname is used as an
// identifier, this is not done as part of the licenseref updates.
if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == '3.0.1'))
{
  $dbManager->begin();
  $row = $dbManager->getSingleRow("
    SELECT rf1.rf_pk AS id_3dfx,
           rf2.rf_pk AS id_glide
    FROM license_ref rf1
      INNER JOIN license_ref rf2 USING (rf_fullname)
    WHERE rf1.rf_shortname='3DFX'
      AND rf2.rf_shortname='Glide'
    LIMIT 1", array(), 'old.3dfx.rf_pk');
337
  if (!empty($row))
338 339 340 341 342 343 344 345 346 347 348
  {
    $id_3dfx = intval($row['id_3dfx']);
    $id_glide = intval($row['id_glide']);
    $dbManager->queryOnce("DELETE FROM license_ref WHERE rf_pk=$id_glide");
    $dbManager->queryOnce("UPDATE license_ref SET rf_shortname='Glide' WHERE rf_pk=$id_3dfx");
  }
  $dbManager->commit();

  $sysconfig['Release'] = "3.0.2";
}

349 350 351 352 353 354 355
if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == '3.0.2'))
{
  require_once("$LIBEXECDIR/dbmigrate_multiple_copyright_decisions.php");

  $sysconfig['Release'] = "3.1.0";
}

356 357 358 359 360
// fix release-version datamodel-version missmatch
if($isUpdating && (empty($sysconfig['Release']) || $sysconfig['Release'] == "3.1.0")) {
  $sysconfig['Release'] = "3.3.0";
}

361 362 363 364 365
$dbManager->begin();
$dbManager->getSingleRow("DELETE FROM sysconfig WHERE variablename=$1",array('Release'),$sqlLog='drop.sysconfig.release');
$dbManager->insertTableRow('sysconfig',
        array('variablename'=>'Release','conf_value'=>$sysconfig['Release'],'ui_label'=>'Release','vartype'=>2,'group_name'=>'Release','description'=>''));
$dbManager->commit();
366 367
/* email/url/author data migration to other table */
require_once("$LIBEXECDIR/dbmigrate_copyright-author.php");
368 369 370 371 372 373 374 375 376 377 378
/* sanity check */
require_once ("$LIBEXECDIR/sanity_check.php");
$checker = new SanityChecker($dbManager,$Verbose);
$errors = $checker->check();

if($errors>0)
{
  echo "ERROR: $errors sanity check".($errors>1?'s':'')." failed\n";
}
exit($errors);

379
/**
380
 * \brief insert into license_ref table using json file.
381
 *
382
 * \param $tableName
383
 **/
384
function insertInToLicenseRefTableUsingJson($tableName)
385 386
{
  global $LIBEXECDIR;
387
  global $dbManager;
388 389 390 391 392

  if (!is_dir($LIBEXECDIR)) {
    print "FATAL: Directory '$LIBEXECDIR' does not exist.\n";
    return (1);
  }
393

394 395 396 397 398
  $dir = opendir($LIBEXECDIR);
  if (!$dir) {
    print "FATAL: Unable to access '$LIBEXECDIR'.\n";
    return (1);
  }
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
  $dbManager->begin();
  if ($tableName === 'license_ref_2') {
    $dbManager->queryOnce("DROP TABLE IF EXISTS license_ref_2", $statment = __METHOD__.'.dropAncientBackUp');
    $dbManager->queryOnce("CREATE TABLE license_ref_2 AS SELECT * FROM license_ref WHERE 1=2", $statment = __METHOD__.'.backUpData');
  }
  /** import licenseRef.json */
  $keysToBeChanged = array(
    'rf_OSIapproved' => '"rf_OSIapproved"',
    'rf_FSFfree'=> '"rf_FSFfree"',
    'rf_GPLv2compatible' => '"rf_GPLv2compatible"',
    'rf_GPLv3compatible'=> '"rf_GPLv3compatible"',
    'rf_Fedora' => '"rf_Fedora"'
    );

  $jsonData = json_decode(file_get_contents("$LIBEXECDIR/licenseRef.json"), true);
  $statementName = __METHOD__.'.insertInTo'.$tableName;
  foreach($jsonData as $licenseArrayKey => $licenseArray) {
    $keys = strtr(implode(",", array_keys($licenseArray)), $keysToBeChanged);
    $valuePlaceHolders = "$" . join(",$",range(1, count(array_keys($licenseArray))));
    $SQL = "INSERT INTO $tableName ( $keys ) VALUES ($valuePlaceHolders);";
    $dbManager->prepare($statementName, $SQL);
    $dbManager->execute($statementName, array_values($licenseArray));
  }
  $dbManager->commit();
  return;
}
425

426 427 428 429 430 431 432 433 434 435 436
/**
 * \brief Load the license_ref table with licenses.
 *
 * \param $Verbose display database load progress information.  If $Verbose is false,
 * this function only prints errors.
 *
 * \return 0 on success, 1 on failure
 **/
function initLicenseRefTable($Verbose)
{
  global $dbManager;
437

438 439
  $dbManager->queryOnce("BEGIN");
  insertInToLicenseRefTableUsingJson('license_ref_2');
440 441
  $dbManager->prepare(__METHOD__.".newLic", "select * from license_ref_2");
  $result_new = $dbManager->execute(__METHOD__.".newLic");
442

443
  $dbManager->prepare(__METHOD__.'.licenseRefByShortname','SELECT * from license_ref where rf_shortname=$1');
444
  /** traverse all records in user's license_ref table, update or insert */
445
  while ($row = pg_fetch_assoc($result_new))
446 447 448
  {
    $rf_shortname = $row['rf_shortname'];
    $escaped_name = pg_escape_string($rf_shortname);
449
    $result_check = $dbManager->execute(__METHOD__.'.licenseRefByShortname',array($rf_shortname));
450 451 452 453 454 455 456 457 458 459
    $count = pg_num_rows($result_check);

    $rf_text = pg_escape_string($row['rf_text']);
    $rf_url = pg_escape_string($row['rf_url']);
    $rf_fullname = pg_escape_string($row['rf_fullname']);
    $rf_notes = pg_escape_string($row['rf_notes']);
    $rf_active = $row['rf_active'];
    $marydone = $row['marydone'];
    $rf_text_updatable = $row['rf_text_updatable'];
    $rf_detector_type = $row['rf_detector_type'];
460
    $rf_flag = $row['rf_flag'];
461 462

    if ($count) // update when it is existing
463
    {
464 465 466 467 468 469 470 471 472 473
      $row_check = pg_fetch_assoc($result_check);
      pg_free_result($result_check);
      $rf_text_check = pg_escape_string($row_check['rf_text']);
      $rf_url_check = pg_escape_string($row_check['rf_url']);
      $rf_fullname_check = pg_escape_string($row_check['rf_fullname']);
      $rf_notes_check = pg_escape_string($row_check['rf_notes']);
      $rf_active_check = $row_check['rf_active'];
      $marydone_check = $row_check['marydone'];
      $rf_text_updatable_check = $row_check['rf_text_updatable'];
      $rf_detector_type_check = $row_check['rf_detector_type'];
474
      $rf_flag_check = $row_check['rf_flag'];
475 476

      $sql = "UPDATE license_ref set ";
477
      if ($rf_flag_check == 2 &&  $rf_flag == 1) {
478
        $sql .= " rf_text='$rf_text_check',";
479 480
      } else {
        if ($rf_text_check != $rf_text && !empty($rf_text) && !(stristr($rf_text, 'License by Nomos')))  $sql .= " rf_text='$rf_text', rf_flag='1',";
481
      }
482 483 484 485 486 487 488 489 490
      if ($rf_url_check != $rf_url && !empty($rf_url))  $sql .= " rf_url='$rf_url',";
      if ($rf_fullname_check != $rf_fullname && !empty($rf_fullname))  $sql .= " rf_fullname ='$rf_fullname',";
      if ($rf_notes_check != $rf_notes && !empty($rf_notes))  $sql .= " rf_notes ='$rf_notes',";
      if ($rf_active_check != $rf_active && !empty($rf_active))  $sql .= " rf_active ='$rf_active',";
      if ($marydone_check != $marydone && !empty($marydone))  $sql .= " marydone ='$marydone',";
      if ($rf_text_updatable_check != $rf_text_updatable && !empty($rf_text_updatable))  $sql .= " rf_text_updatable ='$rf_text_updatable',";
      if ($rf_detector_type_check != $rf_detector_type && !empty($rf_detector_type))  $sql .= " rf_detector_type = '$rf_detector_type',";
      $sql = substr_replace($sql ,"",-1);

491
      if ($sql != "UPDATE license_ref set") { // check if have something to update
492
        $sql .= " where rf_shortname = '$escaped_name'";
493
        $dbManager->queryOnce($sql);
494
      }
495
    } else {  // insert when it is new
496
      pg_free_result($result_check);
497
      $sql = "INSERT INTO license_ref (rf_shortname, rf_text, rf_url, rf_fullname, rf_notes, rf_active, rf_text_updatable, rf_detector_type, marydone)"
498 499
              . "VALUES ('$escaped_name', '$rf_text', '$rf_url', '$rf_fullname', '$rf_notes', '$rf_active', '$rf_text_updatable', '$rf_detector_type', '$marydone');";
      $dbManager->queryOnce($sql);
500 501
    }
  }
502 503
  pg_free_result($result_new);

504 505
  $dbManager->queryOnce("DROP TABLE license_ref_2");
  $dbManager->queryOnce("COMMIT");
506

507 508
  return (0);
} // initLicenseRefTable()
509

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

function guessSysconfdir()
{
  $rcfile = "fossology.rc";
  $varfile = dirname(__DIR__).'/variable.list';
  $sysconfdir = getenv('SYSCONFDIR');
  if ((false===$sysconfdir) && file_exists($rcfile))
  {
    $sysconfdir = file_get_contents($rcfile);
  }
  if ((false===$sysconfdir) && file_exists($varfile))
  {
    $ini_array = parse_ini_file($varfile);
    if($ini_array!==false && array_key_exists('SYSCONFDIR', $ini_array))
    {
      $sysconfdir = $ini_array['SYSCONFDIR'];
    }
  }
  if (false===$sysconfdir)
  {
    $text = _("FATAL! System Configuration Error, no SYSCONFDIR.");
    echo "$text\n";
    exit(1);
  }
  return $sysconfdir;
}


538
/**
539
 * \brief Determine SYSCONFDIR, parse fossology.conf
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
 *
 * \param $sysconfdir Typically from the caller's -c command line parameter
 *
 * \return the $SysConf array of values.  The first array dimension
 * is the group, the second is the variable name.
 * For example:
 *  -  $SysConf[DIRECTORIES][MODDIR] => "/mymoduledir/
 *
 * The global $SYSCONFDIR is also set for backward compatibility.
 *
 * \Note Since so many files expect directory paths that used to be in pathinclude.php
 * to be global, this function will define the same globals (everything in the
 * DIRECTORIES section of fossology.conf).
 */
function bootstrap($sysconfdir="")
{
  if (empty($sysconfdir))
  {
558 559
    $sysconfdir = guessSysconfdir();
    echo "assuming SYSCONFDIR=$sysconfdir\n";
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
  }

  $sysconfdir = trim($sysconfdir);
  $GLOBALS['SYSCONFDIR'] = $sysconfdir;

  /*************  Parse fossology.conf *******************/
  $ConfFile = "{$sysconfdir}/fossology.conf";
  if (!file_exists($ConfFile))
  {
    $text = _("FATAL! Missing configuration file: $ConfFile");
    echo "$text\n";
    exit(1);
  }
  $SysConf = parse_ini_file($ConfFile, true);
  if ($SysConf === false)
  {
    $text = _("FATAL! Invalid configuration file: $ConfFile");
    echo "$text\n";
    exit(1);
  }

  /* evaluate all the DIRECTORIES group for variable substitutions.
   * For example, if PREFIX=/usr/local and BINDIR=$PREFIX/bin, we
   * want BINDIR=/usr/local/bin
   */
  foreach($SysConf['DIRECTORIES'] as $var=>$assign)
  {
    $toeval = "\$$var = \"$assign\";";
    eval($toeval);

    /* now reassign the array value with the evaluated result */
    $SysConf['DIRECTORIES'][$var] = ${$var};
    $GLOBALS[$var] = ${$var};
  }

  if (empty($MODDIR))
  {
    $text = _("FATAL! System initialization failure: MODDIR not defined in $SysConf");
598
    echo "$text\n";
599 600 601 602 603
    exit(1);
  }

  //require("i18n.php"); DISABLED until i18n infrastructure is set-up.
  require_once("$MODDIR/lib/php/common.php");
604
  require_once("$MODDIR/lib/php/Plugin/FO_Plugin.php");
605 606
  return $SysConf;
}