export.lib.inc.php 29 KB

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