export.lib.inc.php 29 KB

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