export.lib.inc.php 29 KB

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