<?php

// user.php - Preferences page
// ------------------------------------------------------------------------
// 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.
// ------------------------------------------------------------------------
// $Id: user.php,v 1.1.1.6 2006/01/25 15:39:34 denis Exp $

include 'include.php';

function delete_vote($bug_id) {
    global $db, $u, $me, $now;
	
    $db->query("delete from ".TBL_BUG_VOTE." where user_id = $u and bug_id = $bug_id");
    header("Location: $me?r=$now");
}

function change_bug_list_columns($column_list) {
    global $db, $u, $t, $HTTP_SESSION_VARS, $STRING;
	
    $HTTP_SESSION_VARS['db_fields'] = $column_list;
    //DEBUG
    //println("A la sauvegarde column_list vaut :");
    //printarray($column_list);
    $column_list = serialize($column_list);
    $db->query("update ".TBL_AUTH_USER." set bug_list_fields = '$column_list' where user_id = $u");
    show_text($STRING['USER_PREF']['ColumnPreferencesSaved']);
}

function change_access_project($access_project) {
    global $db, $u, $t, $HTTP_SESSION_VARS, $STRING;

//    $ProjectPermAdmin = $db->getOne('select perm_id from ' . TBL_AUTH_PERM . " where perm_name ='Admin'");
//    $ProjectPermUser = $db->getOne('select perm_id from ' . TBL_AUTH_PERM . " where perm_name ='Editbug'");
    $old_access_project = $db->getCol("SELECT pp.project_id FROM " . TBL_PROJECT_PERM . " pp, " . TBL_AUTH_PERM . " ap WHERE pp.perm_id<=ap.perm_id AND ap.perm_name='Request' AND pp.user_id=$u"); 
    if (isset($old_access_project) and is_array($old_access_project) and count($old_access_project))
    {}
    else
    {
	    $old_access_project=array();
    }
    if (isset($access_project) and is_array($access_project) and count($access_project)) 
    {
        // Compute differences between old and new
        $remove_from = array_diff($old_access_project, $access_project);
//	printarray($remove_from);
        $add_to = array_diff($access_project, $old_access_project);
        if (count($remove_from)) {
            foreach ($remove_from as $projectid) {
                // print_r( "remove=$user  \\n");
                $db->query('delete pp.* from ' . TBL_PROJECT_PERM . " pp, " . TBL_AUTH_PERM . " ap where pp.project_id = $projectid
					and pp.user_id = $u and pp.perm_id<=ap.perm_id AND ap.perm_name='Request'");
		//println( "last query vaut " . $db->last_query);
		$subject=$STRING['eMail_access_subject_remove'];
		$content=$HTTP_SESSION_VARS['uname'] . $STRING['eMail_access_content_remove'];
		$content.=INSTALL_URL . "/admin/project.php?op=edit&id=$projectid";
		mailtoDomainAdmin($projectid,$subject,$content);
            } 
        } 
        if (count($add_to)) {
            foreach ($add_to as $projectid) 
	    {
		if (DB::isError($db->query("REPLACE INTO " . TBL_PROJECT_PERM . " (project_id, user_id, perm_id) SELECT '$projectid','$u',ap.perm_id 
				FROM " . TBL_AUTH_PERM . " ap WHERE ap.perm_name='Request' ") )) 
		{
			death("DBerror 01","permission attribution failed");
		}
		$subject=$STRING['eMail_access_subject'];
		$content=$HTTP_SESSION_VARS['uname'] . $STRING['eMail_access_content'];
		$content.=INSTALL_URL . "/admin/project.php?op=edit&id=$projectid";
		mailtoDomainAdmin($projectid,$subject,$content);
            } 
        } 
    }
    else
    {
    // User selected nothing,
        $db->query('delete from ' . TBL_PROJECT_PERM . " where user_id = $u and (perm_id=$ProjectPermUser or perm_id=$ProjectPermAdmin)");
    } 


	show_text($STRING['USER_PREF']['access_projectSaved']);
}


function change_password($pass1, $pass2) {
    global $t, $db, $u, $STRING;

    if (!$pass1 = trim($pass1)) {
	$error = $STRING['givepassword'];
    } elseif ($pass1 != $pass2) {
	$error = $STRING['passwordmatch'];
    } else {
	$error = false;
    }

    if ($error) {
	show_preferences_form($error);
	return;
    }

    if (ENCRYPT_PASS) {
	$mpassword = md5($pass1);
    } else {
	$mpassword = $pass1;
    }
	
    $db->query("update ".TBL_AUTH_USER." set password = '$mpassword' where user_id = $u");
    $t->assign('changetext', $STRING['password_changed']);
    $t->wrap('changessaved.html', 'changessaved');
}

// Save changes to a user's preferences
function change_preferences($prefs) {
    global $db, $u, $t, $STRING;

    $updates = array();
    $old_prefs = $db->getRow("select * from ".TBL_USER_PREF." where user_id = $u");

    array_shift($old_prefs); // Drop the user_id field
    $updates = array();
    foreach ($old_prefs as $pref => $val) {
	if (in_array($pref, $prefs) and !$val) {
	    $updates[] = "set $pref = 1";
	} elseif (!in_array($pref, $prefs) and $val) {
	    $updates[] = "set $pref = 0";
	}
    }
    if (count($updates)) {
	$db->query("update ".TBL_USER_PREF.' '.@join(', ', $updates).
	    " where user_id = $u");
    }

    $t->assign('changetext', $STRING['prefs_changed']);
    $t->wrap('changessaved.html', 'changessaved');
}

// Save changes to a user's pageSize
function change_pageSize($prefs) {
    global $db, $u, $t, $STRING ;

    $res = $db->query("update ".TBL_AUTH_USER." set page_size=$prefs where user_id = $u");
if (DB::isError($res)) 
	{
	death("DB ERROR", "01 impossibility to update page_size field in the database, check with your administrator database is updated.<br>" . $res->getMessage());
        } 
	
    $_SESSION['pageSize'] = $prefs;
 
    $t->assign('changetext', $STRING['prefs_changed']);
    $t->wrap('changessaved.html', 'changessaved');
}


function show_preferences_form($error = '') {
    global $t, $all_db_fields, $default_db_fields, $_sv, $db, $u, $STRING, $QUERY, $restricted_projects;

    // Display the votes (if any)
    $t->assign('votes',
	$db->getAll("select * from ".TBL_BUG_VOTE." where user_id = $u"));

    // Display the pageSize (if any)
    $t->assign('def_results',
	$db->getOne("select page_size from ". TBL_AUTH_USER ." where user_id = $u"));

    // Display current preference settings
    $pref_labels = array(
	'email_notices' => $STRING['USER_PREF']['ReceiveNotifications'],
	'saved_queries' => $STRING['USER_PREF']['ShowSavedQueries']
    );
    
    $prefs = $db->getRow("select * from ".TBL_USER_PREF." where user_id = $u");
    foreach ($pref_labels as $pref => $label) {
	$preferences[] = array(
	    'pref' => $pref,
	    'label' => $label,
	    'checked' => $prefs[$pref]
	);
    }
   $sql = sprintf($QUERY['get_valid_project_id_and_name'], $restricted_projects);
   //print $restricted_projects; 
   //print $sql;
   //println("La requête SQL vaut $sql ");
   $res = $db->getAll($sql);
   //println("la valeur du tableau de projet id et name vaut");
   //printarray($res);
   
	//println("valeur des field_name par projet vaut ");
    foreach ($res as $id=>$project) {
		//printarray($project);
		$toto=$project['project_id'];
		$toto2=$project['project_name'];
		$Project_name[$project['project_id']]=$project['project_name'];
		//println("project_id vaut $toto project_name vaut $toto2");
		$sql = sprintf($QUERY['get_project_field'], $project['project_id']);
		$res2 = $db->getCol($sql);


		$mpfile = &new MPFile($project['project_id']);
		$field_conf = $mpfile->project_field_properties;

		$hidden_field_names=array();
		foreach ($field_conf as $FieldName)
		{
			$res = $res[0]; // there should be only one result
			// subproperties
			$prop = & $mpfile->sp_cache[$FieldName['field_name']];
			if ($prop->hidden==true)
			{
				$hidden_field_names[]=$FieldName['title'];
			}
		}
		$res3=array_diff($res2, ($hidden_field_names));

		$field_titles[$project['project_id']]=$res3;
	}

	
//	$access_project = @unserialize($db->getOne('select access_project from ' . TBL_AUTH_USER . " where  user_id = $u")); 
	$t->assign(array(
			'error' => $error,
			'my_fields' => $_sv['db_fields'] ? $_sv['db_fields'] : $default_db_fields,
			'mySelection' => $db->getCol("SELECT pp.project_id FROM " . TBL_PROJECT_PERM . " pp, " . TBL_AUTH_PERM . " ap WHERE pp.perm_id<=ap.perm_id AND ap.perm_name='Request' AND pp.user_id=$u"),
			// 'field_titles' => $all_db_fields,
			'field_titles' => $field_titles,
			'Project_name' => $Project_name,
			'preferences' => $preferences
		)
	);

    $t->wrap('user.html', 'preferences');
}

$perm->check_group('User');

if (isset($_gv['op'])) {
    switch ($_gv['op']) {
	case 'delvote':
	    delete_vote($_gv['bugid']);
	break;
    }
} elseif (isset($_pv['do'])) {
    switch ($_pv['do']) {
	case 'changepassword':
	    change_password($_pv['pass1'], $_pv['pass2']);
	break;
	case 'changecolumnlist':
	    change_bug_list_columns($_pv['column_list']);
	break;
	case 'change_access_project':
	    change_access_project($_pv['access_project']);
	break;
	case 'changeprefs':
	    change_preferences(isset($_pv['preferences']) ? $_pv['preferences'] : array());
	break;
	case 'changePageSize':
	    change_pageSize(isset($_pv['def_results']) ? $_pv['def_results'] : MAX_FILES_PER_PAGE);
	break;
	default:
	    show_preferences_form();
    }
} else {
    show_preferences_form();
}

?>
