export.lib.inc.php 28 KB

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