export.lib.inc.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. <?php
  2. /*
  3. ==============================================================================
  4. Dokeos - elearning and course management software
  5. Copyright (c) 2004 Dokeos S.A.
  6. Copyright (c) 2003 Ghent University (UGent)
  7. Copyright (c) 2001 Universite catholique de Louvain (UCL)
  8. Copyright (c) Olivier Brouckaert
  9. Copyright (c) Bart Mollet, Hogeschool Gent
  10. For a full list of contributors, see "credits.txt".
  11. The full license can be read in "license.txt".
  12. This program is free software; you can redistribute it and/or
  13. modify it under the terms of the GNU General Public License
  14. as published by the Free Software Foundation; either version 2
  15. of the License, or (at your option) any later version.
  16. See the GNU General Public License for more details.
  17. Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
  18. ==============================================================================
  19. */
  20. /**
  21. ==============================================================================
  22. * This is the export library for Dokeos.
  23. * Include/require it in your code to use its functionality.
  24. *
  25. * plusieures fonctions ci-dessous ont été adaptées de fonctions distribuées par www.nexen.net
  26. *
  27. * @package dokeos.library
  28. ==============================================================================
  29. */
  30. require_once ('document.lib.php');
  31. class Export
  32. {
  33. /**
  34. * Export tabular data to CSV-file
  35. * @param array $data
  36. * @param string $filename
  37. */
  38. function export_table_csv($data, $filename = 'export')
  39. {
  40. $file = api_get_path(SYS_ARCHIVE_PATH).'/'.uniqid('').'.csv';
  41. $handle = fopen($file, 'a+');
  42. foreach ($data as $index => $row)
  43. {
  44. $line = '';
  45. foreach($row as $value)
  46. {
  47. $line .= '"'.str_replace('"','""',$value).'";';
  48. }
  49. fwrite($handle, $line."\n");
  50. }
  51. fclose($handle);
  52. DocumentManager :: file_send_for_download($file, true, $filename.'.csv');
  53. exit;
  54. }
  55. /**
  56. * Export tabular data to XLS-file
  57. * @param array $data
  58. * @param string $filename
  59. */
  60. function export_table_xls($data, $filename = 'export')
  61. {
  62. $file = api_get_path(SYS_ARCHIVE_PATH).'/'.uniqid('').'.xls';
  63. $handle = fopen($file, 'a+');
  64. foreach ($data as $index => $row)
  65. {
  66. fwrite($handle, implode("\t", $row)."\n");
  67. }
  68. fclose($handle);
  69. DocumentManager :: file_send_for_download($file, true, $filename.'.xls');
  70. exit;
  71. }
  72. /**
  73. * Export tabular data to XML-file
  74. * @param array $data
  75. * @param string $filename
  76. */
  77. function export_table_xml($data, $filename = 'export', $item_tagname = 'item', $wrapper_tagname = null)
  78. {
  79. $file = api_get_path(SYS_ARCHIVE_PATH).'/'.uniqid('').'.xml';
  80. $handle = fopen($file, 'a+');
  81. fwrite($handle, '<?xml version="1.0" encoding="ISO-8859-1"?>'."\n");
  82. if (!is_null($wrapper_tagname))
  83. {
  84. fwrite($handle, "\t".'<'.$wrapper_tagname.'>'."\n");
  85. }
  86. foreach ($data as $index => $row)
  87. {
  88. fwrite($handle, '<'.$item_tagname.'>'."\n");
  89. foreach ($row as $key => $value)
  90. {
  91. fwrite($handle, "\t\t".'<'.$key.'>'.$value.'</'.$key.'>'."\n");
  92. }
  93. fwrite($handle, "\t".'</'.$item_tagname.'>'."\n");
  94. }
  95. if (!is_null($wrapper_tagname))
  96. {
  97. fwrite($handle, '</'.$wrapper_tagname.'>'."\n");
  98. }
  99. fclose($handle);
  100. DocumentManager :: file_send_for_download($file, true, $filename.'.xml');
  101. exit;
  102. }
  103. }
  104. /*
  105. ==============================================================================
  106. FUNCTIONS
  107. ==============================================================================
  108. */
  109. /**
  110. * Backup a db to a file
  111. *
  112. * @param ressource $link lien vers la base de donnees
  113. * @param string $db_name nom de la base de donnees
  114. * @param boolean $structure true => sauvegarde de la structure des tables
  115. * @param boolean $donnees true => sauvegarde des donnes des tables
  116. * @param boolean $format format des donnees
  117. 'INSERT' => des clauses SQL INSERT
  118. 'CSV' => donnees separees par des virgules
  119. * @param boolean $insertComplet true => clause INSERT avec nom des champs
  120. * @param boolean $verbose true => comment are printed
  121. * @deprecated Function only used in deprecated function makeTheBackup(...)
  122. */
  123. function backupDatabase($link, $db_name, $structure, $donnees, $format = 'SQL', $whereSave = '.', $insertComplet = '', $verbose = false)
  124. {
  125. $errorCode = "";
  126. if (!is_resource($link))
  127. {
  128. GLOBAL $error_msg, $error_no;
  129. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] link is not a ressource";
  130. $error_no["backup"][] = "1";
  131. return false;
  132. }
  133. mysql_select_db($db_name);
  134. $format = strtolower($format);
  135. $filename = $whereSave."/courseDbContent.".$format;
  136. $format = strtoupper($format);
  137. $fp = fopen($filename, "w");
  138. if (!is_resource($fp))
  139. return false;
  140. // liste des tables
  141. $res = mysql_list_tables($db_name, $link);
  142. $num_rows = mysql_num_rows($res);
  143. $i = 0;
  144. while ($i < $num_rows)
  145. {
  146. $tablename = mysql_tablename($res, $i);
  147. if ($format == "PHP")
  148. fwrite($fp, "\nmysql_query(\"");
  149. if ($format == "HTML")
  150. fwrite($fp, "\n<h2>$tablename</h2><table border=\"1\" width=\"100%\">");
  151. if ($verbose)
  152. echo "[".$tablename."] ";
  153. if ($structure === true)
  154. {
  155. if ($format == "PHP" || $format == "SQL")
  156. fwrite($fp, "DROP TABLE IF EXISTS `$tablename`;");
  157. if ($format == "PHP")
  158. fwrite($fp, "\");\n");
  159. if ($format == "PHP")
  160. fwrite($fp, "\nmysql_query(\"");
  161. // requete de creation de la table
  162. $query = "SHOW CREATE TABLE `".$tablename."`";
  163. $resCreate = mysql_query($query);
  164. $row = mysql_fetch_array($resCreate);
  165. $schema = $row[1].";";
  166. if ($format == "PHP" || $format == "SQL")
  167. fwrite($fp, "$schema");
  168. if ($format == "PHP")
  169. fwrite($fp, "\");\n\n");
  170. }
  171. if ($donnees === true)
  172. {
  173. // les données de la table
  174. $query = "SELECT * FROM $tablename";
  175. $resData = mysql_query($query);
  176. if (mysql_num_rows($resData) > 0)
  177. {
  178. $sFieldnames = "";
  179. if ($insertComplet === true)
  180. {
  181. $num_fields = mysql_num_fields($resData);
  182. for ($j = 0; $j < $num_fields; $j ++)
  183. {
  184. $sFieldnames .= "`".mysql_field_name($resData, $j)."`, ";
  185. }
  186. $sFieldnames = "(".substr($sFieldnames, 0, -2).")";
  187. }
  188. $sInsert = "INSERT INTO `$tablename` $sFieldnames values ";
  189. while ($rowdata = mysql_fetch_assoc($resData))
  190. {
  191. if ($format == "HTML")
  192. {
  193. $lesDonnees = "\n\t<tr>\n\t\t<td>".implode("\n\t\t</td>\n\t\t<td>", $rowdata)."\n\t\t</td></tr>";
  194. }
  195. if ($format == "SQL" || $format == "PHP")
  196. {
  197. $lesDonnees = "<guillemet>".implode("<guillemet>,<guillemet>", $rowdata)."<guillemet>";
  198. $lesDonnees = str_replace("<guillemet>", "'", addslashes($lesDonnees));
  199. if ($format == "SQL")
  200. {
  201. $lesDonnees = $sInsert." ( ".$lesDonnees." );";
  202. }
  203. if ($format == "PHP")
  204. fwrite($fp, "\nmysql_query(\"");
  205. }
  206. fwrite($fp, "$lesDonnees");
  207. if ($format == "PHP")
  208. fwrite($fp, "\");\n");
  209. }
  210. }
  211. }
  212. $i ++;
  213. if ($format == "HTML")
  214. fwrite($fp, "\n</table>\n<hr />\n");
  215. }
  216. echo "fin du backup au format :".$format;
  217. fclose($fp);
  218. }
  219. /**
  220. * @deprecated use function copyDirTo($origDirPath, $destination) in
  221. * fileManagerLib.inc.php
  222. */
  223. function copydir($origine, $destination, $verbose = false)
  224. {
  225. $dossier = @ opendir($origine) or die("<HR>impossible d'ouvrir ".$origine." [".__LINE__."]");
  226. if ($verbose)
  227. echo "<BR> $origine -> $destination";
  228. /* if (file_exists($destination))
  229. {
  230. echo "la cible existe, ca ne va pas être possible";
  231. return 0;
  232. }
  233. */
  234. mkpath($destination, 0770);
  235. if ($verbose)
  236. echo "
  237. <strong>
  238. [".basename($destination)."]
  239. </strong>
  240. <OL>";
  241. $total = 0;
  242. while ($fichier = readdir($dossier))
  243. {
  244. $l = array ('.', '..');
  245. if (!in_array($fichier, $l))
  246. {
  247. if (is_dir($origine."/".$fichier))
  248. {
  249. if ($verbose)
  250. echo "
  251. <LI>";
  252. $total += copydir("$origine/$fichier", "$destination/$fichier", $verbose);
  253. }
  254. else
  255. {
  256. copy("$origine/$fichier", "$destination/$fichier");
  257. if ($verbose)
  258. echo "
  259. <LI>
  260. $fichier";
  261. $total ++;
  262. }
  263. if ($verbose)
  264. echo "
  265. </LI>";
  266. }
  267. }
  268. if ($verbose)
  269. echo "
  270. </OL>";
  271. return $total;
  272. }
  273. /**
  274. * Export a course to a zip file
  275. *
  276. * @param integer $currentCourseID needed sysId Of course to be exported
  277. * @param boolean $verbose_backup def FALSE echo step of work
  278. * @param string $ignore def NONE // future param for selected bloc to export.
  279. * @param string $formats def ALL ALL,SQL,PHP,XML,CSV,XLS,HTML
  280. *
  281. * @deprecated Function not in use (old backup system)
  282. *
  283. * 1° Check if all data needed are aivailable
  284. * 2° Build the archive repository tree
  285. * 3° Build exported element and Fill the archive repository tree
  286. * 4° Compress the tree
  287. == tree structure == == here we can found ==
  288. /archivePath/ temporary files of export for the current claroline
  289. /$exportedCourseId temporary files of export for the current course
  290. /$dateBackuping/ root of the future archive
  291. archive.ini course properties
  292. readme.txt
  293. /originalDocs
  294. /html
  295. /sql
  296. /csv
  297. /xml
  298. /php
  299. ;
  300. about "ignore"
  301. As we don't know what is add in course by the local admin of claroline,
  302. I prefer follow the logic : save all except ...
  303. */
  304. function makeTheBackup($exportedCourseId, $verbose_backup = FALSE, $ignore = "", $formats = "ALL")
  305. {
  306. global $error_msg, $error_no, $db, $archiveRepositorySys, $archiveRepositoryWeb,
  307. $appendCourse, $appendMainDb, $archiveName, $_configuration, $_course, $TABLEUSER, $TABLECOURSUSER, $TABLECOURS, $TABLEANNOUNCEMENT;
  308. // ****** 1° 2. params.
  309. $errorCode = 0;
  310. $stop = FALSE;
  311. // ****** 1° 2. 1 params.needed
  312. if (!isset ($exportedCourseId))
  313. {
  314. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] Course Id Missing";
  315. $error_no["backup"][] = "1";
  316. $stop = TRUE;
  317. }
  318. if (!isset ($_configuration['main_database']))
  319. {
  320. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] Main Db name is Missing";
  321. $error_no["backup"][] = "2";
  322. $stop = TRUE;
  323. }
  324. if (!isset ($archiveRepositorySys))
  325. {
  326. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] archive Path not found";
  327. $error_no["backup"][] = "3";
  328. $stop = TRUE;
  329. }
  330. if (!isset ($appendMainDb))
  331. {
  332. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] where place course datas from main db in archive";
  333. $error_no["backup"][] = "4";
  334. $stop = TRUE;
  335. }
  336. if (!isset ($appendCourse))
  337. {
  338. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] where place course datas in archive";
  339. $error_no["backup"][] = "5";
  340. $stop = TRUE;
  341. }
  342. if (!isset ($TABLECOURS))
  343. {
  344. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] name of table of course not defined";
  345. $error_no["backup"][] = "6";
  346. $stop = TRUE;
  347. }
  348. if (!isset ($TABLEUSER))
  349. {
  350. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] name of table of users not defined";
  351. $error_no["backup"][] = "7";
  352. $stop = TRUE;
  353. }
  354. if (!isset ($TABLECOURSUSER))
  355. {
  356. $error_msg["backup"][] = "[".basename(__FILE__)."][".__LINE__."] name of table of subscription of users in courses not defined";
  357. $error_no["backup"][] = "8";
  358. $stop = TRUE;
  359. }
  360. if ($stop)
  361. {
  362. return false;
  363. }
  364. // ****** 1° 2. 2 params.optional
  365. if (!isset ($verbose_backup))
  366. {
  367. $verbose_backup = false;
  368. }
  369. // ****** 1° 3. check if course exist
  370. // not done
  371. //////////////////////////////////////////////
  372. // ****** 2° Build the archive repository tree
  373. // ****** 2° 1. fix names
  374. $shortDateBackuping = date("YzBs"); // YEAR - Day in Year - Swatch - second
  375. $archiveFileName = "archive.".$exportedCourseId.".".$shortDateBackuping.".zip";
  376. $dateBackuping = $shortDateBackuping;
  377. $archiveDir .= $archiveRepositorySys.$exportedCourseId."/".$shortDateBackuping."/";
  378. $archiveDirOriginalDocs = $archiveDir."originalDocs/";
  379. $archiveDirHtml = $archiveDir."HTML/";
  380. $archiveDirCsv = $archiveDir."CSV/";
  381. $archiveDirXml = $archiveDir."XML/";
  382. $archiveDirPhp = $archiveDir."PHP/";
  383. $archiveDirLog = $archiveDir."LOG/";
  384. $archiveDirSql = $archiveDir."SQL/";
  385. $systemFileNameOfArchive = "claroBak-".$exportedCourseId."-".$dateBackuping.".txt";
  386. $systemFileNameOfArchiveIni = "archive.ini";
  387. $systemFileNameOfReadMe = "readme.txt";
  388. $systemFileNameOfarchiveLog = "readme.txt";
  389. ###################
  390. if ($verbose_backup)
  391. {
  392. 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>";
  393. if (function_exists(diskfreespace))
  394. echo "<u>".get_lang('DiskFreeSpace')."</u> : <strong>".diskfreespace("/")."</strong> bytes";
  395. echo "<hr />";
  396. }
  397. mkpath($archiveDirOriginalDocs.$appendMainDb, $verbose_backup);
  398. mkpath($archiveDirHtml.$appendMainDb, $verbose_backup);
  399. mkpath($archiveDirCsv.$appendMainDb, $verbose_backup);
  400. mkpath($archiveDirXml.$appendMainDb, $verbose_backup);
  401. mkpath($archiveDirPhp.$appendMainDb, $verbose_backup);
  402. mkpath($archiveDirLog.$appendMainDb, $verbose_backup);
  403. mkpath($archiveDirSql.$appendMainDb, $verbose_backup);
  404. mkpath($archiveDirOriginalDocs.$appendCourse, $verbose_backup);
  405. mkpath($archiveDirHtml.$appendCourse, $verbose_backup);
  406. mkpath($archiveDirCsv.$appendCourse, $verbose_backup);
  407. mkpath($archiveDirXml.$appendCourse, $verbose_backup);
  408. mkpath($archiveDirPhp.$appendCourse, $verbose_backup);
  409. mkpath($archiveDirLog.$appendCourse, $verbose_backup);
  410. mkpath($archiveDirSql.$appendCourse, $verbose_backup);
  411. $dirCourBase = $archiveDirSqlCourse;
  412. $dirMainBase = $archiveDirSqlMainDb;
  413. /////////////////////////////////////////////////////////////////////////
  414. // ****** 3° Build exported element and Fill the archive repository tree
  415. if ($verbose_backup)
  416. echo "
  417. build config file
  418. <hr>";
  419. // ********************************************************************
  420. // build config file
  421. // ********************************************************************
  422. $stringConfig = "<?php
  423. /*
  424. +----------------------------------------------------------------------+
  425. Dokeos version ".$dokeos_version."
  426. +----------------------------------------------------------------------+
  427. This file was generate by script ".api_get_self()."
  428. ".date("r")." |
  429. +----------------------------------------------------------------------+
  430. | This program is free software; you can redistribute it and/or |
  431. | modify it under the terms of the GNU General Public License |
  432. | as published by the Free Software Foundation; either version 2 |
  433. */
  434. // Dokeos Version was : ".$dokeos_version."
  435. // Source was in ".realpath("../../".$exportedCourseId."/")."
  436. // find in ".$archiveDir."/courseBase/courseBase.sql sql to rebuild the course base
  437. // find in ".$archiveDir."/".$exportedCourseId." to content of directory of course
  438. /**
  439. * options
  440. ";
  441. $stringConfig .= "
  442. */";
  443. // ********************************************************************
  444. // Copy of from DB main
  445. // fields about this course
  446. // ********************************************************************
  447. // info about cours
  448. // ********************************************************************
  449. if ($verbose_backup)
  450. echo "
  451. <LI>
  452. ".get_lang('BUCourseDataOfMainBase')." ".$exportedCourseId."
  453. <HR>
  454. <PRE>";
  455. $sqlInsertCourse = "
  456. INSERT INTO course SET ";
  457. $csvInsertCourse = "\n";
  458. $iniCourse = "[".$exportedCourseId."]\n";
  459. $sqlSelectInfoCourse = "Select * from `".$TABLECOURS."` `course` where code = '".$exportedCourseId."' ";
  460. $resInfoCourse = api_sql_query($sqlSelectInfoCourse, __FILE__, __LINE__);
  461. $infoCourse = mysql_fetch_array($resInfoCourse);
  462. for ($noField = 0; $noField < mysql_num_fields($resInfoCourse); $noField ++)
  463. {
  464. if ($noField > 0)
  465. $sqlInsertCourse .= ", ";
  466. $nameField = mysql_field_name($resInfoCourse, $noField);
  467. /*echo "
  468. <BR>
  469. $nameField -> ".$infoCourse["$nameField"]." ";
  470. */
  471. $sqlInsertCourse .= "$nameField = '".$infoCourse["$nameField"]."'";
  472. $csvInsertCourse .= "'".addslashes($infoCourse["$nameField"])."';";
  473. }
  474. // buildTheIniFile
  475. $iniCourse .= "name=".strtr($infoCourse['title'], "()", "[]")."\n"."official_code=".strtr($infoCourse['visual_code'], "()", "[]")."\n".// use in echo
  476. "adminCode=".strtr($infoCourse['code'], "()", "[]")."\n".// use as key in db
  477. "path=".strtr($infoCourse['code'], "()", "[]")."\n".// use as key in path
  478. "dbName=".strtr($infoCourse['code'], "()", "[]")."\n".// use as key in db list
  479. "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);
  480. $sqlInsertCourse .= ";";
  481. // echo $csvInsertCourse."<BR>";
  482. $stringConfig .= "
  483. # Insert Course
  484. #------------------------
  485. # ".$sqlInsertCourse."
  486. #------------------------
  487. ";
  488. if ($verbose_backup)
  489. {
  490. echo "</PRE>";
  491. }
  492. $fcoursql = fopen($archiveDirSql.$appendMainDb."course.sql", "w");
  493. fwrite($fcoursql, $sqlInsertCourse);
  494. fclose($fcoursql);
  495. $fcourcsv = fopen($archiveDirCsv.$appendMainDb."course.csv", "w");
  496. fwrite($fcourcsv, $csvInsertCourse);
  497. fclose($fcourcsv);
  498. $fcourini = fopen($archiveDir.$systemFileNameOfArchiveIni, "w");
  499. fwrite($fcourini, $iniCourse);
  500. fclose($fcourini);
  501. echo $iniCourse, " ini Course";
  502. // ********************************************************************
  503. // info about users
  504. // ********************************************************************
  505. // if ($backupUser )
  506. {
  507. if ($verbose_backup)
  508. echo "
  509. <LI>
  510. ".get_lang('BUUsersInMainBase')." ".$exportedCourseId."
  511. <hR>
  512. <PRE>";
  513. // recup users
  514. $sqlUserOfTheCourse = "
  515. SELECT
  516. `user`.*
  517. FROM `".$TABLEUSER."`, `".$TABLECOURSUSER."`
  518. WHERE `user`.`user_id`=`".$TABLECOURSUSER."`.`user_id`
  519. AND `".$TABLECOURSUSER."`.`course_code`='".$exportedCourseId."'";
  520. $resUsers = api_sql_query($sqlUserOfTheCourse, __FILE__, __LINE__);
  521. $nbUsers = mysql_num_rows($resUsers);
  522. if ($nbUsers > 0)
  523. {
  524. $nbFields = mysql_num_fields($resUsers);
  525. $sqlInsertUsers = "";
  526. $csvInsertUsers = "";
  527. $htmlInsertUsers = "<table>\t<TR>\n";
  528. //
  529. // creation of headers
  530. //
  531. for ($noField = 0; $noField < $nbFields; $noField ++)
  532. {
  533. $nameField = mysql_field_name($resUsers, $noField);
  534. $csvInsertUsers .= "'".addslashes($nameField)."';";
  535. $htmlInsertUsers .= "\t\t<TH>".$nameField."</TH>\n";
  536. }
  537. $htmlInsertUsers .= "\t</TR>\n";
  538. //
  539. // creation of body
  540. //
  541. while ($users = mysql_fetch_array($resUsers))
  542. {
  543. $htmlInsertUsers .= "\t<TR>\n";
  544. $sqlInsertUsers .= "
  545. INSERT IGNORE INTO user SET ";
  546. $csvInsertUsers .= "\n";
  547. for ($noField = 0; $noField < $nbFields; $noField ++)
  548. {
  549. if ($noField > 0)
  550. $sqlInsertUsers .= ", ";
  551. $nameField = mysql_field_name($resUsers, $noField);
  552. /*echo "
  553. <BR>
  554. $nameField -> ".$users["$nameField"]." ";
  555. */
  556. $sqlInsertUsers .= "$nameField = '".$users["$nameField"]."' ";
  557. $csvInsertUsers .= "'".addslashes($users["$nameField"])."';";
  558. $htmlInsertUsers .= "\t\t<TD>".$users["$nameField"]."</TD>\n";
  559. }
  560. $sqlInsertUsers .= ";";
  561. $htmlInsertUsers .= "\t</TR>\n";
  562. }
  563. $htmlInsertUsers .= "</TABLE>\n";
  564. $stringConfig .= "
  565. # INSERT Users
  566. #------------------------------------------
  567. # ".$sqlInsertUsers."
  568. #------------------------------------------
  569. ";
  570. $fuserssql = fopen($archiveDirSql.$appendMainDb."users.sql", "w");
  571. fwrite($fuserssql, $sqlInsertUsers);
  572. fclose($fuserssql);
  573. $fuserscsv = fopen($archiveDirCsv.$appendMainDb."users.csv", "w");
  574. fwrite($fuserscsv, $csvInsertUsers);
  575. fclose($fuserscsv);
  576. $fusershtml = fopen($archiveDirHtml.$appendMainDb."users.html", "w");
  577. fwrite($fusershtml, $htmlInsertUsers);
  578. fclose($fusershtml);
  579. }
  580. else
  581. {
  582. if ($verbose_backup)
  583. {
  584. echo "<HR><div align=\"center\">NO user in this course !!!!</div><HR>";
  585. }
  586. }
  587. if ($verbose_backup)
  588. {
  589. echo "</PRE>";
  590. }
  591. }
  592. /* End of backup user */
  593. if ($saveAnnouncement)
  594. {
  595. // ********************************************************************
  596. // info about announcment
  597. // ********************************************************************
  598. if ($verbose_backup)
  599. {
  600. echo "
  601. <LI>
  602. ".get_lang('BUAnnounceInMainBase')." ".$exportedCourseId."
  603. <hR>
  604. <PRE>";
  605. }
  606. // recup annonce
  607. $sqlAnnounceOfTheCourse = "
  608. SELECT
  609. *
  610. FROM `".$TABLEANNOUNCEMENT."`
  611. WHERE course_code='".$exportedCourseId."'";
  612. $resAnn = api_sql_query($sqlAnnounceOfTheCourse, __FILE__, __LINE__);
  613. $nbFields = mysql_num_fields($resAnn);
  614. $sqlInsertAnn = "";
  615. $csvInsertAnn = "";
  616. $htmlInsertAnn .= "<table>\t<TR>\n";
  617. //
  618. // creation of headers
  619. //
  620. for ($noField = 0; $noField < $nbFields; $noField ++)
  621. {
  622. $nameField = mysql_field_name($resUsers, $noField);
  623. $csvInsertAnn .= "'".addslashes($nameField)."';";
  624. $htmlInsertAnn .= "\t\t<TH>".$nameField."</TH>\n";
  625. }
  626. $htmlInsertAnn .= "\t</TR>\n";
  627. //
  628. // creation of body
  629. //
  630. while ($announce = mysql_fetch_array($resAnn))
  631. {
  632. $htmlInsertAnn .= "\t<TR>\n";
  633. $sqlInsertAnn .= "
  634. INSERT INTO users SET ";
  635. $csvInsertAnn .= "\n";
  636. for ($noField = 0; $noField < $nbFields; $noField ++)
  637. {
  638. if ($noField > 0)
  639. $sqlInsertAnn .= ", ";
  640. $nameField = mysql_field_name($resAnn, $noField);
  641. /*echo "
  642. <BR>
  643. $nameField -> ".$users["$nameField"]." ";
  644. */
  645. $sqlInsertAnn .= "$nameField = '".addslashes($announce["$nameField"])."' ";
  646. $csvInsertAnn .= "'".addslashes($announce["$nameField"])."';";
  647. $htmlInsertAnn .= "\t\t<TD>".$announce["$nameField"]."</TD>\n";
  648. }
  649. $sqlInsertAnn .= ";";
  650. $htmlInsertAnn .= "\t</TR>\n";
  651. }
  652. if ($verbose_backup)
  653. {
  654. echo "</PRE>";
  655. }
  656. $htmlInsertAnn .= "</TABLE>\n";
  657. $stringConfig .= "
  658. #INSERT ANNOUNCE
  659. #------------------------------------------
  660. # ".$sqlInsertAnn."
  661. #------------------------------------------
  662. ";
  663. $fannsql = fopen($archiveDirSql.$appendMainDb."annonces.sql", "w");
  664. fwrite($fannsql, $sqlInsertAnn);
  665. fclose($fannsql);
  666. $fanncsv = fopen($archiveDirCsv.$appendMainDb."annnonces.csv", "w");
  667. fwrite($fanncsv, $csvInsertAnn);
  668. fclose($fanncsv);
  669. $fannhtml = fopen($archiveDirHtml.$appendMainDb."annonces.html", "w");
  670. fwrite($fannhtml, $htmlInsertAnn);
  671. fclose($fannhtml);
  672. /* End of backup Annonces */
  673. }
  674. // we can copy file of course
  675. if ($verbose_backup)
  676. {
  677. echo '<li>'.get_lang('CopyDirectoryCourse');
  678. }
  679. $nbFiles = copydir(api_get_path(SYS_COURSE_PATH).$_course['path'], $archiveDirOriginalDocs.$appendCourse, $verbose_backup);
  680. if ($verbose_backup)
  681. echo "
  682. <strong>
  683. ".$nbFiles."
  684. </strong>
  685. ".get_lang('FileCopied')."
  686. <br>
  687. </li>";
  688. $stringConfig .= "
  689. // ".$nbFiles." was in ".realpath($archiveDirOriginalDocs);
  690. // ********************************************************************
  691. // Copy of DB course
  692. // with mysqldump
  693. // ********************************************************************
  694. if ($verbose_backup)
  695. echo "
  696. <LI>
  697. ".get_lang('BackupOfDataBase')." ".$exportedCourseId." (SQL)
  698. <hr>";
  699. backupDatabase($db, $exportedCourseId, true, true, 'SQL', $archiveDirSql.$appendCourse, true, $verbose_backup);
  700. if ($verbose_backup)
  701. echo "
  702. </LI>
  703. <LI>
  704. ".get_lang('BackupOfDataBase')." ".$exportedCourseId." (PHP)
  705. <hr>";
  706. backupDatabase($db, $exportedCourseId, true, true, 'PHP', $archiveDirPhp.$appendCourse, true, $verbose_backup);
  707. if ($verbose_backup)
  708. echo "
  709. </LI>
  710. <LI>
  711. ".get_lang('BackupOfDataBase')." ".$exportedCourseId." (CSV)
  712. <hr>";
  713. backupDatabase($db, $exportedCourseId, true, true, 'CSV', $archiveDirCsv.$appendCourse, true, $verbose_backup);
  714. if ($verbose_backup)
  715. echo "
  716. <LI>
  717. ".get_lang('BackupOfDataBase')." ".$exportedCourseId." (HTML)
  718. <hr>";
  719. backupDatabase($db, $exportedCourseId, true, true, 'HTML', $archiveDirHtml.$appendCourse, true, $verbose_backup);
  720. if ($verbose_backup)
  721. echo "
  722. <LI>
  723. ".get_lang('BackupOfDataBase')." ".$exportedCourseId." (XML)
  724. <hr>";
  725. backupDatabase($db, $exportedCourseId, true, true, 'XML', $archiveDirXml.$appendCourse, true, $verbose_backup);
  726. if ($verbose_backup)
  727. echo "
  728. <LI>
  729. ".get_lang('BackupOfDataBase')." ".$exportedCourseId." (LOG)
  730. <hr>";
  731. backupDatabase($db, $exportedCourseId, true, true, 'LOG', $archiveDirLog.$appendCourse, true, $verbose_backup);
  732. // ********************************************************************
  733. // Copy of DB course
  734. // with mysqldump
  735. // ********************************************************************
  736. $fdesc = fopen($archiveDir.$systemFileNameOfArchive, "w");
  737. fwrite($fdesc, $stringConfig);
  738. fclose($fdesc);
  739. if ($verbose_backup)
  740. echo "
  741. </LI>
  742. </OL>
  743. <br>";
  744. ///////////////////////////////////
  745. // ****** 4° Compress the tree
  746. if (extension_loaded("zlib"))
  747. {
  748. $whatZip[] = $archiveRepositorySys.$exportedCourseId."/".$shortDateBackuping."/HTML";
  749. $forgetPath = $archiveRepositorySys.$exportedCourseId."/".$shortDateBackuping."/";
  750. $prefixPath = $exportedCourseId;
  751. $zipCourse = new PclZip($archiveRepositorySys.$archiveFileName);
  752. $zipRes = $zipCourse->create($whatZip, PCLZIP_OPT_ADD_PATH, $prefixPath, PCLZIP_OPT_REMOVE_PATH, $forgetPath);
  753. if ($zipRes == 0)
  754. {
  755. echo "<font size=\"+1\" color=\"#FF0000\">", $zipCourse->errorInfo(true), "</font>";
  756. }
  757. else
  758. for ($i = 0; $i < sizeof($zipRes); $i ++)
  759. {
  760. for (reset($zipRes[$i]); $key = key($zipRes[$i]); next($zipRes[$i]))
  761. {
  762. echo "File $i / [$key] = ".$list[$i][$key]."<br>";
  763. }
  764. echo "<br>";
  765. }
  766. $pathToArchive = $archiveRepositoryWeb.$archiveFileName;
  767. if ($verbose_backup)
  768. {
  769. echo '<hr>'.get_lang('BuildTheCompressedFile');
  770. }
  771. // removeDir($archivePath);
  772. }
  773. return 1;
  774. } // function makeTheBackup()
  775. ?>