Virtual.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Cocur\Slugify\Slugify;
  4. use Symfony\Component\Finder\Finder;
  5. use Symfony\Component\Console\Input\ArrayInput;
  6. use Symfony\Component\Console\Output\StreamOutput;
  7. use Symfony\Component\Console\Application;
  8. use Doctrine\ORM\EntityManager;
  9. /**
  10. * Class Virtual
  11. */
  12. class Virtual
  13. {
  14. /**
  15. * @param array $_configuration
  16. */
  17. public static function hookConfiguration(& $_configuration)
  18. {
  19. global $virtualChamilo;
  20. if (defined('CLI_SCRIPT') && !defined('CLI_VCHAMILO_OVERRIDE')) {
  21. return;
  22. }
  23. // provides an effective value for the virtual root_web based on domain analysis
  24. self::getHostName($_configuration);
  25. // We are on physical chamilo. Let original config play
  26. $virtualChamiloWebRoot = rtrim($_configuration['vchamilo_web_root'], '/') . '/';
  27. $virtualChamilo = [];
  28. if ($_configuration['root_web'] == $virtualChamiloWebRoot) {
  29. return;
  30. }
  31. // pre hook to chamilo main table and get alternate configuration.
  32. // sure Database object is not set up. Soo use bootstrap connection
  33. /** @var \Doctrine\DBAL\Connection $connection */
  34. $connection = Virtual::bootConnection($_configuration);
  35. $query = "SELECT * FROM vchamilo WHERE root_web = '$virtualChamiloWebRoot'";
  36. $result = $connection->executeQuery($query);
  37. if ($result->rowCount()) {
  38. $data = $result->fetch();
  39. $excludes = array('id', 'name');
  40. $query = "SELECT * FROM settings_current WHERE subkey = 'vchamilo'";
  41. $virtualSettings = $connection->executeQuery($query);
  42. $virtualSettings = $virtualSettings->fetchAll();
  43. $homePath = '';
  44. $coursePath = '';
  45. $archivePath = '';
  46. $uploadPath = '';
  47. $passwordEncryption = '';
  48. foreach ($virtualSettings as $setting) {
  49. switch ($setting['variable']) {
  50. case 'vchamilo_upload_real_root':
  51. $uploadPath = $setting['selected_value'];
  52. break;
  53. case 'vchamilo_home_real_root':
  54. $homePath = $setting['selected_value'];
  55. break;
  56. case 'vchamilo_course_real_root':
  57. $coursePath = $setting['selected_value'];
  58. break;
  59. case 'vchamilo_archive_real_root':
  60. $archivePath = $setting['selected_value'];
  61. break;
  62. case 'vchamilo_password_encryption':
  63. $passwordEncryption = $setting['selected_value'];
  64. break;
  65. }
  66. }
  67. if (empty($homePath) || empty($coursePath) || empty($archivePath) || empty($uploadPath)) {
  68. echo 'Configure correctly the vchamilo plugin';
  69. exit;
  70. }
  71. // Only load if is visible
  72. if ($data && $data['visible'] === '1') {
  73. foreach ($data as $key => $value) {
  74. if (!in_array($key, $excludes)) {
  75. // Avoid empty password_encryption
  76. if ($key == 'password_encryption' && empty($value)) {
  77. continue;
  78. }
  79. $_configuration[$key] = $value;
  80. }
  81. $_configuration['virtual'] = $data['root_web'].'/';
  82. }
  83. $data['SYS_ARCHIVE_PATH'] = self::addTrailingSlash($archivePath).$data['slug'];
  84. $data['SYS_HOME_PATH'] = self::addTrailingSlash($homePath).$data['slug'];
  85. $data['SYS_COURSE_PATH'] = self::addTrailingSlash($coursePath).$data['slug'];
  86. $data['SYS_UPLOAD_PATH'] = self::addTrailingSlash($uploadPath).$data['slug'];
  87. $data['WEB_HOME_PATH'] = self::addTrailingSlash($data['home_url']);
  88. $data['WEB_UPLOAD_PATH'] = self::addTrailingSlash($data['upload_url']);
  89. $data['WEB_ARCHIVE_PATH'] = self::addTrailingSlash($data['archive_url']);
  90. //$data['WEB_COURSE_PATH'] = self::addTrailingSlash($data['course_url']);
  91. if (!empty($passwordEncryption)) {
  92. $_configuration['password_encryption'] = $passwordEncryption;
  93. }
  94. $virtualChamilo = $data;
  95. } else {
  96. exit("This portal is disabled. Please contact your administrator");
  97. }
  98. } else {
  99. // Platform was not configured yet
  100. //die("VChamilo : Could not fetch virtual chamilo configuration");
  101. }
  102. }
  103. /**
  104. * @param array $_configuration
  105. */
  106. public static function getHostName(&$_configuration)
  107. {
  108. if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
  109. $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_configuration['force_https_forwarded_proto'])
  110. ) {
  111. $protocol = 'https';
  112. } else {
  113. if (!empty($_SERVER['HTTPS'])) {
  114. $protocol = 'https';
  115. } else {
  116. $protocol = 'http';
  117. }
  118. }
  119. if (defined('CLI_VCHAMILO_OVERRIDE')) {
  120. $_configuration['vchamilo_web_root'] = CLI_VCHAMILO_OVERRIDE;
  121. $_configuration['vchamilo_name'] = preg_replace('#https?://#', '', CLI_VCHAMILO_OVERRIDE);
  122. // remove radical from override for name
  123. // fake the server signature
  124. global $_SERVER;
  125. $_SERVER['SERVER_NAME'] = $_configuration['vchamilo_name'];
  126. $_SERVER['HTTP_HOST'] = $_configuration['vchamilo_name'];
  127. $_SERVER['QUERY_STRING'] = '';
  128. $_SERVER['REQUEST_URI'] = CLI_VCHAMILO_OVERRIDE;
  129. return;
  130. }
  131. $contentPrefix = '/';
  132. if (isset($_SERVER['CONTEXT_PREFIX']) && !empty($_SERVER['CONTEXT_PREFIX'])) {
  133. $contentPrefix = $_SERVER['CONTEXT_PREFIX'];
  134. } else {
  135. // Getting url_append from URL
  136. if (isset($_SERVER['REQUEST_URI'])) {
  137. $requestUri = $_SERVER['REQUEST_URI'];
  138. if (strpos($requestUri, '/courses/') !== false) {
  139. $result = substr($requestUri, 0, strpos($requestUri, '/courses/'));
  140. if (!empty($result) && $result != '/') {
  141. $contentPrefix = $result;
  142. }
  143. }
  144. }
  145. }
  146. $_configuration['vchamilo_web_root'] = "{$protocol}://".@$_SERVER['HTTP_HOST'].$contentPrefix;
  147. $_configuration['vchamilo_name'] = @$_SERVER['HTTP_HOST'];
  148. if (empty($_configuration['vchamilo_name'])) { // try again with another source if has failed
  149. $_configuration['vchamilo_name'] = "{$protocol}://".$_SERVER['SERVER_NAME'];
  150. if ($_SERVER['SERVER_PORT'] != 80) {
  151. $_configuration['vchamilo_name'] .= ':'.$_SERVER['SERVER_PORT'];
  152. }
  153. $_configuration['vchamilo_name'] = $_SERVER['SERVER_NAME'];
  154. }
  155. }
  156. /**
  157. * @param string $path
  158. * @return string
  159. */
  160. public static function addTrailingSlash($path)
  161. {
  162. return substr($path, -1) == '/' ? $path : $path.'/';
  163. }
  164. /**
  165. * provides a side connection to a vchamilo database
  166. * @param array $_configuration
  167. *
  168. * @return \Doctrine\DBAL\Driver\Connection
  169. */
  170. public static function bootConnection(&$_configuration)
  171. {
  172. $dbParams = array(
  173. 'driver' => 'pdo_mysql',
  174. 'host' => $_configuration['db_host'],
  175. 'user' => $_configuration['db_user'],
  176. 'password' => $_configuration['db_password'],
  177. 'dbname' => isset($_configuration['main_database']) ? $_configuration['main_database'] : '',
  178. // Only relevant for pdo_sqlite, specifies the path to the SQLite database.
  179. 'path' => isset($_configuration['db_path']) ? $_configuration['db_path'] : '',
  180. // Only relevant for pdo_mysql, pdo_pgsql, and pdo_oci/oci8,
  181. 'port' => isset($_configuration['db_port']) ? $_configuration['db_port'] : '',
  182. );
  183. try {
  184. $database = new \Database();
  185. $connection = $database->connect(
  186. $dbParams,
  187. $_configuration['root_sys'],
  188. $_configuration['root_sys'],
  189. true
  190. );
  191. } catch (Exception $e) {
  192. echo('Side connection failure with '.$_configuration['db_host'].', '.$_configuration['db_user'].', ******** ');
  193. die();
  194. }
  195. return $connection;
  196. }
  197. /**
  198. * @param string $url
  199. */
  200. public static function redirect($url)
  201. {
  202. if (preg_match('#https?://#', $url)) {
  203. header('location: '.$url);
  204. } else {
  205. header('location: ' . api_get_path(WEB_PATH).$url);
  206. }
  207. exit;
  208. }
  209. /**
  210. * @param string $course_folder
  211. * @return string
  212. */
  213. public static function getHtaccessFragment($course_folder)
  214. {
  215. $str = "
  216. # Change this file to fit your configuration and save it as .htaccess in the courses folder #
  217. # Chamilo mod rewrite
  218. # Comment lines start with # and are not processed
  219. <IfModule mod_rewrite.c>
  220. RewriteEngine On
  221. # Rewrite base is the dir chamilo is installed in with trailing slash
  222. RewriteBase /{$course_folder}/
  223. # Do not rewrite on the main dir
  224. # Change this path to the path of your main folder
  225. RewriteCond %{REQUEST_URI} !^/main/
  226. #replace nasty ampersands by 3 slashes, we change these back in download.php
  227. RewriteRule ([^/]+)/document/(.*)&(.*)$ $1/document/$2///$3 [N]
  228. # Rewrite everything in the scorm folder of a course to the download script
  229. RewriteRule ([^/]+)/scorm/(.*)$ /main/document/download_scorm.php?doc_url=/$2&cDir=$1 [QSA,L]
  230. # Rewrite everything in the document folder of a course to the download script
  231. RewriteRule ([^/]+)/document/(.*)$ /main/document/download.php?doc_url=/$2&cDir=$1 [QSA,L]
  232. # Rewrite everything in the work folder
  233. RewriteRule ([^/]+)/work/(.*)$ /main/work/download.php?file=work/$2&cDir=$1 [QSA,L]
  234. </IfModule>
  235. ";
  236. return $str;
  237. }
  238. /**
  239. * @return string
  240. */
  241. public static function getDefaultCourseIndexFragment()
  242. {
  243. return "<html><head></head><body></body></html>";
  244. }
  245. /**
  246. * @param string $template
  247. * @return bool
  248. */
  249. public static function templateExists($template)
  250. {
  251. global $_configuration;
  252. // Find and checktemplate directory (files and SQL).
  253. $separator = DIRECTORY_SEPARATOR;
  254. $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
  255. $relative_datadir = $templatefoldername.$separator.$template.'_sql';
  256. $absolute_datadir = $_configuration['root_sys'].$relative_datadir;
  257. return is_dir($absolute_datadir);
  258. }
  259. /**
  260. * drop a vchamilo instance databases using the physical connection
  261. * @param stdClass $params
  262. * return an array of errors or false if ok
  263. */
  264. public static function dropDatabase($params)
  265. {
  266. $params = clone $params;
  267. if (empty($params->main_database)) {
  268. Display::addFlash(Display::return_message('No database found'));
  269. return;
  270. }
  271. $databaseToDelete = $params->main_database;
  272. unset($params->main_database);
  273. $connection = self::getConnectionFromInstance($params);
  274. if ($connection) {
  275. $databases = $connection->getSchemaManager()->listDatabases();
  276. if (in_array($databaseToDelete, $databases)) {
  277. $connection->getSchemaManager()->dropDatabase(
  278. $databaseToDelete
  279. );
  280. Display::addFlash(
  281. Display::return_message(
  282. 'Database deleted: '.$databaseToDelete
  283. )
  284. );
  285. } else {
  286. Display::addFlash(
  287. Display::return_message(
  288. 'Database does not exist: '.$databaseToDelete
  289. )
  290. );
  291. }
  292. } else {
  293. Display::addFlash(
  294. Display::return_message(
  295. "Cannot connect DB: $databaseToDelete"
  296. )
  297. );
  298. }
  299. return false;
  300. }
  301. /**
  302. * @param stdClass $params
  303. * @return bool
  304. */
  305. public static function createDatabase($params)
  306. {
  307. $params = clone $params;
  308. $databaseName = $params->main_database;
  309. unset($params->main_database);
  310. $connection = Virtual::getConnectionFromInstance($params);
  311. if ($connection) {
  312. $databaseList = $connection->getSchemaManager()->listDatabases();
  313. if (!in_array($databaseName, $databaseList)) {
  314. $connection->getSchemaManager()->createDatabase($databaseName);
  315. Display::addFlash(
  316. Display::return_message("Creating DB ".$databaseName)
  317. );
  318. } else {
  319. Display::addFlash(
  320. Display::return_message("DB already exists: ".$databaseName)
  321. );
  322. }
  323. return true;
  324. }
  325. return false;
  326. }
  327. /**
  328. * get a proper SQLdump command
  329. * @param object $vchamilodata the complete new host information
  330. * @return string the shell command
  331. */
  332. public static function getDatabaseDumpCmd($vchamilodata)
  333. {
  334. $pgm = self::getConfig('vchamilo', 'mysql_cmd');
  335. if (!$pgm) {
  336. $pgm = '/usr/bin/mysql';
  337. }
  338. $phppgm = str_replace("\\", '/', $pgm);
  339. $phppgm = str_replace("\"", '', $phppgm);
  340. $pgm = str_replace("/", DIRECTORY_SEPARATOR, $pgm);
  341. if (!is_executable($phppgm)) {
  342. throw new Exception('databasecommanddoesnotmatchanexecutablefile');
  343. }
  344. // Retrieves the host configuration (more secure).
  345. $vchamilodata = empty($vchamilodata) ? Virtual::makeThis() : $vchamilodata;
  346. if (strstr($vchamilodata->db_host, ':') !== false) {
  347. list($vchamilodata->db_host, $vchamilodata->db_port) = explode(
  348. ':',
  349. $vchamilodata->db_host
  350. );
  351. }
  352. // Password.
  353. $databasePassword = '';
  354. if (!empty($vchamilodata->db_password)) {
  355. $databasePassword = '-p'.escapeshellarg($vchamilodata->db_password).' ';
  356. }
  357. // Making the command line (see 'vconfig.php' file for defining the right paths).
  358. $sqlcmd = $pgm.' -h'.$vchamilodata->db_host.(isset($vchamilodata->db_port) ? ' -P'.$vchamilodata->db_port.' ' : ' ' );
  359. $sqlcmd .= '-u'.$vchamilodata->db_user.' '.$databasePassword;
  360. $sqlcmd .= '%DATABASE% < ';
  361. return $sqlcmd;
  362. }
  363. /**
  364. * @param stdClass $vchamilo
  365. * @param string $template
  366. * @return bool
  367. */
  368. public static function loadDbTemplate($vchamilo, $template)
  369. {
  370. global $_configuration;
  371. // Make template directory (files and SQL).
  372. $separator = DIRECTORY_SEPARATOR;
  373. $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
  374. $absolute_datadir = $_configuration['root_sys'].$templatefoldername.$separator.$template.$separator.'dump.sql';
  375. if (!$sqlcmd = Virtual::getDatabaseDumpCmd($vchamilo)) {
  376. return false;
  377. }
  378. $sqlcmd = str_replace('%DATABASE%', $vchamilo->main_database, $sqlcmd);
  379. // Make final commands to execute, depending on the database type.
  380. $import = $sqlcmd.$absolute_datadir;
  381. // Execute the command.
  382. Display::addFlash(Display::return_message("Load database from template dump: \n $import "));
  383. if (!defined('CLI_SCRIPT')) {
  384. putenv('LANG=en_US.utf-8');
  385. }
  386. // ensure utf8 is correctly handled by php exec()
  387. // @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input
  388. exec($import, $output, $return);
  389. if (!empty($output)) {
  390. Display::addFlash(Display::return_message(implode("\n", $output)."\n"));
  391. }
  392. return true;
  393. }
  394. /**
  395. * Backups a database for having a snapshot.
  396. * @param $vchamilo object The Vchamilo object.
  397. * @param $outputfilerad string The output SQL file radical.
  398. * @return bool If TRUE, dumping database was a success, otherwise FALSE.
  399. */
  400. public static function backupDatabase($vchamilo, $outputfilerad)
  401. {
  402. // Separating host and port, if sticked.
  403. if (strstr($vchamilo->db_host, ':') !== false) {
  404. list($host, $port) = explode(':', $vchamilo->db_host);
  405. } else {
  406. $host = $vchamilo->db_host;
  407. }
  408. // By default, empty password.
  409. $pass = '';
  410. $pgm = null;
  411. if (empty($port)) {
  412. $port = 3306;
  413. }
  414. // Password.
  415. if (!empty($vchamilo->db_password)) {
  416. $pass = "-p".escapeshellarg($vchamilo->db_password);
  417. }
  418. // Making the commands for each database.
  419. $cmds = array();
  420. //if ($CFG->ostype == 'WINDOWS') {
  421. if (false) {
  422. $cmd_main = "-h{$host} -P{$port} -u{$vchamilo->db_user} {$pass} {$vchamilo->main_database}";
  423. $cmds[] = $cmd_main . ' > ' . $outputfilerad;
  424. } else {
  425. $cmd_main = "-h{$host} -P{$port} -u{$vchamilo->db_user} {$pass} {$vchamilo->main_database}";
  426. $cmds[] = $cmd_main . ' > ' . escapeshellarg($outputfilerad);
  427. }
  428. $mysqldumpcmd = self::getConfig('vchamilo', 'cmd_mysqldump', true);
  429. $pgm = !empty($mysqldumpcmd) ? stripslashes($mysqldumpcmd) : false;
  430. if (!$pgm) {
  431. $message = "Database dump command not available check here: ";
  432. $url = api_get_path(WEB_CODE_PATH).'admin/configure_plugin.php?name=vchamilo';
  433. $message .= Display::url($url, $url);
  434. Display::addFlash(Display::return_message($message));
  435. return false;
  436. } else {
  437. $phppgm = str_replace("\\", '/', $pgm);
  438. $phppgm = str_replace("\"", '', $phppgm);
  439. $pgm = str_replace('/', DIRECTORY_SEPARATOR, $pgm);
  440. if (!is_executable($phppgm)) {
  441. $message = "Database dump command $phppgm does not match any executable";
  442. Display::addFlash(Display::return_message($message));
  443. return false;
  444. }
  445. // executing all commands
  446. foreach ($cmds as $cmd) {
  447. // Final command.
  448. $cmd = $pgm.' '.$cmd;
  449. // Executes the SQL command.
  450. exec($cmd, $execoutput, $returnvalue);
  451. }
  452. }
  453. // End with success.
  454. return 1;
  455. }
  456. /**
  457. * read manifest values in vchamilo template.
  458. */
  459. public static function getVmanifest($version)
  460. {
  461. $templatewwwroot = '';
  462. // Define the $templatewwwroot content, found in manifest.php for this template
  463. $file = api_get_path(SYS_PATH).'/plugin/vchamilo/templates/'.$version.'/manifest.php';
  464. if (file_exists($file)) {
  465. include $file;
  466. $manifest = new stdClass();
  467. $manifest->templatewwwroot = $templatewwwroot;
  468. // $manifest->templatevdbprefix = $templatevdbprefix;
  469. // $manifest->coursefolder = $coursefolder;
  470. return $manifest;
  471. }
  472. return false;
  473. }
  474. /**
  475. * make a fake vchamilo that represents the current host
  476. */
  477. public static function makeThis()
  478. {
  479. global $_configuration;
  480. $thisPortal = new stdClass();
  481. $thisPortal->root_web = $_configuration['root_web'];
  482. $thisPortal->db_host = $_configuration['db_host'];
  483. $thisPortal->db_user = $_configuration['db_user'];
  484. $thisPortal->db_password = $_configuration['db_password'];
  485. $thisPortal->main_database = $_configuration['main_database'];
  486. return $thisPortal;
  487. }
  488. /**
  489. * Get available templates for defining a new virtual host.
  490. * @return array The available templates, or EMPTY array.
  491. */
  492. public static function getAvailableTemplates()
  493. {
  494. global $_configuration;
  495. $separator = DIRECTORY_SEPARATOR;
  496. $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
  497. $tempDir = $_configuration['root_sys'].$templatefoldername;
  498. // Scans the templates.
  499. if (!is_dir($tempDir)) {
  500. mkdir($tempDir, 0777, true);
  501. }
  502. $finder = new \Symfony\Component\Finder\Finder();
  503. $dirs = $finder->in($tempDir)->depth('== 0');
  504. // Retrieves template(s) name(s). Should be hostnames.
  505. $templates = [];
  506. /*if ($addEmptyTemplate) {
  507. $templates = array('' => $plugin->get_lang('emptysite'));
  508. }*/
  509. $template = self::getConfig('vchamilo', 'default_template');
  510. if ($dirs) {
  511. /** @var Symfony\Component\Finder\SplFileInfo $dir */
  512. foreach ($dirs as $dir) {
  513. if (is_dir($dir->getPathname())) {
  514. // A template is considered when a dump.sql exists.
  515. if (file_exists($dir->getPathname().'/dump.sql')) {
  516. $templateName = $dir->getRelativePathname();
  517. if ($templateName == $template) {
  518. $templateName .= ' (default)';
  519. }
  520. $templates[$dir->getRelativePathname()] = $templateName;
  521. }
  522. }
  523. }
  524. }
  525. return $templates;
  526. }
  527. /**
  528. * this function set will map standard moodle API calls to chamilo
  529. * internal primitives. This avoids too many changes to do in imported
  530. * code
  531. */
  532. public static function getConfig($module, $key, $isplugin = true)
  533. {
  534. if ($isplugin) {
  535. $key = $module.'_'.$key;
  536. }
  537. $params = array('variable = ? AND subkey = ?' => [$key, $module]);
  538. $result = api_get_settings_params_simple($params);
  539. if ($result) {
  540. return $result['selected_value'];
  541. }
  542. return false;
  543. }
  544. /**
  545. * @param stdClass $vchamilo
  546. * @param string $template
  547. */
  548. public static function loadFilesFromTemplate($vchamilo, $template)
  549. {
  550. global $_configuration;
  551. // Make template directory (files and SQL).
  552. $separator = DIRECTORY_SEPARATOR;
  553. $templateDir = $_configuration['root_sys'].'plugin'.$separator.'vchamilo'.$separator.'templates'.$separator.$template;
  554. $vchamilo->virtual = true;
  555. $coursePath = self::getConfig('vchamilo', 'course_real_root').$separator.$vchamilo->slug;
  556. $homePath = self::getConfig('vchamilo', 'home_real_root').$separator.$vchamilo->slug;
  557. $archivePath = self::getConfig('vchamilo', 'archive_real_root').$separator.$vchamilo->slug;
  558. $uploadPath = self::getConfig('vchamilo', 'upload_real_root').$separator.$vchamilo->slug;
  559. // get the protocol free hostname
  560. Display::addFlash(
  561. Display::return_message("Copying {$templateDir}/data/courses => $coursePath")
  562. );
  563. copyDirTo(
  564. self::chopLastSlash($templateDir.'/data/courses'),
  565. self::chopLastSlash($coursePath),
  566. false
  567. );
  568. Display::addFlash(
  569. Display::return_message("Copying {$templateDir}/data/archive => $archivePath")
  570. );
  571. copyDirTo(
  572. self::chopLastSlash($templateDir.'/data/archive'),
  573. self::chopLastSlash($archivePath),
  574. false
  575. );
  576. Display::addFlash(
  577. Display::return_message("Copying {$templateDir}/data/home => $homePath")
  578. );
  579. copyDirTo(
  580. self::chopLastSlash($templateDir.'/data/home'),
  581. self::chopLastSlash($homePath),
  582. false
  583. );
  584. // Upload
  585. Display::addFlash(
  586. Display::return_message("Copying {$templateDir}/data/upload => $uploadPath")
  587. );
  588. copyDirTo(
  589. self::chopLastSlash($templateDir.'/data/upload/'),
  590. self::chopLastSlash($uploadPath),
  591. false
  592. );
  593. }
  594. /**
  595. * @param string $path
  596. *
  597. * @return mixed
  598. */
  599. public static function chopLastSlash($path)
  600. {
  601. return preg_replace('/\/$/', '', $path);
  602. }
  603. /**
  604. * @param string $str
  605. */
  606. public static function ctrace($str)
  607. {
  608. error_log($str);
  609. Display::addFlash(Display::return_message($str, 'normal', false));
  610. }
  611. /**
  612. * @param $file
  613. * @param $component
  614. * @param bool $return
  615. * @return string
  616. */
  617. public static function requireJs($file, $component, $return = false)
  618. {
  619. global $_configuration, $htmlHeadXtra;
  620. if (preg_match('/^local_/', $component)) {
  621. $component = str_replace('local_', '', $component);
  622. $path = 'local/';
  623. } else {
  624. $path = 'plugin/';
  625. }
  626. // Secure the postslashing of the roots.
  627. $root_web = $_configuration['root_web'].'/';
  628. $root_web = preg_replace('#//$#', '/', $root_web);
  629. $str = '<script type="text/javascript" src="'.$root_web.$path.$component.'/js/'.$file.'"></script>'."\n";
  630. if ($return === 'head') {
  631. $htmlHeadXtra[] = $str;
  632. }
  633. if ($return) {
  634. return $str;
  635. }
  636. echo $str;
  637. }
  638. /**
  639. * @param $file
  640. * @param $component
  641. * @param bool $return
  642. * @return string
  643. */
  644. public static function requireCss($file, $component, $return = false)
  645. {
  646. global $_configuration, $htmlHeadXtra;
  647. if (preg_match('/^local_/', $component)) {
  648. $component = str_replace('local_', '', $component);
  649. $path = 'local/';
  650. } else {
  651. $path = 'plugin/';
  652. }
  653. // Secure the postslashing of the roots.
  654. $root_web = $_configuration['root_web'].'/';
  655. $root_web = preg_replace('#//$#', '/', $root_web);
  656. $str = '<link rel="stylesheet" type="text/css" href="'.$root_web.$path.$component.'/'.$file.'.css" />'."\n";
  657. if ($return === 'head') {
  658. $htmlHeadXtra[] = $str;
  659. }
  660. if ($return) {
  661. return $str;
  662. }
  663. echo $str;
  664. }
  665. /**
  666. * @param string $url
  667. * @return string
  668. */
  669. public static function getSlugFromUrl($url)
  670. {
  671. $slugify = new Slugify();
  672. $urlInfo = parse_url($url);
  673. if (isset($urlInfo['host'])) {
  674. $path = $urlInfo['path'] != '/' ? '_'.$urlInfo['path'] : '';
  675. return $slugify->slugify($urlInfo['host'].$path);
  676. }
  677. return false;
  678. }
  679. /**
  680. * Check if all settings are complete
  681. */
  682. public static function checkSettings()
  683. {
  684. $enabled = self::getConfig('vchamilo', 'enable_virtualisation');
  685. if (empty($enabled)) {
  686. api_not_allowed(true, 'Plugin is not enabled');
  687. }
  688. global $virtualChamilo;
  689. if (!isset($virtualChamilo)) {
  690. api_not_allowed(
  691. true,
  692. 'You have to edit the configuration.php. Please check the readme file.'
  693. );
  694. }
  695. $coursePath = self::getConfig('vchamilo', 'course_real_root');
  696. $homePath = self::getConfig('vchamilo', 'home_real_root');
  697. $archivePath = self::getConfig('vchamilo', 'archive_real_root');
  698. $uploadPath = self::getConfig('vchamilo', 'upload_real_root');
  699. $cmdSql = self::getConfig('vchamilo', 'cmd_mysql');
  700. $cmdMySql = self::getConfig('vchamilo', 'cmd_mysqldump');
  701. if (empty($coursePath) || empty($homePath) || empty($uploadPath) || empty($archivePath) || empty($cmdSql) || empty($cmdMySql)) {
  702. api_not_allowed(true, 'You have to complete all plugin settings.');
  703. }
  704. $separator = DIRECTORY_SEPARATOR;
  705. $templatePath = api_get_path(SYS_PATH).'plugin'.$separator.'vchamilo'.$separator.'templates';
  706. $paths = [
  707. $coursePath,
  708. $homePath,
  709. $archivePath,
  710. $uploadPath,
  711. $templatePath
  712. ];
  713. foreach ($paths as $path) {
  714. $path = trim($path);
  715. if (is_dir($path)) {
  716. if (!is_writable($path)) {
  717. Display::addFlash(
  718. Display::return_message("Directory must have writable permissions: '$path'", 'warning')
  719. );
  720. };
  721. } else {
  722. Display::addFlash(
  723. Display::return_message("Directory doesn't exist: '$path'", 'warning')
  724. );
  725. }
  726. }
  727. }
  728. /**
  729. * @param object $instance
  730. * @return bool|\Doctrine\DBAL\Connection
  731. */
  732. public static function getConnectionFromInstance($instance, $getManager = false)
  733. {
  734. $dbParams = array(
  735. 'driver' => 'pdo_mysql',
  736. 'host' => $instance->db_host,
  737. 'user' => $instance->db_user,
  738. 'password' => $instance->db_password,
  739. //'dbname' => $instance->main_database,
  740. // Only relevant for pdo_sqlite, specifies the path to the SQLite database.
  741. //'path' => isset($_configuration['db_path']) ? $_configuration['db_path'] : '',
  742. // Only relevant for pdo_mysql, pdo_pgsql, and pdo_oci/oci8,
  743. //'port' => isset($_configuration['db_port']) ? $_configuration['db_port'] : '',
  744. );
  745. if (!empty($instance->main_database)) {
  746. $dbParams['dbname'] = $instance->main_database;
  747. }
  748. try {
  749. $database = new \Database();
  750. $manager = $database->connect(
  751. $dbParams,
  752. api_get_configuration_value('root_sys'),
  753. api_get_configuration_value('root_sys'),
  754. false,
  755. true
  756. );
  757. if ($getManager) {
  758. return $manager;
  759. }
  760. return $manager->getConnection();
  761. } catch (Exception $e) {
  762. error_log($e->getMessage());
  763. }
  764. return false;
  765. }
  766. /**
  767. * @param $data
  768. */
  769. public static function addInstance($data)
  770. {
  771. if (isset($data->what)) {
  772. unset($data->what);
  773. }
  774. if (isset($data->submitbutton)) {
  775. unset($data->submitbutton);
  776. }
  777. if (isset($data->id)) {
  778. unset($data->id);
  779. }
  780. if (isset($data->vid)) {
  781. unset($data->vid);
  782. }
  783. if (isset($data->testconnection)) {
  784. unset($data->testconnection);
  785. }
  786. if (isset($data->testdatapath)) {
  787. unset($data->testdatapath);
  788. }
  789. $registeronly = $data->registeronly;
  790. unset($data->registeronly);
  791. $data->lastcron = 0;
  792. $data->lastcrongap = 0;
  793. $data->croncount = 0;
  794. if (isset($data->template) && !empty($data->template)) {
  795. $template = $data->template;
  796. } else {
  797. $template = '';
  798. }
  799. $mainDatabase = api_get_configuration_value('main_database');
  800. if ($mainDatabase == $data->main_database) {
  801. Display::addFlash(
  802. Display::return_message('You cannot use the same database as the chamilo master', 'error')
  803. );
  804. return ;
  805. }
  806. $databaseName = $data->main_database;
  807. $data->main_database = '';
  808. $connection = Virtual::getConnectionFromInstance($data);
  809. $data->main_database = $databaseName;
  810. if (!$connection) {
  811. Display::addFlash(
  812. Display::return_message(
  813. 'Cannot connect to database with params: '.print_r($data, 1),
  814. 'error'
  815. )
  816. );
  817. return ;
  818. }
  819. $data->root_web = api_add_trailing_slash($data->root_web);
  820. $data->archive_url = api_add_trailing_slash($data->archive_url);
  821. $data->home_url = api_add_trailing_slash($data->home_url);
  822. $data->upload_url = api_add_trailing_slash($data->upload_url);
  823. $data->course_url = api_add_trailing_slash($data->course_url);
  824. if (substr($data->root_web, 0, 4) != 'http') {
  825. $data->root_web = api_get_protocol().'://'.$data->root_web;
  826. }
  827. self::ctrace('Registering: '.$data->root_web);
  828. $tablename = Database::get_main_table('vchamilo');
  829. $sql = "SELECT * FROM $tablename
  830. WHERE root_web = '".Database::escape_string($data->root_web)."'";
  831. $result = Database::query($sql);
  832. if (Database::num_rows($result)) {
  833. Database::update($tablename, $data, ['root_web = ?' => $data->root_web]);
  834. $virtualInfo = Database::fetch_array($result);
  835. $slug = $virtualInfo['slug'];
  836. } else {
  837. $slug = $data->slug = Virtual::getSlugFromUrl($data->root_web);
  838. if (empty($slug)) {
  839. Display::addFlash(
  840. Display::return_message('Cannot create slug from url: '.$data->root_web, 'error')
  841. );
  842. return ;
  843. }
  844. Database::insert($tablename, (array) $data);
  845. }
  846. if ($registeronly) {
  847. // Stop it now.
  848. self::ctrace('Registering only. out.');
  849. Virtual::redirect(api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php');
  850. }
  851. // or we continue with physical creation
  852. self::createDirsFromSlug($slug);
  853. if (!$template) {
  854. // Create empty database for install
  855. self::ctrace("Creating database");
  856. Virtual::createDatabase($data);
  857. } else {
  858. // Deploy template database
  859. self::ctrace("Creating databases from template '$template'");
  860. Virtual::createDatabase($data);
  861. self::ctrace("Loading data template '$template'");
  862. Virtual::loadDbTemplate($data, $template);
  863. self::ctrace("Coying files from template '$template'");
  864. Virtual::loadFilesFromTemplate($data, $template);
  865. }
  866. // pluging in site name institution
  867. $settingstable = $data->main_database.'.settings_current';
  868. $accessurltable = $data->main_database.'.access_url';
  869. $sitename = Database::escape_string($data->sitename);
  870. $institution = Database::escape_string($data->institution);
  871. $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$sitename}'
  872. WHERE variable = 'siteName' AND category = 'Platform' ";
  873. $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$institution}'
  874. WHERE variable = 'institution' AND category = 'Platform' ";
  875. $sqls[] = "UPDATE {$accessurltable} SET url = '{$data->root_web}' WHERE id = '1' ";
  876. foreach ($sqls as $sql) {
  877. Database::query($sql);
  878. }
  879. self::ctrace("Finished");
  880. }
  881. /**
  882. * @param stdClass $data
  883. * @param string $fromVersion
  884. */
  885. public static function importInstance($data, $fromVersion)
  886. {
  887. if (isset($data->what)) {
  888. unset($data->what);
  889. }
  890. if (isset($data->submitbutton)) {
  891. unset($data->submitbutton);
  892. }
  893. if (isset($data->id)) {
  894. unset($data->id);
  895. }
  896. if (isset($data->vid)) {
  897. unset($data->vid);
  898. }
  899. if (isset($data->testconnection)) {
  900. unset($data->testconnection);
  901. }
  902. if (isset($data->testdatapath)) {
  903. unset($data->testdatapath);
  904. }
  905. $fromCoursePath = $data->course_path;
  906. $fromHomePath = $data->home_path;
  907. $fromUploadPath = $data->upload_path;
  908. unset($data->course_path);
  909. unset($data->home_path);
  910. unset($data->upload_path);
  911. $newDatabase = clone $data;
  912. $newDatabase->main_database = $newDatabase->import_to_main_database;
  913. $newDatabase->db_user = $newDatabase->import_to_db_user;
  914. $newDatabase->db_password = $newDatabase->import_to_db_password;
  915. $newDatabase->db_host = $newDatabase->import_to_db_host;
  916. unset($newDatabase->import_to_main_database);
  917. unset($newDatabase->import_to_db_user);
  918. unset($newDatabase->import_to_db_password);
  919. unset($newDatabase->import_to_db_host);
  920. unset($data->import_to_main_database);
  921. unset($data->import_to_db_user);
  922. unset($data->import_to_db_password);
  923. unset($data->import_to_db_host);
  924. $data->lastcron = 0;
  925. $data->lastcrongap = 0;
  926. $data->croncount = 0;
  927. $mainDatabase = api_get_configuration_value('main_database');
  928. if ($mainDatabase == $data->main_database) {
  929. Display::addFlash(
  930. Display::return_message('You cannot use the same database as the chamilo master', 'error')
  931. );
  932. return false;
  933. }
  934. self::ctrace('Registering: '.$data->root_web);
  935. $table = Database::get_main_table('vchamilo');
  936. $sql = "SELECT * FROM $table
  937. WHERE root_web = '".Database::escape_string($data->root_web)."'";
  938. $result = Database::query($sql);
  939. $id = null;
  940. if (Database::num_rows($result)) {
  941. Display::addFlash(
  942. Display::return_message('Instance was already added: '.$data->root_web, 'error')
  943. );
  944. return false;
  945. } else {
  946. /** @var EntityManager $em */
  947. $em = Virtual::getConnectionFromInstance($data, true);
  948. if ($em) {
  949. $connection = $em->getConnection();
  950. $statement = $connection->query('SELECT * FROM settings_current');
  951. $settings = $statement->fetchAll();
  952. $settings = array_column(
  953. $settings,
  954. 'selected_value',
  955. 'variable'
  956. );
  957. $institution = $settings['Institution'];
  958. $siteName = $settings['siteName'];
  959. $newDatabase->sitename = $siteName;
  960. $newDatabase->institution = $institution;
  961. $slug = $newDatabase->slug = $data->slug = Virtual::getSlugFromUrl($data->root_web);
  962. $id = Database::insert($table, (array)$newDatabase);
  963. }
  964. }
  965. if (!$id) {
  966. var_dump($data);
  967. throw new Exception('Was not registered');
  968. }
  969. if (empty($slug)) {
  970. throw new Exception('Slug is empty');
  971. }
  972. self::createDirsFromSlug($slug);
  973. $databaseCreated = Virtual::createDatabase($newDatabase);
  974. if (!$databaseCreated) {
  975. Display::addFlash(
  976. Display::return_message('Error while creating a DB', 'error')
  977. );
  978. return false;
  979. }
  980. $coursePath = self::getConfig('vchamilo', 'course_real_root').'/'.$slug;
  981. $homePath = self::getConfig('vchamilo', 'home_real_root').'/'.$slug;
  982. $uploadPath = self::getConfig('vchamilo', 'upload_real_root').'/'.$slug;
  983. $dumpFile = api_get_path(SYS_ARCHIVE_PATH).uniqid($data->main_database.'_dump_', true).'.sql';
  984. self::ctrace('Create backup from "'.$data->main_database.'" here: '.$dumpFile.' ');
  985. Virtual::backupDatabase($data, $dumpFile);
  986. $sqlcmd = Virtual::getDatabaseDumpCmd($newDatabase);
  987. $sqlcmd = str_replace('%DATABASE%', $newDatabase->main_database, $sqlcmd);
  988. $import = $sqlcmd.$dumpFile;
  989. // Execute the command.
  990. if (!defined('CLI_SCRIPT')) {
  991. putenv('LANG=en_US.utf-8');
  992. }
  993. // ensure utf8 is correctly handled by php exec()
  994. // @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input
  995. $result = exec($import, $output, $return);
  996. self::ctrace('Restore backup here "'.$newDatabase->main_database.'" : <br />'.$import.' ');
  997. self::ctrace($result);
  998. $command = new \Chash\Command\Installation\UpgradeDatabaseCommand();
  999. // Creates the helper set
  1000. $helperSet = \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($em);
  1001. $helpers = array(
  1002. 'configuration' => new Chash\Helpers\ConfigurationHelper(),
  1003. 'dialog' => new \Symfony\Component\Console\Helper\QuestionHelper(),
  1004. );
  1005. foreach ($helpers as $name => $helper) {
  1006. $helperSet->set($helper, $name);
  1007. }
  1008. $command->setHelperSet($helperSet);
  1009. $tmpFile = tmpfile();
  1010. $outputStream = new \Symfony\Component\Console\Output\BufferedOutput($tmpFile);
  1011. $arguments = array(
  1012. 'from-version' => $fromVersion, // @todo change value
  1013. 'to-version' => '1.11.x',
  1014. 'host' => $newDatabase->db_host,
  1015. 'username' => $newDatabase->db_user,
  1016. 'password' => $newDatabase->db_password,
  1017. 'db_name' => $newDatabase->main_database,
  1018. 'root_sys' => api_get_configuration_value('root_sys')
  1019. );
  1020. $input = new ArrayInput($arguments);
  1021. $command->run($input, $outputStream);
  1022. error_log($outputStream->fetch());
  1023. if (file_exists($dumpFile)) {
  1024. unlink($dumpFile);
  1025. }
  1026. // Course
  1027. self::ctrace("Copy from '$fromCoursePath' to backup '$coursePath' ");
  1028. copyDirTo(
  1029. self::chopLastSlash($fromCoursePath),
  1030. self::chopLastSlash($coursePath),
  1031. false
  1032. );
  1033. // Home
  1034. self::ctrace("Copy from '$fromHomePath' to backup '$homePath' ");
  1035. copyDirTo(
  1036. self::chopLastSlash($fromHomePath),
  1037. self::chopLastSlash($homePath),
  1038. false
  1039. );
  1040. // Upload
  1041. self::ctrace("Copy from '$fromUploadPath' to backup '$uploadPath' ");
  1042. copyDirTo(
  1043. self::chopLastSlash($fromUploadPath),
  1044. self::chopLastSlash($uploadPath),
  1045. false
  1046. );
  1047. self::ctrace("Finished");
  1048. }
  1049. /**
  1050. * @param string $slug
  1051. *
  1052. * @return string
  1053. */
  1054. public static function createDirsFromSlug($slug)
  1055. {
  1056. // We continue with physical creation
  1057. // Create course directory for operations.
  1058. // this is very important here (DO NOT USE api_get_path() !!) because storage may be remotely located
  1059. $absAlternateCourse = Virtual::getConfig('vchamilo', 'course_real_root');
  1060. $courseDir = $absAlternateCourse.'/'.$slug;
  1061. if (!is_dir($courseDir)) {
  1062. self::ctrace("Creating physical course dir in $courseDir");
  1063. mkdir($courseDir, 0777, true);
  1064. // initiate default index
  1065. $indexFile = $courseDir.'/index.html';
  1066. if ($indexFile) {
  1067. file_put_contents($indexFile, self::getDefaultCourseIndexFragment());
  1068. }
  1069. $htaccessFile = $courseDir.'/.htaccess';
  1070. if ($htaccessFile) {
  1071. file_put_contents($htaccessFile, self::getHtaccessFragment($slug));
  1072. }
  1073. }
  1074. $absAlternateHome = Virtual::getConfig('vchamilo', 'home_real_root');
  1075. $absAlternateArchive = Virtual::getConfig('vchamilo', 'archive_real_root');
  1076. $absAlternateUpload = Virtual::getConfig('vchamilo', 'upload_real_root');
  1077. // absalternatehome is a vchamilo config setting that tells where the
  1078. // real physical storage for home pages are.
  1079. $homeDir = $absAlternateHome.'/'.$slug;
  1080. $archiveDir = $absAlternateArchive.'/'.$slug;
  1081. $uploadDir = $absAlternateUpload.'/'.$slug;
  1082. $dirs = [
  1083. $homeDir,
  1084. $archiveDir,
  1085. $uploadDir
  1086. ];
  1087. foreach ($dirs as $dir) {
  1088. self::ctrace("Making dir as $dir");
  1089. if (!is_dir($dir)) {
  1090. if (!mkdir($dir, 0777, true)) {
  1091. self::ctrace("Error creating dir $dir \n");
  1092. }
  1093. }
  1094. }
  1095. }
  1096. /**
  1097. * @param $id
  1098. * @return array|mixed
  1099. */
  1100. public static function getInstance($id)
  1101. {
  1102. $vhost = new stdClass();
  1103. if ($id) {
  1104. $id = (int) $id;
  1105. $sql = "SELECT * FROM vchamilo WHERE id = $id";
  1106. $result = Database::query($sql);
  1107. $vhost = (object) Database::fetch_array($result, 'ASSOC');
  1108. }
  1109. return $vhost;
  1110. }
  1111. /**
  1112. * @param stdClass $instance
  1113. *
  1114. * @return bool|string returns the original version of the app
  1115. */
  1116. public static function canBeUpgraded($instance)
  1117. {
  1118. $connection = Virtual::getConnectionFromInstance($instance);
  1119. if ($connection) {
  1120. $sql = 'SELECT * FROM settings_current WHERE variable = "chamilo_database_version"';
  1121. $statement = $connection->query($sql);
  1122. $settings = $statement->fetchAll();
  1123. $settings = array_column($settings, 'selected_value', 'variable');
  1124. $version = $settings['chamilo_database_version'];
  1125. $versionParts = explode('.', $version);
  1126. $version = implode('.', [$versionParts[0], $versionParts[1], '0']);
  1127. $currentVersion = api_get_setting('chamilo_database_version');
  1128. $versionParts = explode('.', $currentVersion);
  1129. $currentVersion = implode(
  1130. '.',
  1131. [$versionParts[0], $versionParts[1], '0']
  1132. );
  1133. if (version_compare($version, $currentVersion, '<')) {
  1134. return $version;
  1135. }
  1136. }
  1137. return false;
  1138. }
  1139. /**
  1140. * @return array
  1141. */
  1142. public static function getEncryptList()
  1143. {
  1144. $encryptList = [
  1145. 'bcrypt',
  1146. 'sha1',
  1147. 'md5',
  1148. 'none'
  1149. ];
  1150. return array_combine($encryptList, $encryptList);
  1151. }
  1152. }