<?php

// include.php - Set up global variables
// ------------------------------------------------------------------------
// Copyright (c) 2001, 2002 The phpBugTracker Group
// Copyright (c) 2004, 2005 David Han Sze Chuen, Denis Guinnepain for Air Liquide Medical Systems (Taema)
// Copyright (c) 2005, 2006, 2015 Denis Guinnepain
 
// ------------------------------------------------------------------------
// This file is part of Diamentis

// Diamentis is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.

// Diamentis 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 phpBugTracker; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ------------------------------------------------------------------------
error_reporting(0); // hide all warnings

$HTTP_POST_VARS = $_POST;
$HTTP_GET_VARS = $_GET;
$HTTP_SERVER_VARS = $_SERVER;
$HTTP_COOKIE_VARS = $_COOKIE;
$HTTP_ENV_VARS = $_ENV;
$HTTP_POST_FILES = $_FILES;

// _SESSION is the only superglobal which is conditionally set
if (isset($_SESSION))
{
$HTTP_SESSION_VARS = $_SESSION;
} 

//set_include_path(get_include_path().PATH_SEPARATOR.'C:\Development\wamp\www\DiaChange\lib\pear');
$path = "lib";
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
$path = "lib/pear";
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
$path = "lib/Artichow";
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
$path = "phpmyadmin";
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'Artichow.cfg.php';

//DEBUG
ob_start();

ini_set("magic_quotes_runtime", 0);
ini_set("magic_quotes_sybase", 0);

if (!@include('config.php')) {
  header("Location: install.php");
  exit();
}

if (!defined('DB_HOST')) { // Installation hasn't been completed
  header("Location: install.php");
  exit();
}

// Grab the global functions
require_once('inc/functions.php');

// PEAR::DB
define('PEAR_PATH', 'inc/pear/');//'inc/pear/'); // Set this to '' to use system-wide PEAR
require_once(PEAR_PATH.'DB.php');
$dsn = array(
	'phptype' => DB_TYPE,
	'hostspec' => DB_HOST,
	'database' => DB_DATABASE,
	'username' => DB_USER,
	'password' => DB_PASSWORD
	);
$db = DB::Connect($dsn);
if (DB::isError($db)) {
	die($db->message.'<br>'.$db->userinfo);
}
$db->setOption('optimize', 'portability');
$db->setFetchMode(DB_FETCHMODE_ASSOC);
$db->setErrorHandling(PEAR_ERROR_CALLBACK, "handle_db_error");

// Set up the configuration variables
$rs = $db->query('select varname, varvalue from '.TBL_CONFIGURATION);
while (list($k, $v) = $rs->fetchRow(DB_FETCHMODE_ORDERED)) {
  define($k, $v);
}

require_once ('inc/db/'.DB_TYPE.'.php');

// Localization - include the file with the desired language
include 'languages/'.LANGUAGE.'.php';

// get the other classes
require_once("inc/class_MPFile.inc.php");
require_once("inc/class_MPSubProperty.inc.php");

$me = $HTTP_SERVER_VARS['PHP_SELF'];
$selrange = MAX_FILES_PER_PAGE;
$now = time();
$_gv =& $HTTP_GET_VARS;
$_pv =& $HTTP_POST_VARS;
//echo "coucou_";

$all_db_fields = array(
  'bug_id' => $STRING['BUGDISPLAY']['bug_id'],
  'title' => $STRING['BUGDISPLAY']['summary'],
  'description' => $STRING['BUGDISPLAY']['description'],
  'url' => $STRING['BUGDISPLAY']['url'],
  'severity_name' => $STRING['BUGDISPLAY']['severity'],
  'priority' => $STRING['BUGDISPLAY']['priority'],
  'status_name' => $STRING['BUGDISPLAY']['status'],
  'resolution_name' => $STRING['BUGDISPLAY']['resolution'],
  'closed_in_version_name' => $STRING['BUGDISPLAY']['closedinversion'],
  'to_be_closed_in_version_name' => $STRING['BUGDISPLAY']['tobeclosedinversion'],
  'database_name' => $STRING['BUGDISPLAY']['database'],
  'site_name' => $STRING['BUGDISPLAY']['site'],
  'reporter' => $STRING['BUGDISPLAY']['reporter'],
  'owner' => $STRING['BUGDISPLAY']['assignedto'],
  'created_date' => $STRING['BUGDISPLAY']['created'],
  'lastmodifier' => $STRING['BUGDISPLAY']['lastmodifier'],
  'last_modified_date' => $STRING['BUGDISPLAY']['last_modified_date'],
  'project_name' => $STRING['BUGDISPLAY']['project'],
  'version_name' => $STRING['BUGDISPLAY']['version'],
  'component_name' => $STRING['BUGDISPLAY']['component'],
  'os_name' => $STRING['BUGDISPLAY']['os'],
//  'browser_string' => $STRING['BUGDISPLAY']['browser_string'],
  'close_date' => $STRING['BUGDISPLAY']['close_date']
  );

$res=$db->getAll("SELECT perm_name, perm_id FROM " . TBL_AUTH_PERM );
$permValue=array();
foreach ($res as $k=>$v)
{
	$permValue[$res[$k]['perm_name']]=$res[$k]['perm_id'];
}
$default_db_fields = array('bug_id', 'title', 'reporter', 'owner',
  'severity_name', 'priority', 'status_name', 'resolution_name');

// FM398 D.HSC 22/06/2004
// This declaration comes from list_items() in query.php
$query_db_fields = array(
	'bug_id' => 'bug_id',
	'title' => 'title',
	'description' => 'description',
	'url' => 'url',
	'severity_name' => 'severity.severity_name',
	'priority' => 'priority',
	'status_name' => 'status.status_name',
	'resolution_name' => 'resolution_name',
	'reporter' => 'reporter.login as reporter',
	'owner' => 'owner.login as owner',
	'created_date' => 'b.created_date',
	'lastmodifier' => 'lastmodifier.login as last_modifier',
	'last_modified_date' => 'b.last_modified_date',
	'project_name' => 'project.project_name',
	'version_name' => 'version.version_name',
	'to_be_closed_in_version_name' => 'version2.version_name as v2',
	'closed_in_version_name' => 'version3.version_name as v3',
	'database_name' => TBL_DATABASE.'.database_name',
	'site_name' => 'site.site_name',
	'component_name' => 'component.component_name',
	'os_name' => 'os.os_name',
	'browser_string' => 'browser_string',
	'close_date' => 'close_date'
);
// FM398 D.HSC 22/06/2004
// This declaration comes from list_items() in query.php
$db_headers = array(
	'bug_id' => 'bug_id',
	'title' => 'title',
	'description' => 'description',
	'url' => 'url',
	'severity_name' => 'severity.sort_order',
	'priority' => 'b.priority',
	'status_name' => 'status.sort_order',
	'owner' => 'owner',
	'reporter' => 'reporter.login',
	'lastmodifier' => 'last_modifier',
	'created_date' => 'b.created_date',
	'last_modified_date' => 'b.last_modified_date',
	'project_name' => 'project_name',
	'component_name' => 'component_name',
	'version_name' => 'version_name',
	'os_name' => 'os_name',
	'to_be_closed_in_version_name' => 'v2',
	'closed_in_version_name' => 'v3',
	'database_name' => TBL_DATABASE.'.database_name',
	'site_name' => 'site.sort_order',
	'browser_string' => 'browser_string',
	'resolution_name' => 'resolution.sort_order',
	'close_date' => 'close_date'
);

// Template class
if (!@include(SMARTY_PATH . 'Smarty.class.php')) {
	include('templates/default/base/smartymissing.html');
	exit;
}

class extSmarty extends Smarty {
	var $isPopup = false;
	function fetch($_smarty_tpl_file, $_smarty_cache_id = null, $_smarty_compile_id = null, $_smarty_display = false) {
		//error_reporting(E_ALL ^ E_NOTICE); // Clobber Smarty warnings
		error_reporting(0); // hide all warnings
		return Smarty::fetch($_smarty_tpl_file, $_smarty_cache_id, $_smarty_compile_id, $_smarty_display);
	}

	// displays the web page using the given template and the given password
	function wrap($template, $title = '', $isPopup = false) {
		global $TITLE, $_gv, $_pv;

		$this->isPopup = $isPopup;
		$this->assign(array(
			'content_template' => $template,
			'adsense'=> ADSENSE,
		'page_title' => isset($TITLE[$title]) ? $TITLE[$title] : $title
			));

		// Use a popup wrap?
		if ($isPopup or
			(isset($_gv['use_js']) and $_gv['use_js']) or
			(isset($_pv['use_js']) and $_pv['use_js'])) {			
			$wrap = 'wrap-popup.html';
		} else {
			$wrap = 'wrap.html';
		}
		if (($dir = dirname($template)) != '.') {
			$this->display("$dir/$wrap");
		} else {
			$this->display($wrap);
		}
	}
}

$t = new extSmarty;
$t->template_dir = 'templates/'.THEME.'/';
$t->compile_dir = 'c_templates';
$t->config_dir = '.';
$t->use_sub_dirs = false;
$t->register_function('build_select', 'build_select');
$t->register_function('select_file_by_id', 'select_file_by_id');
$t->register_function('build_dynamic_input', 'build_dynamic_input');
// $t->register_function('project_js', 'build_project_js');
$t->register_modifier('date', 'bt_date');
$t->assign(array(
	'STRING' => $STRING,
	'TITLE' => $TITLE,
	'STYLE' => STYLE,
	'ERROR' => $ERROR,
	'PRIMARY_LOGO' => PRIMARY_LOGO,
	'ADMIN_LOGO' => ADMIN_LOGO
	));

	
if (defined('TEMPLATE_PATH')) {
	$t->assign('template_path', '../templates/'.THEME.'/'.TEMPLATE_PATH);
} else {
	$t->assign('template_path', 'templates/'.THEME);
}

// End classes -- Begin page

if (!defined('NO_AUTH')) {
	
	// FM1242 david.han-sze-chuen@airliquide.com 22/07/2004 :
	$cookie_path = '';
	// if DEFAULT_SESSION_COOKIE_PATH is filled, use it
	if (strlen(trim(DEFAULT_SESSION_COOKIE_PATH)) > 0) {
		$cookie_path = DEFAULT_SESSION_COOKIE_PATH;
		//DEBUG
		//println("Cookie path set by DB : $cookie_path");
	} else {
		// try to guess the cookie path
		// ex : INSTALL_URL = http://etude58/MementoTest/memplus_dev
		$res = preg_match('/\/([^\/]+[\/]?)+/i', INSTALL_URL, $matches); // we get $matches[0] = /etude58/MementoTest/memplus_dev
		if ($res) {
			// we have to remove the host name
			$cookie_path = strstr(substr($matches[0], 1), '/'); // => /MementoTest/memplus_dev			
			//DEBUG
			//println("Cookie path set automatically");
		} else death('COOKIE PATH ERROR', 'Unable to define the cookie path.');
	}
	//printarray(session_get_cookie_params());
	//session_set_cookie_params (0, $cookie_path);
	
	/*
	INSERT INTO `phpbt_configuration` ( `varname` , `varvalue` , `description` , `vartype` )
	VALUES (
	'DEFAULT_SESSION_COOKIE_PATH', '/MementoTest/MyMemento/', 'Determines to what extent the session applies on the web server. Default value is "/". <br>For example, if it\'s <i>"/my_site_folder/"</i>. It means that the session range is every php script using session in that folder.', 'string'
	);
	*/
 // session_cache_limiter('private'); 
  session_start();
// _SESSION is the only superglobal which is conditionally set
if (isset($_SESSION))
{
$HTTP_SESSION_VARS = & $_SESSION;
} 
  $_sv =& $HTTP_SESSION_VARS;
//printarray($_sv);
  $auth = new uauth;
  $perm = new uperm;
//printarray($_SESSION);
  $u = isset($_sv['uid']) ? $_sv['uid'] : 0;
}

// Check to see if the user is trying to login
if (isset($_pv['dologin'])) {
  if (!empty($_pv['sendpass'])) {
		$username = $_pv['username'];
    list($email, $password) = $db->getRow("select email, password from ".TBL_AUTH_USER." where login = '{$_pv['username']}' and active > 0", null, DB_FETCHMODE_ORDERED);
    if (!$email) {
      $t->assign('loginerror', '<div class="error">Invalid login</div>');
    } else {
      if (ENCRYPT_PASS) {
        $password = genpassword(10);
        $mpassword = md5($password);
        $db->query("update ".TBL_AUTH_USER." set password = '$mpassword' where login = '$username'");
      }
      qp_mail($email, $STRING['newacctsubject'], sprintf($STRING['newacctmessage'], $password),
        sprintf("From: %s",ADMIN_EMAIL));
      $t->assign('loginerror',
        '<div class="result">Your password has been emailed to you</div>');
			$emailsuccess = true;
    }
  } else {
    if (!$u = $auth->auth_validatelogin()) {
      $t->assign('loginerror', '<div class="error">Invalid login</div>');
			$username = $_pv['username'];
    }
    //DEBUG
		//echo "test B isset exp = " . (isset($HTTP_SESSION_VARS['exp'])? 'true':'false') . '<br>';
		//echo "test B exp = {$HTTP_SESSION_VARS['exp']} <br>";
  }

	// "Remember me" handling
	if (RECALL_LOGIN) {
		if (!empty($_pv["savecookie"])) {
			setcookie('phpbt_user', $_pv["username"], $now + 18144000); // 3 week expiration
			setcookie('phpbt_user_pw', $_pv["password"], $now + 18144000); // 3 week expiration
		} elseif (!empty($HTTP_COOKIE_VARS['phpbt_user'])) {
			// Clear the cookie if the cookie is populated and the box wasn't checked
			setcookie('phpbt_user');
			setcookie('phpbt_user_pw');
		}
	}

}

if (defined('FORCE_LOGIN') and FORCE_LOGIN and !$u and !defined('NO_AUTH')) {
	include('templates/'.THEME.'/login.html');
	exit;
}

$op = isset($_GET['op']) ? $_GET['op'] : (isset($_POST['op']) ? $_POST['op'] : '');

// get the public project_id
// note : the public project_id has become so useful that I put it in a constant.
// TODO : update the code parts where project_id is used
define('PUBLIC_PROJECT_ID', MPFile::getProjectData(null, 'project_id'));
// define open bug status ids ex: "1, 2, 3, ..."
define('OPEN_FILE_STATUS_IDS', join(', ', get_open_status_ids()));
define('CLOSED_FILE_STATUS_IDS', join(', ', get_closed_status_ids()));



if (!defined('NO_AUTH')) {
	// Check to see if we have projects that shouldn't be visible to the user
	$restricted_projects = '0';
	if (!$perm->have_perm('Admin')) {
		$viewable_projects = delimit_list(',',
			$db->getCol($sql="select pg.project_id from ".TBL_PROJECT_GROUP.
				" pg, " . TBL_PROJECT . " p where p.project_id=pg.project_id and p.active<>0 and pg.group_id in (".delimit_list(',', $_sv['group_ids']) .")"));
		$viewable_projects = $viewable_projects ? $viewable_projects : '0';
		$sup_viewable_projects = delimit_list(',',
			$db->getCol($sql="select pp.project_id from " . TBL_PROJECT_PERM . " pp where pp.user_id=$u "));
		if ($sup_viewable_projects) {
			$viewable_projects .= ",$sup_viewable_projects";
		}
		$sup_viewable_projects = delimit_list(',',
			$db->getCol($sql="select p.project_id from " . TBL_PROJECT . " p where p.share_view_all  "));
		if ($sup_viewable_projects) {
			$viewable_projects .= ",$sup_viewable_projects";
		}
		if ($u<>0)
		{
			$sup_viewable_projects = delimit_list(',',
			$db->getCol($sql="select p.project_id from " . TBL_PROJECT . " p where p.share_edit_log  "));
			if ($sup_viewable_projects) {
				$viewable_projects .= ",$sup_viewable_projects";
			}
		}
		$matching_projects = delimit_list(',',
			$db->getCol("select project_id from ".TBL_PROJECT.
				" where project_id not in ($viewable_projects) group by project_id"));
		if ($matching_projects) {
			$restricted_projects .= ",$matching_projects";
		}
	} 
	else
	{
		$viewable_projects=delimit_list(',', $db->getCol("select project_id from " . TBL_PROJECT ));
	}
	$res=$db->getAll("SELECT project_id, parent_project_id FROM " . TBL_PROJECT . " WHERE project_id IN($viewable_projects) ");

	foreach($res as $k => $project)
	{
		$p_id=$project['parent_project_id'];
		$c_id=$project['project_id'];
		$ProjectTree[$c_id]['parent_project_id'][$p_id]=true;
		$ProjectTree[$p_id]['children_project_id'][$c_id]=true;
	}
	//printarray(delimit_list(',',getChildren(1)));
}

//println("viewable projects : $viewable_projects ; restricted projects : $restricted_projects");
if (!defined(MAX_FILES_PER_PAGE)) {
	define('MAX_FILES_PER_PAGE', 30);
}

// here are the known option names
$known_options = array('reserved', 'closed');

// some special system fields should be hidden
$system_hidden_field_names = array('browser_string');
// some shall be always set to read_only
$system_read_only_field_names = array(
	'bug_id', 
	'created_by', 
	'created_date', 
	'last_modified_by', 
	'last_modified_date', 
	'close_date',
	'browser_string'
);

// comparison types
$comparison_option_keys = array(
	'eq', // equal
	'ne', // not equal
	'gt', // greater than
	'lt', // lesser than
	'ge', // greater or equal
	'le', // lesser or equal
	'in', // in an array of values
	'ni'  // not in an array of values	
);
// additional comparison for strings
$comparison_option_for_string_keys = array(
	'like',			// find in the string
	'one_word',	// at least one of the words
	'all_words'  // all words
);

// additional comparison for integer
$comparison_option_for_discret_keys = array(
	'one_element'	// at least one of the elements
);

// primary input array : store all primary input data when search form is submited
$primary_input_array = 'primary_input';
// secondary input array : store all secondary input data when search form is submited
$secondary_input_array = 'secondary_input';
// compare type input array : store all compare type input data when search form is submited
$cmptype_input_array = 'cmptype';
// selected files array of ids : store all selected files' ids. It's used usually in a file list (resulting of a search)
$selected_files_array = 'selected_files';

// some global values in the template
$t->assign('sel', $selected_files_array);
$t->assign('default_text_size', DEFAULT_TEXT_SIZE);
$t->assign('application_name', APPLICATION_NAME);
$t->assign('application_version', APPLICATION_VERSION);
$t->assign('internal_date_format_js', INTERNAL_DATE_FORMAT_JS);
$t->assign('doc_url', DOC_URL);
$t->assign('popup_field_properties_height', 400);
$t->assign('popup_field_properties_width', 550);
$t->assign('perm', $perm);

// NOTE
// You can add javascript libraries by assigning this variable
// $t->assign('include_js', array("inc/func_cookie.js")); // include_js is used in wrap.html
// You can set an action on the page when the user leaves it.
// $t->assign('onUnload', "javascript:treatSelectedFiles();"); // onUnload is used in wrap.html

// the action list of possible actions
$action_list = array(
	'test_action' => 'example_function',
	'send_message' => 'the function name',
	'project_status'  => 'the function name'
);

// build the links at the top of wrap.html
if (!empty($u)) {
	build_common_file_links();
}

// if the user has just selected file ids (in a query result page)
// this time, selected ids comes from a cookie
//if (is_array($_COOKIE['sel']) && (count($_COOKIE['sel']) > 0)) {
	//DEBUG
//	if ($verbose) {
//		println('$_COOKIE[\'sel\']');
//		printarray($_COOKIE['sel']);
//		println("add_selected_file_ids : ");
//	}
//	add_selected_file_ids($_COOKIE['sel'], $verbose);
//}
//delcookie('sel'); // always delete this cookie after its processing

//DEBUG
if ($verbose) {
	echo "\$HTTP_SESSION_VARS <br>";
	printarray($_SESSION);
	echo "<hr>";
	echo "\$_COOKIE <br>";
	printarray($_COOKIE);
	echo "<hr>";
	echo "Session cookie parameters <br>";
	printarray(session_get_cookie_params ());
	echo "<hr>";
	echo "\$HTTP_GET_VARS<br>";
	printarray($_GET);
	echo "<hr>";
	echo "\$HTTP_POST_VARS<br>";
	printarray($_POST);
	echo "<hr>";
	println("\$_FILES");
	printarray($_FILES);
	echo "<hr>";
}
?>