lib.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. <?php
  2. use Cocur\Slugify\Slugify;
  3. require_once 'lib/bootlib.php';
  4. require_once 'lib/vchamilo_plugin.class.php';
  5. function vchamilo_hook_configuration(&$_configuration)
  6. {
  7. global $VCHAMILO;
  8. if (defined('CLI_SCRIPT') && !defined('CLI_VCHAMILO_OVERRIDE')) {
  9. return;
  10. }
  11. // provides an effective value for the virtual root_web based on domain analysis
  12. vchamilo_get_hostname($_configuration);
  13. //$plugin = VChamiloPlugin::create();
  14. // We are on physical chamilo. Let original config play
  15. $virtualChamiloWebRoot = $_configuration['vchamilo_web_root'].'/';
  16. if ($_configuration['root_web'] == $virtualChamiloWebRoot){
  17. $VCHAMILO = 'main';
  18. return;
  19. }
  20. // pre hook to chamilo main table and get alternate configuration.
  21. // sure Database object is not set up. Soo use bootstrap connection
  22. /** @var \Doctrine\DBAL\Connection $connection */
  23. $connection = vchamilo_boot_connection($_configuration);
  24. $table = 'vchamilo';
  25. $query = "SELECT * FROM $table WHERE root_web = '$virtualChamiloWebRoot'";
  26. $result = $connection->executeQuery($query);
  27. $excludes = array('id', 'name');
  28. if ($result->rowCount()) {
  29. $data = $result->fetch();
  30. foreach ($data as $key => $value){
  31. if (!in_array($key, $excludes)){
  32. $_configuration[$key] = $value;
  33. }
  34. $_configuration['virtual'] = $data['root_web'].'/';
  35. $VCHAMILO = $data['root_web'];
  36. }
  37. } else {
  38. //die ("VChamilo : No configuration for this host. May be faked.");
  39. die ("VChamilo : Could not fetch virtual chamilo configuration");
  40. }
  41. }
  42. /**
  43. * @param array $_configuration
  44. */
  45. function vchamilo_get_hostname(&$_configuration)
  46. {
  47. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  48. $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_configuration['force_https_forwarded_proto'])
  49. ) {
  50. $protocol = 'https';
  51. } else {
  52. $protocol = 'http';
  53. }
  54. if (defined('CLI_VCHAMILO_OVERRIDE')) {
  55. $_configuration['vchamilo_web_root'] = CLI_VCHAMILO_OVERRIDE;
  56. $_configuration['vchamilo_name'] = preg_replace('#https?://#', '', CLI_VCHAMILO_OVERRIDE);
  57. // remove radical from override for name
  58. // fake the server signature
  59. global $_SERVER;
  60. $_SERVER['SERVER_NAME'] = $_configuration['vchamilo_name'];
  61. $_SERVER['HTTP_HOST'] = $_configuration['vchamilo_name'];
  62. $_SERVER['QUERY_STRING'] = '';
  63. $_SERVER['REQUEST_URI'] = CLI_VCHAMILO_OVERRIDE;
  64. return;
  65. }
  66. $_configuration['vchamilo_web_root'] = "{$protocol}://".@$_SERVER['HTTP_HOST'];
  67. $_configuration['vchamilo_name'] = @$_SERVER['HTTP_HOST'];
  68. if (empty($_configuration['vchamilo_name'])) { // try again with another source if has failed
  69. $_configuration['vchamilo_name'] = "{$protocol}://".$_SERVER['SERVER_NAME'];
  70. if ($_SERVER['SERVER_PORT'] != 80) {
  71. $_configuration['vchamilo_name'] .= ':'.$_SERVER['SERVER_PORT'];
  72. }
  73. $_configuration['vchamilo_name'] = $_SERVER['SERVER_NAME'];
  74. }
  75. }
  76. /**
  77. * provides a side connection to a vchamilo database
  78. * @param array $vchamilo
  79. * @return a connection
  80. */
  81. function vchamilo_boot_connection(&$_configuration)
  82. {
  83. $dbParams = array(
  84. 'driver' => 'pdo_mysql',
  85. 'host' => $_configuration['db_host'],
  86. 'user' => $_configuration['db_user'],
  87. 'password' => $_configuration['db_password'],
  88. 'dbname' => isset($_configuration['main_database']) ? $_configuration['main_database'] : '',
  89. // Only relevant for pdo_sqlite, specifies the path to the SQLite database.
  90. 'path' => isset($_configuration['db_path']) ? $_configuration['db_path'] : '',
  91. // Only relevant for pdo_mysql, pdo_pgsql, and pdo_oci/oci8,
  92. 'port' => isset($_configuration['db_port']) ? $_configuration['db_port'] : ''
  93. );
  94. try {
  95. $database = new \Database();
  96. $connection = $database->connect($dbParams, $_configuration['root_sys'], $_configuration['root_sys'], true);
  97. } catch (Exception $e) {
  98. echo('Side connection failure with '.$_configuration['db_host'].', '.$_configuration['db_user'].', ******** ');
  99. die();
  100. }
  101. return $connection;
  102. }
  103. function vchamilo_redirect($url) {
  104. if (preg_match('#https?://#', $url)) {
  105. header('location: '.$url);
  106. } else {
  107. header('location: ' . api_get_path(WEB_PATH).$url);
  108. }
  109. exit;
  110. }
  111. function vchamilo_get_htaccess_fragment($course_folder)
  112. {
  113. $str = "
  114. # Change this file to fit your configuration and save it as .htaccess in the courses folder #
  115. # Chamilo mod rewrite
  116. # Comment lines start with # and are not processed
  117. <IfModule mod_rewrite.c>
  118. RewriteEngine On
  119. # Rewrite base is the dir chamilo is installed in with trailing slash
  120. RewriteBase /{$course_folder}/
  121. # Do not rewrite on the main dir
  122. # Change this path to the path of your main folder
  123. RewriteCond %{REQUEST_URI} !^/main/
  124. #replace nasty ampersands by 3 slashes, we change these back in download.php
  125. RewriteRule ([^/]+)/document/(.*)&(.*)$ $1/document/$2///$3 [N]
  126. # Rewrite everything in the scorm folder of a course to the download script
  127. RewriteRule ([^/]+)/scorm/(.*)$ /main/document/download_scorm.php?doc_url=/$2&cDir=$1 [QSA,L]
  128. # Rewrite everything in the document folder of a course to the download script
  129. RewriteRule ([^/]+)/document/(.*)$ /main/document/download.php?doc_url=/$2&cDir=$1 [QSA,L]
  130. # Rewrite everything in the work folder
  131. RewriteRule ([^/]+)/work/(.*)$ /main/work/download.php?file=work/$2&cDir=$1 [QSA,L]
  132. </IfModule>
  133. ";
  134. }
  135. function vchamilo_get_default_course_index_fragment() {
  136. return "<html><head></head><body></body></html>";
  137. }
  138. function vchamilo_template_exists($template) {
  139. global $_configuration;
  140. // Find and checktemplate directory (files and SQL).
  141. $separator = DIRECTORY_SEPARATOR;
  142. $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
  143. $absolute_templatesdir = $_configuration['root_sys'].$templatefoldername;
  144. $relative_datadir = $templatefoldername.$separator.$template.'_sql';
  145. $absolute_datadir = $_configuration['root_sys'].$relative_datadir;
  146. return is_dir($absolute_datadir);
  147. }
  148. /**
  149. * drop a vchamilo instance databases using the physical connection
  150. * @param object $vchamilo
  151. * @param handle $side_cnx
  152. * return an array of errors or false if ok
  153. */
  154. function vchamilo_drop_databases(&$vchamilo)
  155. {
  156. global $plugininstance;
  157. if (is_array($vchamilo)) $vchamilo = (object)$vchamilo;
  158. // Drop databases you need to drop
  159. $sqls = array(" DROP DATABASE `{$vchamilo->main_database}` ");
  160. if (!empty($vchamilo->statistics_database) && ($vchamilo->main_database != $vchamilo->statistics_database)) {
  161. $sqls[] = " DROP DATABASE `{$vchamilo->statistics_database}` ";
  162. };
  163. if (!empty($vchamilo->user_personal_database) && ($vchamilo->user_personal_database != $vchamilo->statistics_database) && ($vchamilo->main_database != $vchamilo->user_personal_database)) {
  164. $sqls[] = " DROP DATABASE `{$vchamilo->user_personal_database}` ";
  165. }
  166. foreach($sqls as $sql){
  167. $res = Database::query($sql);
  168. if (!$res){
  169. $erroritem = new StdClass();
  170. $erroritem->message = $plugininstance->get_lang('couldnotdropdb');
  171. $erroritem->on = 'db';
  172. $erroritems[] = $erroritem;
  173. }
  174. }
  175. if (!empty($erroritems)){
  176. return $erroritems;
  177. }
  178. return false;
  179. }
  180. /**
  181. * Create all needed databases.
  182. * @uses $CFG The global configuration.
  183. * @param $vmoodledata object All the Host_form data.
  184. * @param $outputfile array The variables to inject in setup template SQL.
  185. * @return bool If TRUE, loading database from template was sucessful, otherwise FALSE.
  186. */
  187. function vchamilo_create_databases($vchamilo)
  188. {
  189. // availability of SQL commands
  190. $createstatement = 'CREATE DATABASE %DATABASE% DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ';
  191. $dbs = array($vchamilo->main_database);
  192. foreach($dbs as $adb){
  193. Display::addFlash(Display::return_message("Creating DB $adb"));
  194. $sql = str_replace('%DATABASE%', $adb, $createstatement);
  195. Database::query($sql);
  196. /*if(!$DB->execute_sql($sql)){
  197. print_error('noexecutionfor','block_vmoodle', $sql);
  198. return false;
  199. }*/
  200. }
  201. return true;
  202. }
  203. /**
  204. * get a proper SQLdump command
  205. * @param object $vmoodledata the complete new host information
  206. * @return string the shell command
  207. */
  208. function vchamilo_get_database_dump_cmd($vchamilodata)
  209. {
  210. global $CFG;
  211. $pgm = vchamilo_get_config('mysql_cmd');
  212. // Checks the needed program.
  213. Display::addFlash(Display::return_message("load_database_from_dump : checking database command"));
  214. if (!$pgm){
  215. $pgm = '/usr/bin/mysql';
  216. Display::addFlash(Display::return_message("Using default database command $pgm "));
  217. }
  218. $phppgm = str_replace("\\", '/', $pgm);
  219. $phppgm = str_replace("\"", '', $phppgm);
  220. $pgm = str_replace("/", DIRECTORY_SEPARATOR, $pgm);
  221. Display::addFlash(Display::return_message('load_database_from_dump : checking command is available'));
  222. if (!is_executable($phppgm)){
  223. print_error('databasecommanddoesnotmatchanexecutablefile');
  224. return false;
  225. }
  226. // Retrieves the host configuration (more secure).
  227. $vchamilodata = vchamilo_make_this();
  228. if (strstr($vchamilodata->db_host, ':') !== false){
  229. list($vchamilodata->db_host, $vchamilodata->db_port) = split(':', $vchamilodata->db_host);
  230. }
  231. // Password.
  232. if (!empty($vchamilodata->db_password)){
  233. $vchamilodata->db_password = '-p'.escapeshellarg($vchamilodata->db_password).' ';
  234. }
  235. // Making the command line (see 'vconfig.php' file for defining the right paths).
  236. $sqlcmd = $pgm.' -h'.$vchamilodata->db_host.(isset($vchamilodata->db_port) ? ' -P'.$vchamilodata->db_port.' ' : ' ' );
  237. $sqlcmd .= '-u'.$vchamilodata->db_user.' '.$vchamilodata->db_password;
  238. $sqlcmd .= '%DATABASE% < ';
  239. return $sqlcmd;
  240. }
  241. function vchamilo_load_db_template($vchamilo, $dbtemplate, $template){
  242. global $_configuration;
  243. // Make template directory (files and SQL).
  244. $separator = DIRECTORY_SEPARATOR;
  245. $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
  246. $absolute_templatesdir = $_configuration['root_sys'].$templatefoldername;
  247. $relative_datadir = $templatefoldername.$separator.$template.'_sql';
  248. $absolute_datadir = $_configuration['root_sys'].$relative_datadir;
  249. $filerad = preg_replace('/_database$/', '', $dbtemplate);
  250. $sqlfile = 'chamilo_master_'.$filerad.'.sql';
  251. if (!$sqlcmd = vchamilo_get_database_dump_cmd($vchamilo)){
  252. return false;
  253. }
  254. $sqlcmd = str_replace('%DATABASE%', $vchamilo->$dbtemplate, $sqlcmd);
  255. // Make final commands to execute, depending on the database type.
  256. $import = $sqlcmd.$absolute_datadir.'/'.$sqlfile;
  257. // Execute the command.
  258. Display::addFlash(Display::return_message("load_database_from_dump : executing feeding sql as \n $import "));
  259. if (!defined('CLI_SCRIPT')){
  260. putenv('LANG=en_US.utf-8');
  261. }
  262. // ensure utf8 is correctly handled by php exec()
  263. // @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input
  264. exec($import, $output, $return);
  265. Display::addFlash(Display::return_message(implode("\n", $output)."\n"));
  266. return true;
  267. }
  268. /**
  269. * load a bulk sql in database that is given through a vchamilo configuration record.
  270. * @param object $vchamilo
  271. * @param string $bulfile a bulk file of queries to process on the database
  272. * @param handle $cnx
  273. * @param array $vars an array of vars to inject in the bulk file before processing
  274. */
  275. function vchamilo_execute_db_sql(&$vchamilo, $bulkfile, $cnx = null, $vars=null, $filter=null){
  276. global $_configuration;
  277. if (file_exists($bulkfile)){
  278. $erroritem = new StdClass();
  279. $erroritem->message = "vchamilo_load_db_template : Bulk file $bulkfile not found";
  280. $erroritems[] = $erroritem;
  281. return $erroritem;
  282. }
  283. $local_cnx = 0;
  284. if (is_null($cnx)){
  285. $cnx = vchamilo_make_connection($vchamilo, true);
  286. $local_cnx = 1;
  287. }
  288. /// get dump file
  289. $sql = file($bulkfile);
  290. // converts into an array of text lines
  291. $dumpfile = implode('', $sql);
  292. if ($filter){
  293. foreach($filter as $from => $to){
  294. $dumpfile = mb_ereg_replace(preg_quote($from), $to, $dumpfile);
  295. }
  296. }
  297. // insert any external vars
  298. if (!empty($vars)){
  299. foreach($vars as $key => $value){
  300. // for debug : echo "$key => $value";
  301. $dumpfile = str_replace("<%%$key%%>", $value, $dumpfile);
  302. }
  303. }
  304. $sql = explode ("\n", $dumpfile);
  305. // cleanup unuseful things
  306. $sql = preg_replace("/^--.*/", "", $sql);
  307. $sql = preg_replace("/^\/\*.*/", "", $sql);
  308. $dumpfile = implode("\n", $sql);
  309. /// split into single queries
  310. $dumpfile = str_replace("\r\n", "\n", $dumpfile); // translates to Unix LF
  311. $queries = preg_split("/;\n/", $dumpfile);
  312. /// feed queries in database
  313. $i = 0;
  314. $j = 0;
  315. $l = 0;
  316. if (!empty($queries)){
  317. foreach($queries as $query){
  318. $query = trim($query); // get rid of trailing spaces and returns
  319. if ($query == '') continue; // avoid empty queries
  320. $query = mb_convert_encoding($query, 'iso-8859-1', 'auto');
  321. if (!$res = vchamilo_execute_query($vchamilo, $query, $cnx)){
  322. $erroritem = new StdClass();
  323. $erroritem->message = "vchamilo_load_db_template : Load error on query $l";
  324. $erroritem->content = $query;
  325. $erroritems[] = $erroritem;
  326. $j++;
  327. } else {
  328. $i++;
  329. }
  330. $l++;
  331. }
  332. }
  333. echo "loaded : $i queries succeeded, $j queries failed<br/>";
  334. if ($local_cnx){
  335. vchamilo_close_connection($vchamilo, $cnx);
  336. }
  337. if (!empty($erroritems)){
  338. return $erroritems;
  339. }
  340. return false;
  341. }
  342. /**
  343. * Dumps a SQL database for having a snapshot.
  344. * @param $vchamilo object The Vchamilo object.
  345. * @param $outputfilerad string The output SQL file radical.
  346. * @return bool If TRUE, dumping database was a success, otherwise FALSE.
  347. */
  348. function vchamilo_dump_databases($vchamilo, $outputfilerad)
  349. {
  350. // Separating host and port, if sticked.
  351. if (strstr($vchamilo->db_host, ':') !== false){
  352. list($host, $port) = split(':', $vchamilo->db_host);
  353. } else {
  354. $host = $vchamilo->db_host;
  355. }
  356. // By default, empty password.
  357. $pass = '';
  358. $pgm = null;
  359. if (empty($port)) {
  360. $port = 3306;
  361. }
  362. // Password.
  363. if (!empty($vchamilo->db_password)) {
  364. $pass = "-p".escapeshellarg($vchamilo->db_password);
  365. }
  366. // Making the commands for each database.
  367. $cmds = array();
  368. //if ($CFG->ostype == 'WINDOWS') {
  369. if (false) {
  370. $cmd_main = "-h{$host} -P{$port} -u{$vchamilo->db_user} {$pass} {$vchamilo->main_database}";
  371. $cmds[] = $cmd_main . ' > ' . $outputfilerad;
  372. } else {
  373. $cmd_main = "-h{$host} -P{$port} -u{$vchamilo->db_user} {$pass} {$vchamilo->main_database}";
  374. $cmds[] = $cmd_main . ' > ' . escapeshellarg($outputfilerad);
  375. }
  376. $mysqldumpcmd = vchamilo_get_config('vchamilo', 'cmd_mysqldump', true);
  377. $pgm = !empty($mysqldumpcmd) ? stripslashes($mysqldumpcmd) : false ;
  378. if (!$pgm) {
  379. $erroritem = new StdClass();
  380. $erroritem->message = "Database dump command not available check here: ";
  381. $url = api_get_path(WEB_CODE_PATH).'admin/configure_plugin.php?name=vchamilo';
  382. $erroritem->message .= Display::url($url, $url);
  383. return array($erroritem);
  384. } else {
  385. $phppgm = str_replace("\\", '/', $pgm);
  386. $phppgm = str_replace("\"", '', $phppgm);
  387. $pgm = str_replace('/', DIRECTORY_SEPARATOR, $pgm);
  388. if (!is_executable($phppgm)){
  389. $erroritem = new StdClass();
  390. $erroritem->message = "Database dump command $phppgm does not match any executable";
  391. return array($erroritem);
  392. }
  393. // executing all commands
  394. foreach($cmds as $cmd){
  395. // Final command.
  396. $cmd = $pgm.' '.$cmd;
  397. // Prints log messages in the page and in 'cmd.log'.
  398. /*if ($LOG = fopen(dirname($outputfilerad).'/cmd.log', 'a')){
  399. fwrite($LOG, $cmd."\n");
  400. }*/
  401. // Executes the SQL command.
  402. exec($cmd, $execoutput, $returnvalue);
  403. /*if ($LOG){
  404. foreach($execoutput as $execline) fwrite($LOG, $execline."\n");
  405. fwrite($LOG, $returnvalue."\n");
  406. fclose($LOG);
  407. }*/
  408. }
  409. }
  410. // End with success.
  411. return 0;
  412. }
  413. /**
  414. * read manifest values in vchamilo template.
  415. * @uses $CFG
  416. */
  417. function vchamilo_get_vmanifest($version)
  418. {
  419. include(api_get_path(SYS_PATH, SYS_PATH).'/plugin/vchamilo/templates/'.$version.'_sql/manifest.php');
  420. $manifest->templatewwwroot = $templatewwwroot;
  421. $manifest->templatevdbprefix = $templatevdbprefix;
  422. $manifest->coursefolder = $coursefolder;
  423. return $manifest;
  424. }
  425. /**
  426. * make a fake vchamilo that represents the current host
  427. */
  428. function vchamilo_make_this()
  429. {
  430. global $_configuration;
  431. $thisPortal = new stdClass();
  432. $thisPortal->root_web = $_configuration['root_web'];
  433. $thisPortal->db_host = $_configuration['db_host'];
  434. $thisPortal->db_user = $_configuration['db_user'];
  435. $thisPortal->db_password = $_configuration['db_password'];
  436. $thisPortal->main_database = $_configuration['main_database'];
  437. return $thisPortal;
  438. }
  439. /**
  440. * Get available templates for defining a new virtual host.
  441. * @return array The availables templates, or EMPTY array.
  442. */
  443. function vchamilo_get_available_templates()
  444. {
  445. global $_configuration;
  446. global $plugininstance;
  447. $separator = DIRECTORY_SEPARATOR;
  448. $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
  449. $absolute_templatesdir = $_configuration['root_sys'].$templatefoldername;
  450. // Scans the templates.
  451. if (!is_dir($absolute_templatesdir)){
  452. mkdir($absolute_templatesdir, 0777, true);
  453. }
  454. $dirs = glob($absolute_templatesdir.'/*');
  455. $vtemplates = preg_grep("/[^\/](.*)_vchamilodata$/", $dirs);
  456. // Retrieves template(s) name(s). Should be hostnames.
  457. $templatesarray = array('' => $plugininstance->get_lang('emptysite'));
  458. if ($vtemplates){
  459. foreach($vtemplates as $vtemplatedir){
  460. preg_match("/([^\/]*)_vchamilodata/", $vtemplatedir, $matches);
  461. $templatesarray[$matches[1]] = $matches[1];
  462. if (!isset($first)) $first = $matches[1];
  463. }
  464. }
  465. return $templatesarray;
  466. }
  467. function vchamilo_print_error($errortrace, $return = false)
  468. {
  469. $str = '';
  470. if (!empty($errortrace)){
  471. $str .= '<div class="vchamilo-errors" style="border:1px solid #a0a0a0;background-color:#ffa0a0;padding:5px;font-size:10px">';
  472. $str .= '<pre>';
  473. foreach($errortrace as $error){
  474. $str .= $error->message.'<br/>';
  475. $str .= @$error->content;
  476. }
  477. $str .= '</pre>';
  478. $str .= '</div>';
  479. }
  480. if ($return) return $str;
  481. Display::addFlash(Display::return_message($str));
  482. }
  483. /**
  484. * this function set will map standard moodle API calls to chamilo
  485. * internal primitives. This avoids too many changes to do in imported
  486. * code
  487. *
  488. */
  489. function vchamilo_get_config($module, $key, $isplugin = true)
  490. {
  491. if ($isplugin) {
  492. $key = $module.'_'.$key;
  493. }
  494. $params = array('variable = ? AND subkey = ?' => [$key, $module]);
  495. $result = api_get_settings_params_simple($params);
  496. if ($result) {
  497. return $result['selected_value'];
  498. }
  499. return false;
  500. }
  501. function vchamilo_load_files_from_template($vchamilo, $template)
  502. {
  503. global $_configuration;
  504. // Make template directory (files and SQL).
  505. $separator = DIRECTORY_SEPARATOR;
  506. $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
  507. $relative_template_datadir = $templatefoldername.$separator.$template.'_vchamilodata';
  508. $absolute_templatesdir = $_configuration['root_sys'].$templatefoldername;
  509. $absolute_template_datadir = $_configuration['root_sys'].$relative_template_datadir;
  510. $vchamilo->virtual = true;
  511. // Get Vchamilo known record.
  512. $vcoursepath = api_get_path(SYS_COURSE_PATH, (array)$vchamilo);
  513. $vhomepath = api_get_path(SYS_HOME_PATH, (array)$vchamilo);
  514. $varchivepath = api_get_path(SYS_ARCHIVE_PATH, (array)$vchamilo);
  515. echo "archiveapth : $varchivepath";
  516. // Rename some dirs top match instance requirements
  517. $manifest = vchamilo_get_vmanifest($template);
  518. // get the protocol free hostname
  519. $originarchivedir = preg_replace('/https?:\/\//', '', $manifest->templatewwwroot);
  520. $originhomedir = preg_replace('/https?:\/\//', '', $manifest->templatewwwroot);
  521. Display::addFlash(Display::return_message("Copying {$absolute_template_datadir}/{$manifest->coursefolder} => $vcoursepath"));
  522. Display::addFlash(Display::return_message("Copying {$absolute_template_datadir}/archive/{$originarchivedir} => $varchivepath"));
  523. Display::addFlash(Display::return_message("Copying {$absolute_template_datadir}/home/{$originhomedir} => $vhomepath"));
  524. copyDirContentTo(chop_last_slash($absolute_template_datadir.'/'.$manifest->coursefolder), chop_last_slash($vcoursepath), false);
  525. copyDirContentTo(chop_last_slash($absolute_template_datadir.'/archive/'.$originarchivedir), chop_last_slash($varchivepath), false);
  526. copyDirContentTo(chop_last_slash($absolute_template_datadir.'/home/'.$originhomedir), chop_last_slash($vhomepath), false);
  527. }
  528. function chop_last_slash($path)
  529. {
  530. return preg_replace('/\/$/', '', $path);
  531. }
  532. /**
  533. * Moves a directory and its content to an other area
  534. *
  535. * @author - Hugues Peeters <peeters@ipm.ucl.ac.be>
  536. * @param - $orig_dir_path (string) - the path of the directory to move
  537. * @param - $destination (string) - the path of the new area
  538. * @return - no return
  539. */
  540. function copyDirContentTo($source, $destination, $move = true) {
  541. // Extract directory name - create it at destination - update destination trail
  542. if (!is_dir($source)) {
  543. return;
  544. }
  545. if (!is_dir($destination)) {
  546. mkdir($destination, api_get_permissions_for_new_directories());
  547. }
  548. $DIR = opendir($source);
  549. while ($element = readdir($DIR)) {
  550. if ($element == '.' || $element == '..') {
  551. continue; // Skip the current and parent directories
  552. } elseif (is_file($source.'/'.$element)) {
  553. copy($source.'/'.$element, $destination.'/'.$element);
  554. if ($move) {
  555. unlink($source.'/'.$element) ;
  556. }
  557. } elseif (is_dir($source.'/'.$element)) {
  558. $dirs_to_copy[] = $element;
  559. }
  560. }
  561. closedir($DIR) ;
  562. if (sizeof($dirs_to_copy) > 0) {
  563. foreach ($dirs_to_copy as $dir) {
  564. copyDirContentTo($source.'/'.$dir, $destination.'/'.$dir, $move); // Recursivity
  565. }
  566. }
  567. if ($move) {
  568. rmdir($source) ;
  569. }
  570. }
  571. // from moot
  572. define('PARAM_BOOL', 1);
  573. define('PARAM_INT', 2);
  574. define('PARAM_TEXT', 3);
  575. define('PARAM_RAW', 4);
  576. /**
  577. * this function set will map standard moodle API calls to chamilo
  578. * internal primitives. This avoids too many changes to do in imported
  579. * code
  580. *
  581. */
  582. function get_config($module, $key = false, $isplugin = true) {
  583. global $_configuration, $DB;
  584. static $static_settings;
  585. if (!isset($static_settings)) {
  586. include_once $_configuration['root_sys'].'local/ent_installer/static_settings.php';
  587. }
  588. if ($isplugin){
  589. $configkey = $module.'_'.$key;
  590. } else {
  591. $configkey = $key;
  592. }
  593. if ($module == 'ent_installer') {
  594. $dyna_setting = $DB->get_field(TABLE_MAIN_SETTINGS_CURRENT, 'selected_value', array('subkey' => 'ent_installer', 'variable' => $configkey));
  595. if (!is_null($dyna_setting)) {
  596. return $dyna_setting;
  597. }
  598. if (empty($config)) {
  599. Display::addFlash(Display::return_message("Wrap to static setting $module,$configkey "));
  600. if (array_key_exists($key, $static_settings)){
  601. return $static_settings[$key];
  602. }
  603. }
  604. } else {
  605. if (!$module) {
  606. return $DB->get_field(TABLE_MAIN_SETTINGS_CURRENT, 'selected_value', array('variable' => $configkey));
  607. }
  608. if ($key) {
  609. return $DB->get_field(TABLE_MAIN_SETTINGS_CURRENT, 'selected_value', array('variable' => $configkey, 'subkey' => $module));
  610. } else {
  611. // Get all config from a subkey as an object
  612. $configs = $DB->get_records(TABLE_MAIN_SETTINGS_CURRENT, array('subkey' => $module));
  613. if (!empty($configs)) {
  614. $config = new StdClass;
  615. foreach ($configs as $cf) {
  616. $key = str_replace($module.'_', '', $cf->variable);
  617. $config->$key = $cf->selected_value;
  618. }
  619. return $config;
  620. }
  621. return null;
  622. }
  623. }
  624. }
  625. function set_config($key, $value, $module, $isplugin = false) {
  626. if ($isplugin) {
  627. $key = $module.'_'.$key;
  628. }
  629. if ($isplugin) {
  630. // ensure setting is actually in database
  631. api_update_setting($value, $key, $module);
  632. } else {
  633. api_update_setting($value, $module, $key);
  634. }
  635. }
  636. /**
  637. * gets a string from a component
  638. *
  639. */
  640. function get_string($key, $component = 'local_ent_installer', $a = ''){
  641. global $_configuration;
  642. static $strings;
  643. static $fallbackstrings;
  644. if ($component == 'local_ent_installer') {
  645. $fallbackpath = $_configuration['root_sys'].'local/ent_installer/lang/english/local_ent_installer.php';
  646. if (!isset($strings)) {
  647. $lang = api_get_language_from_type('platform_lang');
  648. if (empty($lang)) $lang = 'english';
  649. $path = $_configuration['root_sys'].'local/ent_installer/lang/'.$lang.'/local_ent_installer.php';
  650. if (!file_exists($path)) {
  651. if (!file_exists($path)) {
  652. print_error('missinglang', null);
  653. die;
  654. }
  655. if (!isset($fallbackstrings)) {
  656. include $fallbackpath;
  657. $fallbackstrings = $string;
  658. }
  659. }
  660. include $path;
  661. $strings = $string;
  662. }
  663. if (!array_key_exists($key, $strings)) {
  664. if (!isset($fallbackstrings)) {
  665. include $fallbackpath;
  666. $fallbackstrings = $string;
  667. }
  668. if (!array_key_exists($key, $fallbackstrings)) {
  669. return "[[$key]]";
  670. }
  671. if (is_scalar($a)) {
  672. return str_replace('{$a}', $a, $fallbackstrings[$key]);
  673. }
  674. if (is_array($a)) {
  675. $a = (object)$a;
  676. }
  677. if (is_object($a)) {
  678. return replace_string_vars($a, $fallbackstrings[$key]);
  679. }
  680. debugging('String insertion not supported', 1);
  681. die;
  682. }
  683. if (is_scalar($a)) {
  684. return str_replace('{$a}', $a, $strings[$key]);
  685. }
  686. if (is_array($a)){
  687. $a = (object)$a;
  688. }
  689. if (is_object($a)){
  690. return replace_string_vars($a, $strings[$key]);
  691. }
  692. debugging('String insertion not supported', 1);
  693. die;
  694. } else {
  695. return get_lang($key);
  696. }
  697. }
  698. function replace_string_vars($a, $str){
  699. preg_match_all('/{\$a-\>(.+?)}/', $str, $matches);
  700. if (!empty($matches[1])){
  701. foreach($matches[1] as $replacekey){
  702. $str = str_replace('{$a->'.$replacekey.'}', $a->$replacekey, $str);
  703. }
  704. }
  705. return $str;
  706. }
  707. function print_error($key, $component = '', $passthru = false, $extrainfo = ''){
  708. global $debuglevel;
  709. global $debugdisplay;
  710. if ($component === null){
  711. $str = $key;
  712. } else {
  713. $str = get_string($string, $component);
  714. }
  715. ctrace('ERROR: '. $str);
  716. if (!empty($extrainfo)){
  717. ctrace('Extra: '. $extrainfo);
  718. }
  719. if ($debugdisplay >= 3){
  720. debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  721. }
  722. if (!$passthru) die;
  723. }
  724. function debugging($message, $level) {
  725. global $debuglevel;
  726. global $debugdisplay;
  727. if ($level <= $debuglevel) {
  728. ctrace('DEBUG: '.$message);
  729. if ($debugdisplay >= 3){
  730. debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  731. }
  732. }
  733. }
  734. /**
  735. * Wrap moodle to chamilo side
  736. *
  737. */
  738. function mtrace($message){
  739. ctrace($message);
  740. }
  741. function ctrace($str) {
  742. if (!defined('CLI_SCRIPT')) echo "<pre>";
  743. Display::addFlash(Display::return_message($str));
  744. if (!defined('CLI_SCRIPT')) echo "</pre>";
  745. }
  746. /**
  747. * Sets a platform configuration setting to a given value, creating it if necessary
  748. * @param string The value we want to record
  749. * @param string The variable name we want to insert
  750. * @param string The subkey for the variable we want to insert
  751. * @param string The type for the variable we want to insert
  752. * @param string The category for the variable we want to insert
  753. * @param string The title
  754. * @param string The comment
  755. * @param string The scope
  756. * @param string The subkey text
  757. * @param int The access_url for which this parameter is valid
  758. * @param int The changeability of this setting for non-master urls
  759. * @return boolean true on success, false on failure
  760. */
  761. function api_update_setting($val, $var, $sk = null, $type = 'textfield', $c = null, $title = '', $com = '', $sc = null, $skt = null, $a = 1, $v = 0) {
  762. global $_setting;
  763. if (empty($var) || !isset($val)) {
  764. return false;
  765. }
  766. $t_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
  767. $var = Database::escape_string($var);
  768. $val = Database::escape_string($val);
  769. $a = (int) $a;
  770. if (empty($a)) { $a = 1; }
  771. // Check if this variable doesn't exist already
  772. $select = "SELECT id FROM $t_settings WHERE variable = '$var' ";
  773. if (!empty($sk)) {
  774. $sk = Database::escape_string($sk);
  775. $select .= " AND subkey = '$sk'";
  776. }
  777. if ($a > 1) {
  778. $select .= " AND access_url = $a";
  779. } else {
  780. $select .= " AND access_url = 1 ";
  781. }
  782. $res = Database::query($select);
  783. if (Database::num_rows($res) > 0) { // Found item for this access_url.
  784. $row = Database::fetch_array($res);
  785. // update value
  786. $update['selected_value'] = $val;
  787. Database::update($t_settings, $update, array('id = ?' => $row['id']));
  788. return $row['id'];
  789. // update in memory setting value
  790. $_setting[$var][$sk] = $val;
  791. }
  792. // Item not found for this access_url, we have to check if the whole thing is missing
  793. // (in which case we ignore the insert) or if there *is* a record but just for access_url = 1
  794. $insert = "INSERT INTO $t_settings " .
  795. "(variable,selected_value," .
  796. "type,category," .
  797. "subkey,title," .
  798. "comment,scope," .
  799. "subkeytext,access_url,access_url_changeable)" .
  800. " VALUES ('$var','$val',";
  801. if (isset($type)) {
  802. $type = Database::escape_string($type);
  803. $insert .= "'$type',";
  804. } else {
  805. $insert .= "NULL,";
  806. }
  807. if (isset($c)) { // Category
  808. $c = Database::escape_string($c);
  809. $insert .= "'$c',";
  810. } else {
  811. $insert .= "NULL,";
  812. }
  813. if (isset($sk)) { // Subkey
  814. $sk = Database::escape_string($sk);
  815. $insert .= "'$sk',";
  816. } else {
  817. $insert .= "NULL,";
  818. }
  819. if (isset($title)) { // Title
  820. $title = Database::escape_string($title);
  821. $insert .= "'$title',";
  822. } else {
  823. $insert .= "NULL,";
  824. }
  825. if (isset($com)) { // Comment
  826. $com = Database::escape_string($com);
  827. $insert .= "'$com',";
  828. } else {
  829. $insert .= "NULL,";
  830. }
  831. if (isset($sc)) { // Scope
  832. $sc = Database::escape_string($sc);
  833. $insert .= "'$sc',";
  834. } else {
  835. $insert .= "NULL,";
  836. }
  837. if (isset($skt)) { // Subkey text
  838. $skt = Database::escape_string($skt);
  839. $insert .= "'$skt',";
  840. } else {
  841. $insert .= "NULL,";
  842. }
  843. $insert .= "$a,$v)";
  844. $res = Database::query($insert);
  845. // update in memory setting value
  846. $_setting[$var][$sk] = $value;
  847. return $res;
  848. }
  849. /**
  850. * converts a timestamp to sql tms
  851. * @param lint $time a unix timestamp
  852. */
  853. function make_tms($time) {
  854. $tms = date('Y-m-d H:i:s', $time);
  855. return $tms;
  856. }
  857. /**
  858. * Makes sure the data is using valid utf8, invalid characters are discarded.
  859. *
  860. * Note: this function is not intended for full objects with methods and private properties.
  861. *
  862. * @param mixed $value
  863. * @return mixed with proper utf-8 encoding
  864. */
  865. function fix_utf8($value) {
  866. if (is_null($value) or $value === '') {
  867. return $value;
  868. } else if (is_string($value)) {
  869. if ((string)(int)$value === $value) {
  870. // shortcut
  871. return $value;
  872. }
  873. // Lower error reporting because glibc throws bogus notices.
  874. $olderror = error_reporting();
  875. if ($olderror & E_NOTICE) {
  876. error_reporting($olderror ^ E_NOTICE);
  877. }
  878. // Note: this duplicates min_fix_utf8() intentionally.
  879. static $buggyiconv = null;
  880. if ($buggyiconv === null) {
  881. $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'\80') !== '100\80');
  882. }
  883. if ($buggyiconv) {
  884. if (function_exists('mb_convert_encoding')) {
  885. $subst = mb_substitute_character();
  886. mb_substitute_character('');
  887. $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
  888. mb_substitute_character($subst);
  889. } else {
  890. // Warn admins on admin/index.php page.
  891. $result = $value;
  892. }
  893. } else {
  894. $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
  895. }
  896. if ($olderror & E_NOTICE) {
  897. error_reporting($olderror);
  898. }
  899. return $result;
  900. } else if (is_array($value)) {
  901. foreach ($value as $k=>$v) {
  902. $value[$k] = fix_utf8($v);
  903. }
  904. return $value;
  905. } else if (is_object($value)) {
  906. $value = clone($value); // do not modify original
  907. foreach ($value as $k=>$v) {
  908. $value->$k = fix_utf8($v);
  909. }
  910. return $value;
  911. } else {
  912. // this is some other type, no utf-8 here
  913. return $value;
  914. }
  915. }
  916. function print_object($obj) {
  917. echo '<pre>';
  918. print_r($obj);
  919. echo '</pre>';
  920. }
  921. function require_js($file, $component, $return = false)
  922. {
  923. global $_configuration, $htmlHeadXtra;
  924. if (preg_match('/^local_/', $component)) {
  925. $component = str_replace('local_', '', $component);
  926. $path = 'local/';
  927. } else {
  928. $path = 'plugin/';
  929. }
  930. // Secure the postslashing of the roots.
  931. $root_web = $_configuration['root_web'].'/';
  932. $root_web = preg_replace('#//$#', '/', $root_web);
  933. $str = '<script type="text/javascript" src="'.$root_web.$path.$component.'/js/'.$file.'"></script>'."\n";
  934. if ($return === 'head') {
  935. $htmlHeadXtra[] = $str;
  936. }
  937. if ($return) {
  938. return $str;
  939. }
  940. echo $str;
  941. }
  942. function require_css($file, $component, $return = false)
  943. {
  944. global $_configuration, $htmlHeadXtra;
  945. if (preg_match('/^local_/', $component)) {
  946. $component = str_replace('local_', '', $component);
  947. $path = 'local/';
  948. } else {
  949. $path = 'plugin/';
  950. }
  951. // Secure the postslashing of the roots.
  952. $root_web = $_configuration['root_web'].'/';
  953. $root_web = preg_replace('#//$#', '/', $root_web);
  954. $str = '<link rel="stylesheet" type="text/css" href="'.$root_web.$path.$component.'/'.$file.'.css" />'."\n";
  955. if ($return === 'head') {
  956. $htmlHeadXtra[] = $str;
  957. }
  958. if ($return) {
  959. return $str;
  960. }
  961. echo $str;
  962. }
  963. /**
  964. *
  965. */
  966. function required_param($key, $type = 0)
  967. {
  968. if (array_key_exists($key, $_REQUEST)) {
  969. $value = $_REQUEST[$key];
  970. $value = param_filter_type($value, $type);
  971. return $value;
  972. }
  973. die("Missing expected param $key in request input");
  974. }
  975. function optional_param($key, $default, $type = 0)
  976. {
  977. if (array_key_exists($key, $_REQUEST)) {
  978. $value = $_REQUEST[$key];
  979. $value = param_filter_type($value, $type);
  980. return $value;
  981. }
  982. return $default;
  983. }
  984. function param_filter_type($value, $type)
  985. {
  986. switch($type) {
  987. case 0:
  988. return $value; // no filtering
  989. case PARAM_BOOL:
  990. return $value == 0; // forces outputing boolean
  991. case PARAM_INT:
  992. if (preg_match('/^([1-90]+)/', $value, $matches)) {
  993. return $matches[1];
  994. }
  995. return 0;
  996. case PARAM_TEXT:
  997. // TODO more filtering here
  998. return $value;
  999. }
  1000. }
  1001. function redirect($url) {
  1002. header("Location: $url\n\n");
  1003. }
  1004. function vchamilo_get_slug_from_url($url)
  1005. {
  1006. $slugify = new Slugify();
  1007. $urlInfo = parse_url($url);
  1008. return $slugify->slugify($urlInfo['host']);
  1009. }