export.lib.inc.php 28 KB

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