global.inc.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is a bootstrap file that loads all Chamilo dependencies including:
  5. *
  6. * - Loading Chamilo settings in main/inc/configuration.php
  7. * - Loading mysql database (Using Doctrine ORM or the Classic way: Database;;query())
  8. * - Twig templates
  9. * - Loading language files
  10. * - Loading mail settings (smtp/sendmail/mail)
  11. * - Debug (Using Monolog)
  12. * - Redirecting to the main/install folder if the configuration.php file does not exists. *
  13. *
  14. * It's recommended that ALL Chamilo scripts include this file.
  15. * This script returns a $app Application instance so you have access to all the services.
  16. *
  17. * @package chamilo.include
  18. * @todo use the $_configuration array for all the needed variables
  19. *
  20. */
  21. //@todo will be removed before a stable release
  22. $mtime = microtime();
  23. $mtime = explode(" ", $mtime);
  24. $mtime = $mtime[1] + $mtime[0];
  25. $starttime = $mtime;
  26. define('START', $starttime);
  27. // Showing/hiding error codes in global error messages.
  28. //define('SHOW_ERROR_CODES', false);
  29. // Determine the directory path where this current file lies.
  30. // This path will be useful to include the other intialisation files.
  31. $includePath = dirname(__FILE__);
  32. // @todo Isn't this file renamed to configuration.inc.php yet?
  33. // Include the main Chamilo platform configuration file.
  34. $main_configuration_file_path = $includePath.'/conf/configuration.php';
  35. $configurationYML = $includePath.'/conf/configuration.yml';
  36. $already_installed = false;
  37. if (file_exists($main_configuration_file_path)) {
  38. require_once $main_configuration_file_path;
  39. $already_installed = true;
  40. } else {
  41. $_configuration = array();
  42. }
  43. if (file_exists($configurationYML)) {
  44. $already_installed = true;
  45. }
  46. //Redirects to the main/install/ page
  47. /*
  48. if (!$already_installed) {
  49. $global_error_code = 2;
  50. // The system has not been installed yet.
  51. require $includePath.'/global_error_message.inc.php';
  52. die();
  53. }*/
  54. // Include the main Chamilo platform library file.
  55. require_once $includePath.'/lib/main_api.lib.php';
  56. // Specification for usernames:
  57. // 1. ASCII-letters, digits, "." (dot), "_" (underscore) are acceptable, 40 characters maximum length.
  58. // 2. Empty username is formally valid, but it is reserved for the anonymous user.
  59. // 3. Checking the login_is_email portal setting in order to accept 100 chars maximum
  60. $default_username_length = 40;
  61. if (api_get_setting('login_is_email') == 'true') {
  62. $default_username_length = 100;
  63. }
  64. define('USERNAME_MAX_LENGTH', $default_username_length);
  65. // Do not over-use this variable. It is only for this script's local use.
  66. $lib_path = api_get_path(LIBRARY_PATH);
  67. // Fix bug in IIS that doesn't fill the $_SERVER['REQUEST_URI'].
  68. api_request_uri();
  69. // Add the path to the pear packages to the include path
  70. ini_set('include_path', api_create_include_path_setting());
  71. // This is for compatibility with MAC computers.
  72. ini_set('auto_detect_line_endings', '1');
  73. //Fixes Htmlpurifier autoloader issue with composer
  74. define('HTMLPURIFIER_PREFIX', $lib_path.'htmlpurifier/library');
  75. //mpdf constants
  76. define("_MPDF_TEMP_PATH", api_get_path(SYS_ARCHIVE_PATH));
  77. define('_MPDF_PATH', api_get_path(LIBRARY_PATH).'mpdf/');
  78. //Composer autoloader
  79. require_once __DIR__.'../../../vendor/autoload.php';
  80. //Start Silex
  81. use Silex\Application;
  82. use Symfony\Component\HttpFoundation\RedirectResponse;
  83. use Symfony\Component\HttpFoundation\Response;
  84. use Symfony\Component\HttpKernel\Exception\HttpException;
  85. use Symfony\Component\Yaml\Parser;
  86. $app = new Application();
  87. //Overwriting $_configuration
  88. if (file_exists($configurationYML)) {
  89. $yaml = new Parser();
  90. $_configuration = $yaml->parse(file_get_contents($configurationYML));
  91. }
  92. // Ensure that _configuration is in the global scope before loading
  93. // main_api.lib.php. This is particularly helpful for unit tests
  94. if (!isset($GLOBALS['_configuration'])) {
  95. $GLOBALS['_configuration'] = $_configuration;
  96. }
  97. // Code for trnasitional purposes, it can be removed right before the 1.8.7 release.
  98. if (empty($_configuration['system_version'])) {
  99. $_configuration['system_version'] = (!empty($_configuration['dokeos_version']) ? $_configuration['dokeos_version'] : '');
  100. $_configuration['system_stable'] = (!empty($_configuration['dokeos_stable']) ? $_configuration['dokeos_stable'] : '');
  101. $_configuration['software_url'] = 'http://www.chamilo.org/';
  102. }
  103. // For backward compatibility.
  104. $_configuration['dokeos_version'] = $_configuration['system_version'];
  105. $_configuration['dokeos_stable'] = $_configuration['system_stable'];
  106. $userPasswordCrypted = (!empty($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1');
  107. $app['configuration_file'] = $main_configuration_file_path;
  108. $app['configuration_yml_file'] = $configurationYML;
  109. $app['configuration'] = $_configuration;
  110. $app['languages_file'] = array();
  111. $app['installed'] = $already_installed;
  112. //require_once __DIR__.'/../../resources/config/prod.php';
  113. require_once __DIR__.'/../../resources/config/dev.php';
  114. //Setting HttpCacheService provider in order to use do: $app['http_cache']->run();
  115. /*
  116. $app->register(new Silex\Provider\HttpCacheServiceProvider(), array(
  117. 'http_cache.cache_dir' => $app['http_cache.cache_dir'].'/',
  118. ));*/
  119. //$app->register(new Silex\Provider\SessionServiceProvider());
  120. /*
  121. use Symfony\Component\Security\Core\User\UserProviderInterface;
  122. use Symfony\Component\Security\Core\User\UserInterface;
  123. use Symfony\Component\Security\Core\User\User;
  124. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  125. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  126. use Doctrine\DBAL\Connection;
  127. class UserProvider implements UserProviderInterface
  128. {
  129. private $conn;
  130. public function __construct(Connection $conn)
  131. {
  132. $this->conn = $conn;
  133. }
  134. public function loadUserByUsername($username)
  135. {
  136. $stmt = $this->conn->executeQuery('SELECT * FROM users WHERE username = ?', array(strtolower($username)));
  137. if (!$user = $stmt->fetch()) {
  138. throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
  139. }
  140. $roles = 'student';
  141. echo $user['username'];exit;
  142. return new User($user['username'], $user['password'], explode(',', $roles), true, true, true, true);
  143. }
  144. public function refreshUser(UserInterface $user)
  145. {
  146. if (!$user instanceof User) {
  147. throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
  148. }
  149. return $this->loadUserByUsername($user->getUsername());
  150. }
  151. public function supportsClass($class)
  152. {
  153. return $class === 'Symfony\Component\Security\Core\User\User';
  154. }
  155. }
  156. $app->register(new Silex\Provider\SecurityServiceProvider(), array(
  157. 'security.firewalls' => array(
  158. 'secured' => array(
  159. 'pattern' => '^/admin/',
  160. 'form' => array(
  161. 'login_path' => '/login',
  162. 'check_path' => '/admin/login_check'
  163. ),
  164. 'logout' => array('path' => '/logout', 'target' => '/'),
  165. 'users' => $app->share(function() use ($app) {
  166. return new UserProvider($app['db']);
  167. })
  168. )
  169. ),
  170. 'security.role_hierarchy'=> array(
  171. 'ROLE_ADMIN' => array('ROLE_EDITOR'),
  172. "ROLE_EDITOR" => array('ROLE_WRITER'),
  173. "ROLE_WRITER" => array('ROLE_USER'),
  174. "ROLE_USER" => array("ROLE_SUSCRIBER"),
  175. )
  176. ));*/
  177. //URL generator provider
  178. $app->register(new Silex\Provider\UrlGeneratorServiceProvider());
  179. //Validator provider
  180. $app->register(new Silex\Provider\ValidatorServiceProvider());
  181. // Implements symfony2 translator
  182. $app->register(new Silex\Provider\TranslationServiceProvider(), array(
  183. 'locale' => 'en',
  184. 'locale_fallback' => 'en'
  185. ));
  186. //Handling po files
  187. /*
  188. use Symfony\Component\Translation\Loader\PoFileLoader;
  189. use Symfony\Component\Translation\Dumper\PoFileDumper;
  190. $app['translator'] = $app->share($app->extend('translator', function($translator, $app) {
  191. $translator->addLoader('pofile', new PoFileLoader());
  192. $language = api_get_language_interface();
  193. $iterator = new FilesystemIterator(api_get_path(SYS_PATH).'resources/locale/'.$language);
  194. $filter = new RegexIterator($iterator, '/\.(po)$/');
  195. foreach ($filter as $entry) {
  196. //$domain = $entry->getBasename('.inc.po');
  197. $locale = api_get_language_isocode($language); //'es_ES';
  198. //var_dump($locale);exit;
  199. //$translator->addResource('pofile', $entry->getPathname(), $locale, $domain);
  200. $translator->addResource('pofile', $entry->getPathname(), $locale, 'messages');
  201. }
  202. return $translator;
  203. }));
  204. //$app['translator.domains'] = array();
  205. */
  206. // Classic way of render pages or the Controller approach
  207. $app['classic_layout'] = false;
  208. $app['breadcrumb'] = array();
  209. //Form provider
  210. $app->register(new Silex\Provider\FormServiceProvider());
  211. /*
  212. use Doctrine\Common\Persistence\AbstractManagerRegistry;
  213. class ManagerRegistry extends AbstractManagerRegistry
  214. {
  215. protected $container;
  216. protected function getService($name)
  217. {
  218. return $this->container[$name];
  219. }
  220. protected function resetService($name)
  221. {
  222. unset($this->container[$name]);
  223. }
  224. public function getAliasNamespace($alias)
  225. {
  226. throw new \BadMethodCallException('Namespace aliases not supported.');
  227. }
  228. public function setContainer(Application $container)
  229. {
  230. $this->container = $container;
  231. }
  232. }
  233. $app['form.extensions'] = $app->share($app->extend('form.extensions', function ($extensions, $app) {
  234. $managerRegistry = new ManagerRegistry(null, array(), array('orm.em'), null, null, $app['orm.proxies_namespace']);
  235. $managerRegistry->setContainer($app);
  236. $extensions[] = new \Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension($managerRegistry);
  237. return $extensions;
  238. }));*/
  239. //The script is allowed? This setting is modified when calling api_is_not_allowed()
  240. $app['allowed'] = true;
  241. //Setting the Twig service provider
  242. $app->register(
  243. new Silex\Provider\TwigServiceProvider(),
  244. array(
  245. 'twig.path' => array(
  246. api_get_path(SYS_CODE_PATH).'template', //template folder
  247. api_get_path(SYS_PLUGIN_PATH) //plugin folder
  248. ),
  249. 'twig.form.templates' => array('form_div_layout.html.twig', 'default/form/form_custom_template.tpl'),
  250. 'twig.options' => array(
  251. 'debug' => $app['debug'],
  252. 'charset' => 'utf-8',
  253. 'strict_variables' => false,
  254. 'autoescape' => false,
  255. 'cache' => $app['debug'] ? false : $app['twig.cache.path'],
  256. 'optimizations' => -1, // turn on optimizations with -1
  257. )
  258. )
  259. );
  260. //Setting Twig options
  261. $app['twig'] = $app->share(
  262. $app->extend('twig', function ($twig, $app) {
  263. $twig->addFilter('get_lang', new Twig_Filter_Function('get_lang'));
  264. $twig->addFilter('get_path', new Twig_Filter_Function('api_get_path'));
  265. $twig->addFilter('get_setting', new Twig_Filter_Function('api_get_setting'));
  266. $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
  267. $twig->addFilter('return_message', new Twig_Filter_Function('Display::return_message_and_translate'));
  268. $twig->addFilter('display_page_header', new Twig_Filter_Function('Display::page_header_and_translate'));
  269. $twig->addFilter(
  270. 'display_page_subheader',
  271. new Twig_Filter_Function('Display::page_subheader_and_translate')
  272. );
  273. $twig->addFilter('icon', new Twig_Filter_Function('Template::get_icon_path'));
  274. $twig->addFilter('format_date', new Twig_Filter_Function('Template::format_date'));
  275. return $twig;
  276. })
  277. );
  278. //Setting controllers as services
  279. $app->register(new Silex\Provider\ServiceControllerServiceProvider());
  280. //Monolog and web profiler only available if cache is writable
  281. if (is_writable($app['cache.path'])) {
  282. /*
  283. Adding Monolog service provider
  284. Monolog use examples
  285. $app['monolog']->addDebug('Testing the Monolog logging.');
  286. $app['monolog']->addInfo('Testing the Monolog logging.');
  287. $app['monolog']->addError('Testing the Monolog logging.');
  288. */
  289. $app->register(
  290. new Silex\Provider\MonologServiceProvider(),
  291. array(
  292. 'monolog.logfile' => $app['chamilo.log'],
  293. 'monolog.name' => 'chamilo',
  294. )
  295. );
  296. //Adding web profiler
  297. /*
  298. if ($app['debug']) {
  299. $app->register($p = new Silex\Provider\WebProfilerServiceProvider(), array(
  300. 'profiler.cache_dir' => $app['profiler.cache_dir'],
  301. ));
  302. $app->mount('/_profiler', $p);
  303. }
  304. */
  305. }
  306. //Setting Doctrine service provider (DBAL)
  307. if (isset($_configuration['main_database'])) {
  308. $app->register(new Silex\Provider\DoctrineServiceProvider(), array(
  309. 'db.options' => array(
  310. 'driver' => 'pdo_mysql',
  311. 'dbname' => $_configuration['main_database'],
  312. 'user' => $_configuration['db_user'],
  313. 'password' => $_configuration['db_password'],
  314. 'host' => $_configuration['db_host'],
  315. 'driverOptions' => array(
  316. 1002 => 'SET NAMES utf8'
  317. )
  318. )
  319. ));
  320. //Setting Doctrine ORM
  321. $app->register(new Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider, array(
  322. 'orm.auto_generate_proxies' => true,
  323. "orm.proxies_dir" => $app['db.orm.proxies_dir'],
  324. //'orm.proxies_namespace' => '\Doctrine\ORM\Proxy\Proxy',
  325. "orm.em.options" => array(
  326. "mappings" => array(
  327. array(
  328. "type" => "annotation",
  329. "namespace" => "Entity",
  330. "path" => api_get_path(INCLUDE_PATH).'Entity',
  331. )
  332. ),
  333. ),
  334. ));
  335. //Setting Doctrine2 extensions
  336. $timestampableListener = new \Gedmo\Timestampable\TimestampableListener();
  337. $app['db.event_manager']->addEventSubscriber($timestampableListener);
  338. $sluggableListener = new \Gedmo\Sluggable\SluggableListener();
  339. $app['db.event_manager']->addEventSubscriber($sluggableListener);
  340. $sortableListener = new \Gedmo\Sortable\SortableListener();
  341. $app['db.event_manager']->addEventSubscriber($sortableListener);
  342. }
  343. $app['is_admin'] = false;
  344. //Creating a Chamilo service provider
  345. use Silex\ServiceProviderInterface;
  346. class ChamiloServiceProvider implements ServiceProviderInterface
  347. {
  348. public function register(Application $app)
  349. {
  350. //Template
  351. $app['template'] = $app->share(function () use ($app) {
  352. $template = new Template(null, $app);
  353. return $template;
  354. });
  355. }
  356. public function boot(Application $app)
  357. {
  358. }
  359. }
  360. //Registering Chamilo service provider
  361. $app->register(new ChamiloServiceProvider(), array());
  362. //Manage error messages
  363. $app->error(
  364. function (\Exception $e, $code) use ($app) {
  365. if ($app['debug']) {
  366. //return;
  367. }
  368. if (isset($code)) {
  369. switch ($code) {
  370. case 404:
  371. $message = 'The requested page could not be found.';
  372. break;
  373. default:
  374. //$message = 'We are sorry, but something went terribly wrong.';
  375. $message = $e->getMessage();
  376. }
  377. } else {
  378. $code = null;
  379. $message = null;
  380. }
  381. //$code = ($e instanceof HttpException) ? $e->getStatusCode() : 500;
  382. $app['template']->assign('error_code', $code);
  383. $app['template']->assign('error_message', $message);
  384. $response = $app['template']->render_layout('error.tpl');
  385. return new Response($response);
  386. }
  387. );
  388. //Prompts Doctrine SQL queries using monolog
  389. if ($app['debug'] && isset($_configuration['main_database'])) {
  390. $logger = new Doctrine\DBAL\Logging\DebugStack();
  391. $app['db.config']->setSQLLogger($logger);
  392. $app->after(function() use ($app, $logger) {
  393. // Log all queries as DEBUG.
  394. foreach ( $logger->queries as $query ) {
  395. $app['monolog']->debug($query['sql'], array('params' =>$query['params'], 'types' => $query['types']));
  396. }
  397. });
  398. }
  399. //Default template settings loaded in template.inc.php
  400. $app['template.show_header'] = true;
  401. $app['template.show_footer'] = true;
  402. $app['template.show_learnpath'] = true;
  403. $app['template.hide_global_chat'] = true;
  404. $app['template.load_plugins'] = true;
  405. //Default template style
  406. $app['template_style'] = 'default';
  407. //Default layout
  408. $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
  409. //Database constants
  410. require_once $lib_path.'database.constants.inc.php';
  411. require_once $lib_path.'text.lib.php';
  412. require_once $lib_path.'array.lib.php';
  413. require_once $lib_path.'events.lib.inc.php';
  414. require_once $lib_path.'online.inc.php';
  415. /* Database connection (for backward compatibility) */
  416. global $database_connection;
  417. // Connect to the server database and select the main chamilo database.
  418. if (!($conn_return = @Database::connect(
  419. array(
  420. 'server' => $_configuration['db_host'],
  421. 'username' => $_configuration['db_user'],
  422. 'password' => $_configuration['db_password'],
  423. 'persistent' => $_configuration['db_persistent_connection']
  424. // When $_configuration['db_persistent_connection'] is set, it is expected to be a boolean type.
  425. )
  426. ))
  427. ) {
  428. //$app->abort(500, "Database is unavailable"); //error 3
  429. }
  430. /*
  431. if (!$_configuration['db_host']) {
  432. //$app->abort(500, "Database is unavailable"); //error 3
  433. }*/
  434. /* RETRIEVING ALL THE CHAMILO CONFIG SETTINGS FOR MULTIPLE URLs FEATURE*/
  435. if (!empty($_configuration['multiple_access_urls'])) {
  436. $_configuration['access_url'] = 1;
  437. $access_urls = api_get_access_urls();
  438. $protocol = ((!empty($_SERVER['HTTPS']) && strtoupper($_SERVER['HTTPS']) != 'OFF') ? 'https' : 'http').'://';
  439. $request_url1 = $protocol.$_SERVER['SERVER_NAME'].'/';
  440. $request_url2 = $protocol.$_SERVER['HTTP_HOST'].'/';
  441. foreach ($access_urls as & $details) {
  442. if ($request_url1 == $details['url'] or $request_url2 == $details['url']) {
  443. $_configuration['access_url'] = $details['id'];
  444. }
  445. }
  446. } else {
  447. $_configuration['access_url'] = 1;
  448. }
  449. $charset = 'UTF-8';
  450. $checkConnection = false;
  451. if (isset($_configuration['main_database'])) {
  452. // The system has not been designed to use special SQL modes that were introduced since MySQL 5.
  453. Database::query("set session sql_mode='';");
  454. $checkConnection = @Database::select_db($_configuration['main_database'], $database_connection);
  455. if ($checkConnection) {
  456. // Initialization of the database encoding to be used.
  457. Database::query("SET SESSION character_set_server='utf8';");
  458. Database::query("SET SESSION collation_server='utf8_general_ci';");
  459. /* Initialization of the default encodings */
  460. // The platform's character set must be retrieved at this early moment.
  461. /*$sql = "SELECT selected_value FROM settings_current WHERE variable = 'platform_charset';";
  462. $result = Database::query($sql);
  463. while ($row = @Database::fetch_array($result)) {
  464. $charset = $row[0];
  465. }
  466. if (empty($charset)) {
  467. $charset = 'UTF-8';
  468. }*/
  469. //Charset is UTF-8
  470. if (api_is_utf8($charset)) {
  471. // See Bug #1802: For UTF-8 systems we prefer to use "SET NAMES 'utf8'" statement in order to avoid a bizarre problem with Chinese language.
  472. Database::query("SET NAMES 'utf8';");
  473. } else {
  474. Database::query("SET CHARACTER SET '".Database::to_db_encoding($charset)."';");
  475. }
  476. Database::query("SET NAMES 'utf8';");
  477. }
  478. }
  479. // Preserving the value of the global variable $charset.
  480. $charset_initial_value = $charset;
  481. // Initialization of the internationalization library.
  482. api_initialize_internationalization();
  483. // Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
  484. api_set_internationalization_default_encoding($charset);
  485. // Start session after the internationalization library has been initialized
  486. //@todo use silex session provider instead of a custom class
  487. Chamilo::session()->start($already_installed);
  488. //@todo move this inside the before filter
  489. if ($already_installed && $checkConnection) {
  490. $settings_refresh_info = api_get_settings_params_simple(array('variable = ?' => 'settings_latest_update'));
  491. $settings_latest_update = $settings_refresh_info ? $settings_refresh_info['selected_value'] : null;
  492. $_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null;
  493. $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null;
  494. if (empty($_setting)) {
  495. api_set_settings_and_plugins();
  496. } else {
  497. if (isset($_setting['settings_latest_update']) && $_setting['settings_latest_update'] != $settings_latest_update) {
  498. api_set_settings_and_plugins();
  499. $_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null;
  500. $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null;
  501. }
  502. }
  503. }
  504. // Load allowed tag definitions for kses and/or HTMLPurifier.
  505. require_once $lib_path.'formvalidator/Rule/allowed_tags.inc.php';
  506. // which will then be usable from the banner and header scripts
  507. $app['this_section'] = SECTION_GLOBAL;
  508. // include the local (contextual) parameters of this course or section
  509. require $includePath.'/local.inc.php';
  510. //Include Chamilo Mail conf this is added here because the api_get_setting works
  511. //Fixes bug in Chamilo 1.8.7.1 array was not set
  512. $administrator['email'] = isset($administrator['email']) ? $administrator['email'] : 'admin@example.com';
  513. $administrator['name'] = isset($administrator['name']) ? $administrator['name'] : 'Admin';
  514. //Including mail settings
  515. if ($already_installed) {
  516. $mail_conf = api_get_path(CONFIGURATION_PATH).'mail.conf.php';
  517. if (file_exists($mail_conf)) {
  518. require_once $mail_conf;
  519. }
  520. }
  521. // Email service provider
  522. $app->register(new Silex\Provider\SwiftmailerServiceProvider(), array(
  523. 'swiftmailer.options' => array(
  524. 'host' => isset($platform_email['SMTP_HOST']) ? $platform_email['SMTP_HOST'] : null,
  525. 'port' => isset($platform_email['SMTP_PORT']) ? $platform_email['SMTP_PORT'] : null,
  526. 'username' => isset($platform_email['SMTP_USER']) ? $platform_email['SMTP_USER'] : null,
  527. 'password' => isset($platform_email['SMTP_PASS']) ? $platform_email['SMTP_PASS'] : null,
  528. 'encryption' => null,
  529. 'auth_mode' => null
  530. )
  531. ));
  532. //if (isset($platform_email['SMTP_MAILER']) && $platform_email['SMTP_MAILER'] == 'smtp') {
  533. $app['mailer'] = $app->share(function ($app) {
  534. return new \Swift_Mailer($app['swiftmailer.transport']);
  535. });
  536. // Check and modify the date of user in the track.e.online table
  537. if ($already_installed && !$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) {
  538. LoginCheck(isset($_user['user_id']) ? $_user['user_id'] : '');
  539. }
  540. /* Loading languages */
  541. // if we use the javascript version (without go button) we receive a get
  542. // if we use the non-javascript version (with the go button) we receive a post
  543. $user_language = api_get_user_language();
  544. // Include all files (first english and then current interface language)
  545. $app['this_script'] = isset($this_script) ? $this_script : null;
  546. // Checking if we have a valid language. If not we set it to the platform language.
  547. if ($already_installed) {
  548. $app['language_interface'] = $language_interface = api_get_language_interface();
  549. } else {
  550. $app['language_interface'] = $language_interface = 'english';
  551. }
  552. // Sometimes the variable $language_interface is changed
  553. // temporarily for achieving translation in different language.
  554. // We need to save the genuine value of this variable and
  555. // to use it within the function get_lang(...).
  556. $language_interface_initial_value = $language_interface;
  557. //load_translations($app);
  558. $langPath = api_get_path(SYS_LANG_PATH);
  559. $this_script = $app['this_script'];
  560. $language_interface = $app['language_interface'];
  561. /* This will only work if we are in the page to edit a sub_language */
  562. if (isset($this_script) && $this_script == 'sub_language') {
  563. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  564. // getting the arrays of files i.e notification, trad4all, etc
  565. $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(
  566. api_get_path(SYS_LANG_PATH).'english',
  567. true
  568. );
  569. //getting parent info
  570. $languageId = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
  571. $parent_language = SubLanguageManager::get_all_information_of_language($languageId);
  572. $subLanguageId = isset($_REQUEST['sub_language_id']) ? $_REQUEST['sub_language_id'] : null;
  573. //getting sub language info
  574. $sub_language = SubLanguageManager::get_all_information_of_language($subLanguageId);
  575. $english_language_array = $parent_language_array = $sub_language_array = array();
  576. if (!empty($language_files_to_load))
  577. foreach ($language_files_to_load as $language_file_item) {
  578. $lang_list_pre = array_keys($GLOBALS);
  579. //loading english
  580. $path = $langPath.'english/'.$language_file_item.'.inc.php';
  581. if (file_exists($path)) {
  582. include $path;
  583. }
  584. $lang_list_post = array_keys($GLOBALS);
  585. $lang_list_result = array_diff($lang_list_post, $lang_list_pre);
  586. unset($lang_list_pre);
  587. // english language array
  588. $english_language_array[$language_file_item] = compact($lang_list_result);
  589. //cleaning the variables
  590. foreach ($lang_list_result as $item) {
  591. unset(${$item});
  592. }
  593. $parent_file = $langPath.$parent_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  594. if (file_exists($parent_file) && is_file($parent_file)) {
  595. include_once $parent_file;
  596. }
  597. // parent language array
  598. $parent_language_array[$language_file_item] = compact($lang_list_result);
  599. //cleaning the variables
  600. foreach ($lang_list_result as $item) {
  601. unset(${$item});
  602. }
  603. if (!empty($sub_language)) {
  604. $sub_file = $langPath.$sub_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  605. if (file_exists($sub_file) && is_file($sub_file)) {
  606. include $sub_file;
  607. }
  608. }
  609. // sub language array
  610. $sub_language_array[$language_file_item] = compact($lang_list_result);
  611. //cleaning the variables
  612. foreach ($lang_list_result as $item) {
  613. unset(${$item});
  614. }
  615. }
  616. }
  617. /**
  618. * Include all necessary language files
  619. * - trad4all
  620. * - notification
  621. * - custom tool language files
  622. */
  623. $language_files = array();
  624. $language_files[] = 'trad4all';
  625. $language_files[] = 'notification';
  626. $language_files[] = 'accessibility';
  627. //@todo Added because userportal and index are loaded by a controller should be fixed when a $app['translator'] is configured
  628. $language_files[] = 'index';
  629. $language_files[] = 'courses';
  630. if (isset($language_file)) {
  631. if (!is_array($language_file)) {
  632. $language_files[] = $language_file;
  633. } else {
  634. $language_files = array_merge($language_files, $language_file);
  635. }
  636. }
  637. if (isset($app['languages_file'])) {
  638. $language_files = array_merge($language_files, $app['languages_file']);
  639. }
  640. // if a set of language files has been properly defined
  641. if (is_array($language_files)) {
  642. // if the sub-language feature is on
  643. if (api_get_setting('allow_use_sub_language') == 'true') {
  644. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  645. $parent_path = SubLanguageManager::get_parent_language_path($language_interface);
  646. foreach ($language_files as $index => $language_file) {
  647. // include English
  648. include $langPath.'english/'.$language_file.'.inc.php';
  649. // prepare string for current language and its parent
  650. $lang_file = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  651. $parent_lang_file = $langPath.$parent_path.'/'.$language_file.'.inc.php';
  652. // load the parent language file first
  653. if (file_exists($parent_lang_file)) {
  654. include $parent_lang_file;
  655. }
  656. // overwrite the parent language translations if there is a child
  657. if (file_exists($lang_file)) {
  658. include $lang_file;
  659. }
  660. }
  661. } else {
  662. // if the sub-languages feature is not on, then just load the
  663. // set language interface
  664. foreach ($language_files as $index => $language_file) {
  665. // include English
  666. include $langPath.'english/'.$language_file.'.inc.php';
  667. // prepare string for current language
  668. $langFile = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  669. if (file_exists($langFile)) {
  670. include $langFile;
  671. }
  672. }
  673. }
  674. }
  675. /* End loading languages */
  676. //error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
  677. error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
  678. if (api_get_setting('server_type') == 'test') {
  679. //error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
  680. } else {
  681. /*
  682. Server type is not test
  683. - normal error reporting level
  684. - full fake register globals block
  685. */
  686. //error_reporting(E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
  687. /*
  688. // TODO: These obsolete variables $HTTP_* to be check whether they are actually used.
  689. if (!isset($HTTP_GET_VARS)) {
  690. $HTTP_GET_VARS = $_GET;
  691. }
  692. if (!isset($HTTP_POST_VARS)) {
  693. $HTTP_POST_VARS = $_POST;
  694. }
  695. if (!isset($HTTP_POST_FILES)) {
  696. $HTTP_POST_FILES = $_FILES;
  697. }
  698. if (!isset($HTTP_SESSION_VARS)) {
  699. $HTTP_SESSION_VARS = $_SESSION;
  700. }
  701. if (!isset($HTTP_SERVER_VARS)) {
  702. $HTTP_SERVER_VARS = $_SERVER;
  703. }
  704. // Register SESSION variables into $GLOBALS
  705. if (sizeof($HTTP_SESSION_VARS)) {
  706. if (!is_array($_SESSION)) {
  707. $_SESSION = array();
  708. }
  709. foreach ($HTTP_SESSION_VARS as $key => $val) {
  710. $_SESSION[$key] = $HTTP_SESSION_VARS[$key];
  711. $GLOBALS[$key] = $HTTP_SESSION_VARS[$key];
  712. }
  713. }
  714. // Register SERVER variables into $GLOBALS
  715. if (sizeof($HTTP_SERVER_VARS)) {
  716. $_SERVER = array();
  717. foreach ($HTTP_SERVER_VARS as $key => $val) {
  718. $_SERVER[$key] = $HTTP_SERVER_VARS[$key];
  719. if (!isset($_SESSION[$key]) && $key != 'includePath' && $key != 'rootSys' && $key != 'lang_path' && $key != 'extAuthSource' && $key != 'thisAuthSource' && $key != 'main_configuration_file_path' && $key != 'phpDigIncCn' && $key != 'drs') {
  720. $GLOBALS[$key] = $HTTP_SERVER_VARS[$key];
  721. }
  722. }
  723. }*/
  724. }
  725. //error_reporting(-1);
  726. //Silex filters: before|after|finish
  727. $app->before(
  728. function () use ($app, $checkConnection) {
  729. if (!file_exists($app['configuration_file']) && !file_exists($app['configuration_yml_file'])) {
  730. return new RedirectResponse(api_get_path(WEB_CODE_PATH).'install');
  731. $app->abort(500, "Incorrect PHP version");
  732. }
  733. //Check the PHP version
  734. if (api_check_php_version() == false) {
  735. $app->abort(500, "Incorrect PHP version");
  736. }
  737. if ($checkConnection == false) {
  738. $app->abort(500, "Database not available");
  739. }
  740. if (!is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
  741. $app->abort(500, "archive folder must be writeable");
  742. }
  743. //var_dump($_setting);
  744. //$app['request']->getSession()->start();
  745. }
  746. );
  747. $app->finish(
  748. function () use ($app) {
  749. //@todo will be removed before a stable release
  750. $mtime = microtime();
  751. $mtime = explode(" ", $mtime);
  752. $mtime = $mtime[1] + $mtime[0];
  753. $message = "Page loaded in:".($mtime - START);
  754. $app['monolog']->addInfo($message);
  755. $message = "memory_get_usage: ".format_file_size(memory_get_usage(true));
  756. $app['monolog']->addInfo($message);
  757. $message = "memory_get_peak_usage: ".format_file_size(memory_get_peak_usage(true));
  758. $app['monolog']->addInfo($message);
  759. }
  760. );
  761. // The global variable $charset has been defined in a language file too (trad4all.inc.php), this is legacy situation.
  762. // So, we have to reassign this variable again in order to keep its value right.
  763. $charset = $charset_initial_value;
  764. // The global variable $text_dir has been defined in the language file trad4all.inc.php.
  765. // For determing text direction correspondent to the current language we use now information from the internationalization library.
  766. $text_dir = api_get_text_direction();
  767. //Update of the logout_date field in the table track_e_login (needed for the calculation of the total connection time)
  768. if (!isset($_SESSION['login_as']) && isset($_user)) {
  769. // if $_SESSION['login_as'] is set, then the user is an admin logged as the user
  770. $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  771. $sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='".$_user["user_id"]."' ORDER BY login_date DESC LIMIT 0,1";
  772. $q_last_connection = Database::query($sql_last_connection);
  773. if (Database::num_rows($q_last_connection) > 0) {
  774. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  775. // is the latest logout_date still relevant?
  776. $sql_logout_date = "SELECT logout_date FROM $tbl_track_login WHERE login_id=$i_id_last_connection";
  777. $q_logout_date = Database::query($sql_logout_date);
  778. $res_logout_date = convert_sql_date(Database::result($q_logout_date, 0, 'logout_date'));
  779. if ($res_logout_date < time() - $_configuration['session_lifetime']) {
  780. // it isn't, we should create a fresh entry
  781. event_login();
  782. // now that it's created, we can get its ID and carry on
  783. $q_last_connection = Database::query($sql_last_connection);
  784. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  785. }
  786. $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date=NOW() WHERE login_id='$i_id_last_connection'";
  787. Database::query($s_sql_update_logout_date);
  788. }
  789. }
  790. // Add language_measure_frequency to your main/inc/conf/configuration.php in
  791. // order to generate language variables frequency measurements (you can then
  792. // see them through main/cron/lang/langstats.php)
  793. // The langstat object will then be used in the get_lang() function.
  794. // This block can be removed to speed things up a bit as it should only ever
  795. // be used in development versions.
  796. if (isset($_configuration['language_measure_frequency']) && $_configuration['language_measure_frequency'] == 1) {
  797. require_once api_get_path(SYS_CODE_PATH).'/cron/lang/langstats.class.php';
  798. $langstats = new langstats();
  799. }
  800. //Default quota for the course documents folder
  801. $default_quota = api_get_setting('default_document_quotum');
  802. //Just in case the setting is not correctly set
  803. if (empty($default_quota)) {
  804. $default_quota = 100000000;
  805. }
  806. define('DEFAULT_DOCUMENT_QUOTA', $default_quota);
  807. $app['pages.controller'] = $app->share(function () use ($app) {
  808. return new PagesController($app['pages.repository']);
  809. });
  810. $app['index.controller'] = $app->share(function () use ($app) {
  811. return new ChamiloLMS\Controller\IndexController();
  812. });
  813. $app['userportal.controller'] = $app->share(function () use ($app) {
  814. return new ChamiloLMS\Controller\UserPortalController();
  815. });
  816. $app['learnpath.controller'] = $app->share(function () use ($app) {
  817. return new ChamiloLMS\Controller\LearnpathController();
  818. });
  819. /*
  820. class PostController
  821. {
  822. protected $repo;
  823. public function __construct()
  824. {
  825. }
  826. public function indexJsonAction()
  827. {
  828. return 'ddd';
  829. }
  830. }
  831. $app['posts.controller'] = $app->share(function() use ($app) {
  832. return new PostController();
  833. });
  834. $app->mount('/', "posts.controller");*/
  835. //All calls made in Chamilo are manage in the src/ChamiloLMS/Controller/IndexController.php file function classicAction
  836. $app->get('/', 'index.controller:classicAction');
  837. $app->post('/', 'index.controller:classicAction');
  838. //index.php
  839. $app->get('/index', 'index.controller:indexAction')->bind('index');
  840. //user_portal.php
  841. $app->get('/userportal', 'userportal.controller:indexAction');
  842. //Logout
  843. $app->get('/logout', 'index.controller:logoutAction');
  844. //LP controller
  845. $app->match('/learnpath/subscribe_users/{lpId}', 'learnpath.controller:indexAction', 'GET|POST')->bind('subscribe_users');
  846. return $app;