<?php
// $Id: update_files.inc.php,v 1.61.2.1 2005/12/20 16:03:15 bmol 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
==============================================================================
*/
/**
==============================================================================
* Updates the Dokeos files from an older version
* IMPORTANT: This script has to be included by install/index.php and update_courses.php
*
* DOKEOS_INSTALL is defined in the install/index.php
* DOKEOS_COURSE_UPDATE is defined in update_courses.php
*
* When DOKEOS_INSTALL or DOKEOS_COURSE_UPDATE is defined, do for every course:
* - remove the .htaccess in the document folder
* - remove the index.php in the group folder
* - write a new group/index.php file, make it an empty html file
* - remove the index.php of the course folder
* - write a new index.php file in the course folder, with some settings
* - create a 'temp' directory in the course folder
* - move the course folder inside the courses folder of the new Dokeos installation
* - move the group documents from the group folder to the document folder,
*   keeping subfolders intact
* - stores all documents inside the database (document and item_property tables)
* - remove the visibility field from the document table
* - update the item properties of the group documents
*
* Additionally, when DOKEOS_INSTALL is defined
* - write a config file, claro_main.conf.php, with important settings
* - write a .htaccess file (with instructions for Apache) in the courses directory
* - remove the new claroline/upload/users directory and rename the claroline/img/users
*   directory of the old version to claroline/upload/users
* - rename the old claro_main.conf.php to claro_main.conf.php.old,
*   or if this fails delete the old claro_main.conf.php
*
* @package dokeos.install
==============================================================================
*/

if(defined('DOKEOS_INSTALL') || defined('DOKEOS_COURSE_UPDATE'))
{
	$newPath = str_replace('\\', '/', realpath('../..')).'/';
	$oldPath = $_POST['updatePath'];

	foreach($coursePath as $key => $course)
	{
		$mysql_base_course = $courseDB[$key];

		@unlink($oldPath.$course.'/document/.htaccess');

		@unlink($oldPath.$course.'/group/index.php');

		if($fp = @fopen($oldPath.$course.'/group/index.php', 'w'))
		{
			fputs($fp, '<html></html>');

			fclose($fp);
		}

		@unlink($oldPath.$course.'/index.php');

		if($fp = @fopen($oldPath.$course.'/index.php', 'w'))
		{
			fputs($fp, '<?php
						$cidReq = "'.$key.'";
						$dbname = "'.str_replace($dbPrefixForm, '', $mysql_base_course).'";

						include("../../claroline/course_home/course_home.php");
						?>');

			fclose($fp);
		}

		@mkdir($oldPath.$course.'/temp', 0777);

		@rename($oldPath.$course, $newPath.'courses/'.$course);

		// Move group documents to document folder of the course
		$group_dir = $newPath.'courses/'.$course.'/group';

		if($dir = @opendir($group_dir))
		{
			while(($entry = readdir($dir)) !== false)
			{
				if($entry != '.' && $entry != '..' && is_dir($group_dir.'/'.$entry))
				{
					$from_dir = $group_dir.'/'.$entry;
					$to_dir = $newPath.'courses/'.$course.'/document/'.$entry;

					@rename($from_dir, $to_dir);
				}
			}

			closedir($dir);
		}

		fill_document_table($newPath.'courses/'.$course.'/document');

		mysql_query("ALTER TABLE `$mysql_base_course".$dbGlu."document` DROP `visibility`");

		// Update item_properties of group documents
		$sql = "SELECT d.id AS doc_id, g.id AS group_id FROM `$mysql_base_course".$dbGlu."group_info` g,`$mysql_base_course".$dbGlu."document` d WHERE path LIKE CONCAT(g.secret_directory,'%')";
		$res = mysql_query($sql);

		while($group_doc = mysql_fetch_object($res))
		{
			$sql = "UPDATE `$mysql_base_course".$dbGlu."item_property` SET to_group_id = '".$group_doc->group_id."', visibility = '1' WHERE ref = '".$group_doc->doc_id."' AND tool = '".TOOL_DOCUMENT."'";
			mysql_query($sql);
		}
	}

	if(defined('DOKEOS_INSTALL'))
	{
		$fp = @fopen($newPath.'claroline/inc/conf/claro_main.conf.php', 'w');

		if($fp)
		{
			$stringConfig = str_replace("\r", "", '<?php
# DOKEOS version '.$clarolineVersion.'
# File generated by /install/index.php script - '.date('r').'

/*
==============================================================================
	Dokeos - elearning and course management software

	Copyright (c) 2004-2005 Dokeos S.A.
	Copyright (c) 2003 University of Ghent (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
==============================================================================
*/
/*
==============================================================================
		Configuration of virtual campus

This file contains a list of variables that can be modified by the campus
site administrator. Pay attention when changing these variables, some changes
can cause Dokeos to stop working.
==============================================================================
*/

// mySQL
$dbHost="'.$dbHostForm.'"; // your mysql server
$mysqlServer=$dbHost;
$dbLogin="'.$dbUsernameForm.'"; // your mysql username
$mysqlUser=$dbLogin;
$dbPass="'.str_replace('"', '\"', $dbPassForm).'"; // your mysql password
$mysqlPassword=$dbPass;

$is_trackingEnabled='.trueFalse($enableTrackingForm).';
$singleDbEnabled='.trueFalse($singleDbForm).'; // DO NOT modify this
$courseTablePrefix="'. ($singleDbForm ? 'crs_' : '').'"; // IF NOT EMPTY, can be replaced by another prefix, else leave empty
$dbGlu="'. ($singleDbForm ? '_' : '`.`').'"; // DO NOT modify this
$dbNamePrefix="'.$dbPrefixForm.'"; // prefix all created bases (for courses) with this string
$mysqlPrefix=$dbNamePrefix;

$mainDbName="'.$dbNameForm.'"; // main Dokeos database
$mysqlMainDb=$mainDbName;
$statsDbName="'.$dbStatsForm.'"; // stats Dokeos database
$scormDbName="'.$dbScormForm.'"; // Scorm Dokeos database
$user_personal_database="'.$dbUserForm.'"; // User Personal Database (where all the personal stuff of the user is stored (personal agenda items, course sorting)

// Directories
$rootWeb="'.$urlForm.'";
$urlServer=$rootWeb;
$serverAddress=$rootWeb;
$rootSys="'.str_replace('\\', '/', realpath($pathForm).'/').'";
$webDir=$rootSys;
$urlAppend="'.$urlAppendPath.'";

$clarolineRepositoryAppend="claroline/";
$coursesRepositoryAppend="courses/";
$rootAdminAppend="admin/";

$clarolineRepositorySys=$rootSys.$clarolineRepositoryAppend;
$clarolineRepositoryWeb=$rootWeb.$clarolineRepositoryAppend;
$coursesRepositorySys=$rootSys.$coursesRepositoryAppend;
$coursesRepositoryWeb=$rootWeb.$coursesRepositoryAppend;
$rootAdminSys=$clarolineRepositorySys.$rootAdminAppend;
$rootAdminWeb=$clarolineRepositoryWeb.$rootAdminAppend;

$garbageRepositorySys="'.str_replace("\\", "/", realpath($clarolineRepositorySys."../garbage/")."/").'"; // change this to a place out of web if you can

$mysqlRepositorySys="'.str_replace("\\", "/", realpath($mysqlRepositorySys)."/").'";

$phpMyAdminPath="";

// For new login module
// Uncomment these lines to activate ldap
// $extAuthSource["ldap"]["login"]=$clarolineRepositorySys."auth/ldap/login.php";
// $extAuthSource["ldap"]["newUser"]=$clarolineRepositorySys."auth/ldap/newUser.php";

// General information
$siteName="'.str_replace('"', '\"', $campusForm).'";

$CourseProgram="http://www.ucl.ac.be/etudes/cours";

$administratorSurname="'.str_replace('"', '\"', $adminLastName).'";
$administratorName="'.str_replace('"', '\"', $adminFirstName).'";
$emailAdministrator="'.str_replace('"', '\"', $emailForm).'";
$telephone="'.str_replace('"', '\"', $adminPhoneForm).'";

$administrator["name"]=$administratorName." ".$administratorSurname;
$administrator["phone"]=$telephone;
$administrator["email"]=$emailAdministrator;

$educationManager["name"]="'.str_replace('"', '\"', $educationForm).'";
$educationManager["phone"]="'.str_replace('"', '\"', $educationPhoneForm).'";
$educationManager["email"]="'.str_replace('"', '\"', $educationEmailForm).'";

//$Institution="'.str_replace('"', '\"', $institutionForm).'"; // -> Moved to install_db.inc.php for the AWACS
//$InstitutionUrl="'.str_replace('"', '\"', $institutionUrlForm).'"; // -> Moved to install_db.inc.php for the AWACS

//$institution["name"]=$Institution; // -> no longer in use, can probably be deleted
//$institution["url"]=$InstitutionUrl; // -> no longer in use, can probably be deleted

// Settings for new and future features
$checkEmailByHashSent='.trueFalse($checkEmailByHashSent).';
$ShowEmailnotcheckedToStudent='.trueFalse($ShowEmailnotcheckedToStudent).';
$userMailCanBeEmpty='.trueFalse($userMailCanBeEmpty).';
$userPasswordCrypted='.trueFalse($encryptPassForm).';
$allowSelfReg='.trueFalse($allowSelfReg).';
$allowSelfRegProf='.trueFalse($allowSelfRegProf).';

// General tool options
$enable_student_view=true;
$homepage_view="default"; // "default" gives the default 2 column view
						  // "basic_tools_fixed" gives a 3 column view with the basic tools in fixed position

$color1="#F5F5F5"; // light grey
$color2="#E6E6E6"; // less light grey for bicolored tables

// Available Languages : look at the "lang" directory

$platformLanguage="'.$languageForm.'";
$language=$platformLanguage;

$clarolineVersion="'.$clarolineVersion.'";
$platformVersion=$clarolineVersion;

// Course backup
$dateBackup=date("Y-m-d-H-i-s");
$shortDateBackup=date("YzBs");

$verboseBackup=false;

$archiveDirName="archive";

// security word for password recovery

$security_key="'.md5(uniqid(rand().time())).'";
?>');
			fwrite($fp, $stringConfig);

			fclose($fp);

			$fp = @fopen('../../courses/.htaccess', 'w');

			if($fp)
			{
				$htaccess = '###########################################################################################
#change this file to fit your configuration and save it as .htaccess in the courses folder#
###########################################################################################
#dokeos mod rewrite
#comment lines start with # and are not processed

<IfModule mod_rewrite.c>
RewriteEngine On
Options +FollowSymlinks

#rewrite base is the dir dokeos is installed in with trailing slash
RewriteBase '.$urlAppendPath.'/courses/

#do not rewrite on the claroline dir
#change this path to the path of your claroline folder
RewriteCond %{REQUEST_URI} !^'.$urlAppendPath.'/claroline/

#replace nasty ampersands by 3 slashes, we change it back in download.php
RewriteRule ([^/]+)/document/(.*)&(.*)$ $1/document/$2///$3 [N]
#rewrite everything in the document folder of a course to the download script
RewriteRule ([^/]+)/document/(.*)$ '.$urlAppendPath.'/claroline/document/download.php?doc_url=/$2&cDir=$1 [QSA,L]
</IfModule>';

				fwrite($fp, $htaccess);

				fclose($fp);
			}
			require_once('../inc/lib/fileManage.lib.php');
			// First remove the upload/users directory in the new installation
			removeDir($newPath.'claroline/upload/users');
			// Move the old user images to the new installation
			@rename($oldPath.'claroline/img/users', $newPath.'claroline/upload/users');

			if(!@rename($oldPath.'claroline/inc/conf/claro_main.conf.php', $oldPath.'claroline/inc/conf/claro_main.conf.old.php'))
			{
				unlink($oldPath.'claroline/inc/conf/claro_main.conf.php');
			}
		}
	}
}
else
{
	echo 'You are not allowed here !';
}

/**
* This function puts the documents of the upgraded courses
* into the necessary tables of the new version:
* the document and item_property tables.
*
* @return boolean true if everything worked, false otherwise
*/
function fill_document_table($dir)
{
	global $newPath, $course, $mysql_base_course, $dbGlu;

	$documentPath = $newPath.'courses/'.$course.'/document';

	if(!@$opendir = opendir($dir))
	{
		return false;
	}

	while($readdir = readdir($opendir))
	{
		if($readdir != '..' && $readdir != '.' && $readdir != '.htaccess')
		{
			$path = str_replace($documentPath, '', $dir.'/'.$readdir);
			$file_date = date("Y-m-d H:i:s", filemtime($dir.'/'.$readdir));

			if(is_file($dir.'/'.$readdir))
			{
				$file_size = filesize($dir.'/'.$readdir);

				$result = mysql_query("SELECT id,visibility FROM `$mysql_base_course".$dbGlu."document` WHERE path='".addslashes($path)."' LIMIT 0,1");

				if(list ($id, $visibility) = mysql_fetch_row($result))
				{
					mysql_query("UPDATE `$mysql_base_course".$dbGlu."document` SET filetype='file',title='".addslashes($readdir)."',size='$file_size' WHERE id='$id' AND path='".addslashes($path)."'");
				}
				else
				{
					mysql_query("INSERT INTO `$mysql_base_course".$dbGlu."document`(path,filetype,title,size) VALUES('".addslashes($path)."','file','".addslashes($readdir)."','$file_size')");

					$id = mysql_insert_id();
				}

				$visibility = ($visibility == 'v') ? 1 : 0;

				mysql_query("INSERT INTO `$mysql_base_course".$dbGlu."item_property`(tool,ref,visibility,lastedit_type,to_group_id,insert_date,lastedit_date) VALUES('document','$id','$visibility','DocumentAdded','0','".$file_date."','".$file_date."')");
			}
			elseif(is_dir($dir.'/'.$readdir))
			{
				$result = mysql_query("SELECT id,visibility FROM `$mysql_base_course".$dbGlu."document` WHERE path='".addslashes($path)."' LIMIT 0,1");

				if(list ($id, $visibility) = mysql_fetch_row($result))
				{
					mysql_query("UPDATE `$mysql_base_course".$dbGlu."document` SET filetype='folder',title='".addslashes($readdir)."' WHERE id='$id' AND path='".addslashes($path)."'");
				}
				else
				{
					mysql_query("INSERT INTO `$mysql_base_course".$dbGlu."document`(path,filetype,title) VALUES('".addslashes($path)."','folder','".addslashes($readdir)."')");

					$id = mysql_insert_id();
				}

				$visibility = ($visibility == 'v') ? 1 : 0;

				mysql_query("INSERT INTO `$mysql_base_course".$dbGlu."item_property`(tool,ref,visibility, lastedit_type, to_group_id,insert_date,lastedit_date) VALUES('document','$id','$visibility','FolderCreated','0','".$file_date."','".$file_date."')");

				if(!fill_document_table($dir.'/'.$readdir))
				{
					return false;
				}
			}
		}
	}

	closedir($opendir);

	return true;
}
?>