Source for file export.lib.inc.php
Documentation is available at export.lib.inc.php
==============================================================================
Dokeos - elearning and course management software
Copyright (c) 2004-2008 Dokeos SPRL
Copyright (c) 2003 Ghent University (UGent)
Copyright (c) 2001 Universite catholique de Louvain (UCL)
Copyright (c) Olivier Brouckaert
Copyright (c) Bart Mollet, Hogeschool Gent
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, rue du Corbeau, 108, B-1030 Brussels, Belgium, info@dokeos.com
==============================================================================
==============================================================================
* This is the export library for Dokeos.
* Include/require it in your code to use its functionality.
* plusieures fonctions ci-dessous ont �t� adapt�es de fonctions distribu�es par www.nexen.net
* @package dokeos.library
==============================================================================
require_once ('document.lib.php');
* Export tabular data to CSV-file
* @param string $filename
$handle = @fopen($file, 'a+');
foreach ($data as $index => $row)
* Export tabular data to XLS-file
* @param string $filename
$handle = @fopen($file, 'a+');
foreach ($data as $index => $row)
* Export tabular data to XML-file
* @param string $filename
function export_table_xml($data, $filename = 'export', $item_tagname = 'item', $wrapper_tagname = null)
$handle = fopen($file, 'a+');
fwrite($handle, '<?xml version="1.0" encoding="ISO-8859-1"?>'. "\n");
fwrite($handle, "\t". '<'. $wrapper_tagname. '>'. "\n");
foreach ($data as $index => $row)
fwrite($handle, '<'. $item_tagname. '>'. "\n");
foreach ($row as $key => $value)
fwrite($handle, "\t\t". '<'. $key. '>'. $value. '</'. $key. '>'. "\n");
fwrite($handle, "\t". '</'. $item_tagname. '>'. "\n");
fwrite($handle, '</'. $wrapper_tagname. '>'. "\n");
==============================================================================
==============================================================================
* @param ressource $link lien vers la base de donnees
* @param string $db_name nom de la base de donnees
* @param boolean $structure true => sauvegarde de la structure des tables
* @param boolean $donnees true => sauvegarde des donnes des tables
* @param boolean $format format des donnees
'INSERT' => des clauses SQL INSERT
'CSV' => donnees separees par des virgules
* @param boolean $insertComplet true => clause INSERT avec nom des champs
* @param boolean $verbose true => comment are printed
* @deprecated Function only used in deprecated function makeTheBackup(...)
function backupDatabase($link, $db_name, $structure, $donnees, $format = 'SQL', $whereSave = '.', $insertComplet = '', $verbose = false)
GLOBAL $error_msg, $error_no;
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] link is not a ressource";
$error_no["backup"][] = "1";
$filename = $whereSave. "/courseDbContent.". $format;
$fp = fopen($filename, "w");
fwrite($fp, "\nmysql_query(\"");
fwrite($fp, "\n<h2>$tablename</h2><table border=\"1\" width=\"100%\">");
echo "[". $tablename. "] ";
if ($format == "PHP" || $format == "SQL")
fwrite($fp, "DROP TABLE IF EXISTS `$tablename`;");
fwrite($fp, "\nmysql_query(\"");
// requete de creation de la table
$query = "SHOW CREATE TABLE `". $tablename. "`";
if ($format == "PHP" || $format == "SQL")
// les donn�es de la table
$query = "SELECT * FROM $tablename";
if ($insertComplet === true)
for ($j = 0; $j < $num_fields; $j ++ )
$sFieldnames = "(". substr($sFieldnames, 0, - 2). ")";
$sInsert = "INSERT INTO `$tablename` $sFieldnames values ";
$lesDonnees = "\n\t<tr>\n\t\t<td>". implode("\n\t\t</td>\n\t\t<td>", $rowdata). "\n\t\t</td></tr>";
if ($format == "SQL" || $format == "PHP")
$lesDonnees = "<guillemet>". implode("<guillemet>,<guillemet>", $rowdata). "<guillemet>";
$lesDonnees = $sInsert. " ( ". $lesDonnees. " );";
fwrite($fp, "\nmysql_query(\"");
fwrite($fp, "\n</table>\n<hr />\n");
echo "fin du backup au format :". $format;
* @deprecated use function copyDirTo($origDirPath, $destination) in
function copydir($origine, $destination, $verbose = false)
$dossier = @ opendir($origine) or die("<HR>impossible d'ouvrir ". $origine. " [".__LINE__. "]");
echo "<BR> $origine -> $destination";
/* if (file_exists($destination))
echo "la cible existe, ca ne va pas �tre possible";
while ($fichier = readdir($dossier))
if (is_dir($origine. "/". $fichier))
$total += copydir("$origine/$fichier", "$destination/$fichier", $verbose);
copy("$origine/$fichier", "$destination/$fichier");
* Export a course to a zip file
* @param integer $currentCourseID needed sysId Of course to be exported
* @param boolean $verbose_backup def FALSE echo step of work
* @param string $ignore def NONE // future param for selected bloc to export.
* @param string $formats def ALL ALL,SQL,PHP,XML,CSV,XLS,HTML
* @deprecated Function not in use (old backup system)
* 1� Check if all data needed are aivailable
* 2� Build the archive repository tree
* 3� Build exported element and Fill the archive repository tree
== tree structure == == here we can found ==
/archivePath/ temporary files of export for the current claroline
/$exportedCourseId temporary files of export for the current course
/$dateBackuping/ root of the future archive
archive.ini course properties
As we don't know what is add in course by the local admin of claroline,
I prefer follow the logic : save all except ...
function makeTheBackup($exportedCourseId, $verbose_backup = FALSE, $ignore = "", $formats = "ALL")
global $error_msg, $error_no, $db, $archiveRepositorySys, $archiveRepositoryWeb,
$appendCourse, $appendMainDb, $archiveName, $_configuration, $_course, $TABLEUSER, $TABLECOURSUSER, $TABLECOURS, $TABLEANNOUNCEMENT;
// ****** 1� 2. 1 params.needed
if (!isset ($exportedCourseId))
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] Course Id Missing";
$error_no["backup"][] = "1";
if (!isset ($_configuration['main_database']))
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] Main Db name is Missing";
$error_no["backup"][] = "2";
if (!isset ($archiveRepositorySys))
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] archive Path not found";
$error_no["backup"][] = "3";
if (!isset ($appendMainDb))
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] where place course datas from main db in archive";
$error_no["backup"][] = "4";
if (!isset ($appendCourse))
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] where place course datas in archive";
$error_no["backup"][] = "5";
if (!isset ($TABLECOURS))
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] name of table of course not defined";
$error_no["backup"][] = "6";
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] name of table of users not defined";
$error_no["backup"][] = "7";
if (!isset ($TABLECOURSUSER))
$error_msg["backup"][] = "[". basename(__FILE__ ). "][".__LINE__. "] name of table of subscription of users in courses not defined";
$error_no["backup"][] = "8";
// ****** 1� 2. 2 params.optional
if (!isset ($verbose_backup))
// ****** 1� 3. check if course exist
//////////////////////////////////////////////
// ****** 2� Build the archive repository tree
// ****** 2� 1. fix names
$shortDateBackuping = date("YzBs"); // YEAR - Day in Year - Swatch - second
$archiveFileName = "archive.". $exportedCourseId. ".". $shortDateBackuping. ".zip";
$dateBackuping = $shortDateBackuping;
$archiveDir .= $archiveRepositorySys. $exportedCourseId. "/". $shortDateBackuping. "/";
$archiveDirOriginalDocs = $archiveDir. "originalDocs/";
$archiveDirHtml = $archiveDir. "HTML/";
$archiveDirCsv = $archiveDir. "CSV/";
$archiveDirXml = $archiveDir. "XML/";
$archiveDirPhp = $archiveDir. "PHP/";
$archiveDirLog = $archiveDir. "LOG/";
$archiveDirSql = $archiveDir. "SQL/";
$systemFileNameOfArchive = "claroBak-". $exportedCourseId. "-". $dateBackuping. ".txt";
$systemFileNameOfArchiveIni = "archive.ini";
$systemFileNameOfReadMe = "readme.txt";
$systemFileNameOfarchiveLog = "readme.txt";
echo "<hr><u>", get_lang('ArchiveName'), "</u> : ", "<strong>", basename($systemFileNameOfArchive), "</strong><br><u>", get_lang('ArchiveLocation'), "</u> : ", "<strong>", realpath($systemFileNameOfArchive), "</strong><br><u>", get_lang('SizeOf'), " ", realpath("../../". $exportedCourseId. "/"), "</u> : ", "<strong>", DirSize("../../". $exportedCourseId. "/"), "</strong> bytes <br>";
mkpath($archiveDirOriginalDocs. $appendMainDb, $verbose_backup);
mkpath($archiveDirHtml. $appendMainDb, $verbose_backup);
mkpath($archiveDirCsv. $appendMainDb, $verbose_backup);
mkpath($archiveDirXml. $appendMainDb, $verbose_backup);
mkpath($archiveDirPhp. $appendMainDb, $verbose_backup);
mkpath($archiveDirLog. $appendMainDb, $verbose_backup);
mkpath($archiveDirSql. $appendMainDb, $verbose_backup);
mkpath($archiveDirOriginalDocs. $appendCourse, $verbose_backup);
mkpath($archiveDirHtml. $appendCourse, $verbose_backup);
mkpath($archiveDirCsv. $appendCourse, $verbose_backup);
mkpath($archiveDirXml. $appendCourse, $verbose_backup);
mkpath($archiveDirPhp. $appendCourse, $verbose_backup);
mkpath($archiveDirLog. $appendCourse, $verbose_backup);
mkpath($archiveDirSql. $appendCourse, $verbose_backup);
$dirCourBase = $archiveDirSqlCourse;
$dirMainBase = $archiveDirSqlMainDb;
/////////////////////////////////////////////////////////////////////////
// ****** 3� Build exported element and Fill the archive repository tree
// ********************************************************************
// ********************************************************************
+----------------------------------------------------------------------+
Dokeos version ". $dokeos_version. "
+----------------------------------------------------------------------+
+----------------------------------------------------------------------+
| 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 |
// Dokeos Version was : ". $dokeos_version. "
// Source was in ". realpath("../../". $exportedCourseId. "/"). "
// find in ". $archiveDir. "/courseBase/courseBase.sql sql to rebuild the course base
// find in ". $archiveDir. "/". $exportedCourseId. " to content of directory of course
// ********************************************************************
// fields about this course
// ********************************************************************
// ********************************************************************
". get_lang('BUCourseDataOfMainBase'). " ". $exportedCourseId. "
INSERT INTO course SET ";
$iniCourse = "[". $exportedCourseId. "]\n";
$sqlSelectInfoCourse = "Select * from `". $TABLECOURS. "` `course` where code = '". $exportedCourseId. "' ";
$resInfoCourse = api_sql_query($sqlSelectInfoCourse, __FILE__ , __LINE__ );
$sqlInsertCourse .= ", ";
$nameField -> ".$infoCourse["$nameField"]." ";
$sqlInsertCourse .= "$nameField = '". $infoCourse["$nameField"]. "'";
$csvInsertCourse .= "'". addslashes($infoCourse["$nameField"]). "';";
$iniCourse .= "name=". strtr($infoCourse['title'], "()", "[]"). "\n". "official_code=". strtr($infoCourse['visual_code'], "()", "[]"). "\n". // use in echo
"adminCode=". strtr($infoCourse['code'], "()", "[]"). "\n". // use as key in db
"path=". strtr($infoCourse['code'], "()", "[]"). "\n". // use as key in path
"dbName=". strtr($infoCourse['code'], "()", "[]"). "\n". // use as key in db list
"titular=". strtr($infoCourse['titulaire'], "()", "[]"). "\n". "language=". strtr($infoCourse['language'], "()", "[]"). "\n". "extLinkUrl=". strtr($infoCourse['departementUrl'], "()", "[]"). "\n". "extLinkName=". strtr($infoCourse['departementName'], "()", "[]"). "\n". "categoryCode=". strtr($infoCourse['faCode'], "()", "[]"). "\n". "categoryName=". strtr($infoCourse['faName'], "()", "[]"). "\n". "visibility=". ($infoCourse['visibility'] == 2 || $infoCourse['visibility'] == 3). "registrationAllowed=". ($infoCourse['visibility'] == 1 || $infoCourse['visibility'] == 2);
// echo $csvInsertCourse."<BR>";
#------------------------
#------------------------
$fcoursql = fopen($archiveDirSql. $appendMainDb. "course.sql", "w");
fwrite($fcoursql, $sqlInsertCourse);
$fcourcsv = fopen($archiveDirCsv. $appendMainDb. "course.csv", "w");
fwrite($fcourcsv, $csvInsertCourse);
$fcourini = fopen($archiveDir. $systemFileNameOfArchiveIni, "w");
fwrite($fcourini, $iniCourse);
echo $iniCourse, " ini Course";
// ********************************************************************
// ********************************************************************
". get_lang('BUUsersInMainBase'). " ". $exportedCourseId. "
FROM `". $TABLEUSER. "`, `". $TABLECOURSUSER. "`
WHERE `user`.`user_id`=`". $TABLECOURSUSER. "`.`user_id`
AND `". $TABLECOURSUSER. "`.`course_code`='". $exportedCourseId. "'";
$resUsers = api_sql_query($sqlUserOfTheCourse, __FILE__ , __LINE__ );
$htmlInsertUsers = "<table>\t<TR>\n";
for ($noField = 0; $noField < $nbFields; $noField ++ )
$csvInsertUsers .= "'". addslashes($nameField). "';";
$htmlInsertUsers .= "\t\t<TH>". $nameField. "</TH>\n";
$htmlInsertUsers .= "\t</TR>\n";
$htmlInsertUsers .= "\t<TR>\n";
INSERT IGNORE INTO user SET ";
for ($noField = 0; $noField < $nbFields; $noField ++ )
$nameField -> ".$users["$nameField"]." ";
$sqlInsertUsers .= "$nameField = '". $users["$nameField"]. "' ";
$csvInsertUsers .= "'". addslashes($users["$nameField"]). "';";
$htmlInsertUsers .= "\t\t<TD>". $users["$nameField"]. "</TD>\n";
$htmlInsertUsers .= "\t</TR>\n";
$htmlInsertUsers .= "</TABLE>\n";
#------------------------------------------
#------------------------------------------
$fuserssql = fopen($archiveDirSql. $appendMainDb. "users.sql", "w");
fwrite($fuserssql, $sqlInsertUsers);
$fuserscsv = fopen($archiveDirCsv. $appendMainDb. "users.csv", "w");
fwrite($fuserscsv, $csvInsertUsers);
$fusershtml = fopen($archiveDirHtml. $appendMainDb. "users.html", "w");
fwrite($fusershtml, $htmlInsertUsers);
echo "<HR><div align=\"center\">NO user in this course !!!!</div><HR>";
// ********************************************************************
// info about announcment
// ********************************************************************
". get_lang('BUAnnounceInMainBase'). " ". $exportedCourseId. "
$sqlAnnounceOfTheCourse = "
FROM `". $TABLEANNOUNCEMENT. "`
WHERE course_code='". $exportedCourseId. "'";
$resAnn = api_sql_query($sqlAnnounceOfTheCourse, __FILE__ , __LINE__ );
$htmlInsertAnn .= "<table>\t<TR>\n";
for ($noField = 0; $noField < $nbFields; $noField ++ )
$htmlInsertAnn .= "\t\t<TH>". $nameField. "</TH>\n";
$htmlInsertAnn .= "\t</TR>\n";
$htmlInsertAnn .= "\t<TR>\n";
for ($noField = 0; $noField < $nbFields; $noField ++ )
$nameField -> ".$users["$nameField"]." ";
$sqlInsertAnn .= "$nameField = '". addslashes($announce["$nameField"]). "' ";
$csvInsertAnn .= "'". addslashes($announce["$nameField"]). "';";
$htmlInsertAnn .= "\t\t<TD>". $announce["$nameField"]. "</TD>\n";
$htmlInsertAnn .= "\t</TR>\n";
$htmlInsertAnn .= "</TABLE>\n";
#------------------------------------------
#------------------------------------------
$fannsql = fopen($archiveDirSql. $appendMainDb. "annonces.sql", "w");
fwrite($fannsql, $sqlInsertAnn);
$fanncsv = fopen($archiveDirCsv. $appendMainDb. "annnonces.csv", "w");
fwrite($fanncsv, $csvInsertAnn);
$fannhtml = fopen($archiveDirHtml. $appendMainDb. "annonces.html", "w");
fwrite($fannhtml, $htmlInsertAnn);
/* End of backup Annonces */
// we can copy file of course
echo '<li>'. get_lang('CopyDirectoryCourse');
// ". $nbFiles. " was in ". realpath($archiveDirOriginalDocs);
// ********************************************************************
// ********************************************************************
". get_lang('BackupOfDataBase'). " ". $exportedCourseId. " (SQL)
backupDatabase($db, $exportedCourseId, true, true, 'SQL', $archiveDirSql. $appendCourse, true, $verbose_backup);
". get_lang('BackupOfDataBase'). " ". $exportedCourseId. " (PHP)
backupDatabase($db, $exportedCourseId, true, true, 'PHP', $archiveDirPhp. $appendCourse, true, $verbose_backup);
". get_lang('BackupOfDataBase'). " ". $exportedCourseId. " (CSV)
backupDatabase($db, $exportedCourseId, true, true, 'CSV', $archiveDirCsv. $appendCourse, true, $verbose_backup);
". get_lang('BackupOfDataBase'). " ". $exportedCourseId. " (HTML)
backupDatabase($db, $exportedCourseId, true, true, 'HTML', $archiveDirHtml. $appendCourse, true, $verbose_backup);
". get_lang('BackupOfDataBase'). " ". $exportedCourseId. " (XML)
backupDatabase($db, $exportedCourseId, true, true, 'XML', $archiveDirXml. $appendCourse, true, $verbose_backup);
". get_lang('BackupOfDataBase'). " ". $exportedCourseId. " (LOG)
backupDatabase($db, $exportedCourseId, true, true, 'LOG', $archiveDirLog. $appendCourse, true, $verbose_backup);
// ********************************************************************
// ********************************************************************
$fdesc = fopen($archiveDir. $systemFileNameOfArchive, "w");
fwrite($fdesc, $stringConfig);
///////////////////////////////////
// ****** 4� Compress the tree
$whatZip[] = $archiveRepositorySys. $exportedCourseId. "/". $shortDateBackuping. "/HTML";
$forgetPath = $archiveRepositorySys. $exportedCourseId. "/". $shortDateBackuping. "/";
$prefixPath = $exportedCourseId;
$zipCourse = new PclZip($archiveRepositorySys. $archiveFileName);
echo "<font size=\"+1\" color=\"#FF0000\">", $zipCourse->errorInfo(true), "</font>";
for ($i = 0; $i < sizeof($zipRes); $i ++ )
for (reset($zipRes[$i]); $key = key($zipRes[$i]); next($zipRes[$i]))
echo "File $i / [$key] = ". $list[$i][$key]. "<br>";
$pathToArchive = $archiveRepositoryWeb. $archiveFileName;
echo '<hr>'. get_lang('BuildTheCompressedFile');
// removeDir($archivePath);
} // function makeTheBackup()
|