<?php // $Id: dropbox_init1.inc.php,v 1.28.2.1 2005/09/12 08:15:19 renehaentjens Exp $
/*
==============================================================================
	Dokeos - elearning and course management software
	
	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 Ghent University (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	
	For a full list of contributors, see "credits.txt".
	The full license can be read in "license.txt".
	
	This program 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.
	
	See the GNU General Public License for more details.
	
	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
	Mail: info@dokeos.com
==============================================================================
*/
/**
==============================================================================
 * Dropbox module for Claroline
 * First initialisation file with initialisation of variables and
 * without outputting anything to browser.
 * 1. Calls claro_init_global.inc.php and lang file
 * 2. Initialises $dropbox_cnf array with all relevant vars
 * 3. Often used functions
 *
 * @version 1.31
 * @copyright 2004-2005
 * @author Jan Bols <jan@ivpv.UGent.be>, main programmer
 * @author Rene Haentjens, severalcontributions <rene.haentjens@UGent.be> (see RH)
 * @author Roan Embrechts, virtual course support
 * @author Patrick Cool <patrick.cool@UGent.be, Dokeos Config Settings (AWACS)
 * @package dokeos.dropbox
==============================================================================
 */

/*
==============================================================================
		INIT SECTION
==============================================================================
*/ 

$langFile = "dropbox";	//name of langfile
$noPHP_SELF = TRUE;	//this var disables the link in the breadcrumps on top of the page

require("../inc/claro_init_global.inc.php");
api_protect_course_script();

/*
-----------------------------------------------------------
	Libraries
-----------------------------------------------------------
*/ 
require(api_get_library_path()."/debug.lib.inc.php");
include_once(api_get_library_path() . "/course.lib.php");
include_once(api_get_library_path() . "/groupmanager.lib.php");

/*
-----------------------------------------------------------
	Virtual course support
-----------------------------------------------------------
*/ 
$user_id = api_get_user_id();
$course_code = $_course['sysCode'];
$course_info = Database::get_course_info_from_code($course_code);
$is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_info);

/**
 * ========================================
 *       Initialises $dropbox_cnf array with all relevant vars
 * ========================================
 *
 * --------------------------------------
 *       DEBUGGING VARS
 * --------------------------------------
 */
$DEBUG = TRUE;

/**
 * --------------------------------------
 *       DATABASE TABLE VARIABLES
 * --------------------------------------
 */
$dropbox_cnf["postTbl"] = $_course["dbNameGlu"] . "dropbox_post";
$dropbox_cnf["fileTbl"] = $_course["dbNameGlu"] . "dropbox_file";
$dropbox_cnf["personTbl"] = $_course["dbNameGlu"] . "dropbox_person";
$dropbox_cnf["introTbl"] = $_course["dbNameGlu"] . "tool_intro";
$dropbox_cnf["userTbl"] = $mainDbName . "`.`user";
$dropbox_cnf["courseUserTbl"] = Database::get_main_table(MAIN_COURSE_USER_TABLE);

/**
 * --------------------------------------
 *       INITIALISE OTHER VARIABLES & CONSTANTS
 * --------------------------------------
 */
$dropbox_cnf["courseId"] = $_cid;
$dropbox_cnf["sysPath"] = api_get_path('SYS_COURSE_PATH') . $_course["path"] . "/dropbox"; //path to dropbox subdir in course containing the uploaded files
$dropbox_cnf["webPath"] = api_get_path('WEB_COURSE_PATH') . $_course["path"] . "/dropbox";
$dropbox_cnf["maxFilesize"] = get_setting("dropbox_max_filesize"); //100 MB file size limit. Other limits maybe imposed in php.ini
//$dropbox_cnf["version"] = "1.3";
$dropbox_cnf["allowOverwrite"] = string_2_boolean(get_setting("dropbox_allow_overwrite"));
$dropbox_cnf["allowJustUpload"] = string_2_boolean(get_setting("dropbox_allow_just_upload"));
$dropbox_cnf["allowStudentToStudent"] = string_2_boolean(get_setting("dropbox_allow_student_to_student"));
$dropbox_cnf["allowGroup"] = string_2_boolean(get_setting("dropbox_allow_group"));

/**
 * --------------------------------------
 * RH:   INITIALISE MAILING VARIABLES
 * --------------------------------------
 */
$dropbox_cnf["allowMailing"] = string_2_boolean(get_setting("dropbox_allow_mailing"));  // false = no mailing functionality
$dropbox_cnf["mailingIdBase"] = 10000000;  // bigger than any user_id,
// allowing enough space for pseudo_ids as uploader_id, dest_user_id, user_id:
// mailing pseudo_id = dropbox_cnf("mailingIdBase") + mailing id
$dropbox_cnf["mailingZipRegexp"] = '/^(.*)(STUDENTID|USERID|LOGINNAME)(.*)\.ZIP$/i';
$dropbox_cnf["mailingWhereSTUDENTID"] = "official_code";
$dropbox_cnf["mailingWhereUSERID"] = "username";
$dropbox_cnf["mailingWhereLOGINNAME"] = "username";
$dropbox_cnf["mailingFileRegexp"] = '/^(.+)\.\w{1,4}$/';

/**
 * ========================================
 *       Get correct langfile
 * ========================================
 * load langfile in .../claroline/dropbox location
 * in case langfile in the .../lang/english/ dir
 * or in case administrator did not update the newest langfile
 *
if (!isset($dropbox_lang['dropbox_version']) || $dropbox_lang['dropbox_version'] != $dropbox_cnf["version"]) {
    require_once( "./dropbox.inc.php");
}
*/

/**
 * ========================================
 *       Often used functions
 * ========================================
 */
/*
* returns username or false if user isn't registered anymore
*/
function getUserNameFromId ( $id)  // RH: Mailing: return 'Mailing ' + id
{
    $mailingId = $id - dropbox_cnf("mailingIdBase");
    if ( $mailingId > 0) return dropbox_lang("mailingAsUsername", "noDLTT") . $mailingId;

    $sql = "SELECT CONCAT(lastname,' ', firstname) AS name
			FROM `" . dropbox_cnf("userTbl") . "`
			WHERE user_id='" . addslashes( $id) . "'";
    $result = api_sql_query($sql,__FILE__,__LINE__);
    $res = mysql_fetch_array( $result);

    if ( $res == FALSE) return FALSE;
    return stripslashes( $res["name"]);
}

/*
* returns loginname or false if user isn't registered anymore
*/
function getLoginFromId ( $id)
{
    $sql = "SELECT username
			FROM `" . dropbox_cnf("userTbl") . "`
			WHERE user_id='" . addslashes( $id) . "'";
    $result =api_sql_query($sql,__FILE__,__LINE__);
    $res = mysql_fetch_array( $result);
    if ( $res == FALSE) return FALSE;
    return stripslashes( $res["username"]);
}

/*
* @return boolean indicating if user with user_id=$user_id is a course member
* @todo eliminate global
*/
function isCourseMember( $user_id)
{
    global $_course;

	$course_code = $_course['sysCode'];
	$course_info = Database::get_course_info_from_code($course_code);
	$is_course_member = CourseManager::is_user_subscribed_in_real_or_linked_course($user_id, $course_info);
	return $is_course_member;
}

/*
* Checks if there are files in the dropbox_file table that aren't used anymore in dropbox_person table.
* If there are, all entries concerning the file are deleted from the db + the file is deleted from the server
*/
function removeUnusedFiles( )
{
    // select all files that aren't referenced anymore
    $sql = "SELECT DISTINCT f.id, f.filename
			FROM `" . dropbox_cnf("fileTbl") . "` f
			LEFT JOIN `" . dropbox_cnf("personTbl") . "` p ON f.id = p.file_id
			WHERE p.user_id IS NULL";
    $result = api_sql_query($sql,__FILE__,__LINE__);
    while ( $res = mysql_fetch_array( $result))
    {
		//delete the selected files from the post and file tables
        $sql = "DELETE FROM `" . dropbox_cnf("postTbl") . "` WHERE file_id='" . $res['id'] . "'";
        $result1 = api_sql_query($sql,__FILE__,__LINE__);
        $sql = "DELETE FROM `" . dropbox_cnf("fileTbl") . "` WHERE id='" . $res['id'] . "'";
        $result1 = api_sql_query($sql,__FILE__,__LINE__);

		//delete file from server
        @unlink( dropbox_cnf("sysPath") . "/" . $res["filename"]);
    }
}

/*
* RH: Mailing (2 new functions)
*
* Mailing zip-file is posted to (dest_user_id = ) mailing pseudo_id
* and is only visible to its uploader (user_id).
*
* Mailing content files have uploader_id == mailing pseudo_id, a normal recipient,
* and are visible initially to recipient and pseudo_id.
*/
function getUserOwningThisMailing($mailingPseudoId, $owner = 0, $or_die = '')
{
    $sql = "SELECT f.uploader_id
			FROM `" . dropbox_cnf("fileTbl") . "` f
			LEFT JOIN `" . dropbox_cnf("postTbl") . "` p ON f.id = p.file_id
			WHERE p.dest_user_id = '" . $mailingPseudoId . "'";
    $result = api_sql_query($sql,__FILE__,__LINE__);

    if (!($res = mysql_fetch_array($result)))
        die(dropbox_lang("generalError")." (code 901)");
    
    if ($owner == 0) return $res['uploader_id'];
    
    if ($res['uploader_id'] == $owner) return TRUE;
    
    die(dropbox_lang("generalError")." (code ".$or_die.")");
}

function removeMoreIfMailing($file_id)
{
    // when deleting a mailing zip-file (posted to mailingPseudoId):
    // 1. the detail window is no longer reachable, so
    //    for all content files, delete mailingPseudoId from person-table
    // 2. finding the owner (getUserOwningThisMailing) is no longer possible, so
    //    for all content files, replace mailingPseudoId by owner as uploader

    $sql = "SELECT p.dest_user_id
			FROM `" . dropbox_cnf("postTbl") . "` p
			WHERE p.file_id = '" . $file_id . "'";
    $result = api_sql_query($sql,__FILE__,__LINE__);

    if ( $res = mysql_fetch_array( $result))
    {
	    $mailingPseudoId = $res['dest_user_id'];
	    if ( $mailingPseudoId > dropbox_cnf("mailingIdBase"))
	    {
	        $sql = "DELETE FROM `" . dropbox_cnf("personTbl") . "` WHERE user_id='" . $mailingPseudoId . "'";
	        $result1 = api_sql_query($sql,__FILE__,__LINE__);
	        
	        $sql = "UPDATE `" . dropbox_cnf("fileTbl") . 
	            "` SET uploader_id='" . api_get_user_id() . "' WHERE uploader_id='" . $mailingPseudoId . "'";
	        $result1 = api_sql_query($sql,__FILE__,__LINE__);
        }
    }
}

/*
* RH: dropbox_lang and dropbox_cnf
*/
function dropbox_lang($variable, $notrans = 'DLTT')
{
    return (get_setting('server_type') == 'test' ?
        get_lang('dropbox_lang["'.$variable.'"]', $notrans) :
        str_replace("\\'", "'", $GLOBALS['dropbox_lang'][$variable]));
}

function dropbox_cnf($variable)
{
    return $GLOBALS['dropbox_cnf'][$variable];
}

?>
