global.inc.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. <?php
  2. /** For licensing terms, see /license.txt */
  3. /**
  4. * This is a bootstrap file that loads all Chamilo dependencies including:
  5. *
  6. * - Chamilo settings config/configuration.yml or config/configuration.php (in this order, using what if finds first)
  7. * - Database (Using Doctrine DBAL/ORM)
  8. * - Templates (Using Twig)
  9. * - Loading language files (Using Symfony component)
  10. * - Loading mail settings (Using SwiftMailer smtp/sendmail/mail)
  11. * - Debug (Using Monolog)
  12. *
  13. * ALL Chamilo scripts must include this file in order to have the $app container
  14. * This script returns a $app Application instance so you have access to all the services.
  15. *
  16. * @package chamilo.include
  17. *
  18. */
  19. use Silex\Application;
  20. use \ChamiloSession as Session;
  21. use Symfony\Component\HttpFoundation\RedirectResponse;
  22. use Symfony\Component\HttpFoundation\Response;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\Yaml\Parser;
  25. // Determine the directory path for this file.
  26. $includePath = dirname(__FILE__);
  27. // Start Silex.
  28. $app = new Application();
  29. // @todo add a helper to read the configuration file once!
  30. // Include the main Chamilo platform configuration file.
  31. // @todo use a service provider to load configuration files:
  32. /*
  33. $app->register(new Igorw\Silex\ConfigServiceProvider($settingsFile));
  34. */
  35. /** Reading configuration files */
  36. // Reading configuration file from main/inc/conf/configuration.php or app/config/configuration.yml
  37. $configurationFilePath = $includePath.'/conf/configuration.php';
  38. $configurationYMLFile = $includePath.'/../../config/configuration.yml';
  39. $configurationFileAppPath = $includePath.'/../../config/configuration.php';
  40. $alreadyInstalled = false;
  41. $_configuration = array();
  42. if (file_exists($configurationFilePath) || file_exists($configurationYMLFile) || file_exists($configurationFileAppPath)) {
  43. if (file_exists($configurationFilePath)) {
  44. require_once $configurationFilePath;
  45. }
  46. if (file_exists($configurationFileAppPath)) {
  47. $configurationFilePath = $configurationFileAppPath;
  48. require_once $configurationFileAppPath;
  49. }
  50. $alreadyInstalled = true;
  51. }
  52. // Overwriting $_configuration
  53. if (file_exists($configurationYMLFile)) {
  54. $yaml = new Parser();
  55. $configurationYML = $yaml->parse(file_get_contents($configurationYMLFile));
  56. if (is_array($configurationYML) && !empty($configurationYML)) {
  57. if (isset($_configuration)) {
  58. $_configuration = array_merge($_configuration, $configurationYML);
  59. } else {
  60. $_configuration = $configurationYML;
  61. }
  62. }
  63. }
  64. /** Setting Chamilo paths */
  65. $app['root_sys'] = isset($_configuration['root_sys']) ? $_configuration['root_sys'] : dirname(dirname(__DIR__)).'/';
  66. $app['sys_root'] = $app['root_sys'];
  67. $app['sys_data_path'] = isset($_configuration['sys_data_path']) ? $_configuration['sys_data_path'] : $app['root_sys'].'data/';
  68. $app['sys_config_path'] = isset($_configuration['sys_config_path']) ? $_configuration['sys_config_path'] : $app['root_sys'].'config/';
  69. $app['sys_course_path'] = isset($_configuration['sys_course_path']) ? $_configuration['sys_course_path'] : $app['sys_data_path'].'/courses/';
  70. $app['sys_temp_path'] = isset($_configuration['sys_temp_path']) ? $_configuration['sys_temp_path'] : $app['sys_data_path'].'temp/';
  71. $app['sys_log_path'] = isset($_configuration['sys_log_path']) ? $_configuration['sys_log_path'] : $app['root_sys'].'logs/';
  72. /** Loading config files (mail, auth, profile) */
  73. if ($alreadyInstalled) {
  74. $configPath = $app['sys_config_path'];
  75. $confFiles = array(
  76. 'auth.conf.php',
  77. 'events.conf.php',
  78. 'mail.conf.php',
  79. 'portfolio.conf.php',
  80. 'profile.conf.php'
  81. );
  82. foreach ($confFiles as $confFile) {
  83. if (file_exists($configPath.$confFile)) {
  84. require_once $configPath.$confFile;
  85. }
  86. }
  87. // Fixing $_configuration array
  88. // Fixes bug in Chamilo 1.8.7.1 array was not set
  89. $administrator['email'] = isset($administrator['email']) ? $administrator['email'] : 'admin@example.com';
  90. $administrator['name'] = isset($administrator['name']) ? $administrator['name'] : 'Admin';
  91. // Code for transitional purposes, it can be removed right before the 1.8.7 release.
  92. /*if (empty($_configuration['system_version'])) {
  93. $_configuration['system_version'] = (!empty($_configuration['dokeos_version']) ? $_configuration['dokeos_version'] : '');
  94. $_configuration['system_stable'] = (!empty($_configuration['dokeos_stable']) ? $_configuration['dokeos_stable'] : '');
  95. $_configuration['software_url'] = 'http://www.chamilo.org/';
  96. }*/
  97. // For backward compatibility.
  98. $_configuration['dokeos_version'] = isset($_configuration['system_version']) ? $_configuration['system_version'] : null;
  99. //$_configuration['dokeos_stable'] = $_configuration['system_stable'];
  100. $userPasswordCrypted = (!empty($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1');
  101. }
  102. /** End loading config files */
  103. /** Including legacy libs */
  104. require_once $includePath.'/lib/api.lib.php';
  105. // Setting $_configuration['url_append']
  106. $urlInfo = isset($_configuration['root_web']) ? parse_url($_configuration['root_web']) : null;
  107. $_configuration['url_append'] = null;
  108. if (isset($urlInfo['path'])) {
  109. $_configuration['url_append'] = '/'.basename($urlInfo['path']);
  110. }
  111. $libPath = $includePath.'/lib/';
  112. // Database constants
  113. require_once $libPath.'database.constants.inc.php';
  114. // @todo Rewrite the events.lib.inc.php in a class
  115. require_once $libPath.'events.lib.inc.php';
  116. // Load allowed tag definitions for kses and/or HTMLPurifier.
  117. require_once $libPath.'formvalidator/Rule/allowed_tags.inc.php';
  118. // Add the path to the pear packages to the include path
  119. ini_set('include_path', api_create_include_path_setting($includePath));
  120. $app['configuration_file'] = $configurationFilePath;
  121. $app['configuration_yml_file'] = $configurationYMLFile;
  122. $app['languages_file'] = array();
  123. $app['installed'] = $alreadyInstalled;
  124. $app['app.theme'] = 'chamilo';
  125. // Developer options relies in the configuration.php file
  126. $app['debug'] = isset($_configuration['debug']) ? $_configuration['debug'] : false;
  127. $app['show_profiler'] = isset($_configuration['show_profiler']) ? $_configuration['show_profiler'] : false;
  128. // Enables assetic in order to load 1 compressed stylesheet or split files
  129. //$app['assetic.enabled'] = $app['debug'];
  130. // Hardcoded to false by default. Implementation is not finished yet.
  131. $app['assetic.enabled'] = false;
  132. // Dumps assets
  133. $app['assetic.auto_dump_assets'] = false;
  134. // Loading $app settings depending of the debug option
  135. if ($app['debug']) {
  136. require_once __DIR__.'/../../src/ChamiloLMS/Resources/config/dev.php';
  137. } else {
  138. require_once __DIR__.'/../../src/ChamiloLMS/Resources/config/prod.php';
  139. }
  140. // Classic way of render pages or the Controller approach
  141. $app['classic_layout'] = false;
  142. $app['full_width'] = false;
  143. $app['breadcrumb'] = array();
  144. // The script is allowed? This setting is modified when calling api_is_not_allowed()
  145. $app['allowed'] = true;
  146. $app->register(new Silex\Provider\SessionServiceProvider());
  147. // Session settings
  148. $app['session.storage.options'] = array(
  149. 'name' => 'chamilo_session',
  150. //'cookie_lifetime' => 30, //Cookie lifetime
  151. //'cookie_path' => null, //Cookie path
  152. //'cookie_domain' => null, //Cookie domain
  153. //'cookie_secure' => null, //Cookie secure (HTTPS)
  154. 'cookie_httponly' => true //Whether the cookie is http only
  155. );
  156. // Loading chamilo settings
  157. /* @todo create a service provider to load plugins.
  158. Check how bolt add extensions (including twig templates, config with yml)*/
  159. // Template settings loaded in template.lib.php
  160. $app['template.show_header'] = true;
  161. $app['template.show_footer'] = true;
  162. $app['template.show_learnpath'] = false;
  163. $app['template.hide_global_chat'] = true;
  164. $app['template.load_plugins'] = true;
  165. $app['configuration'] = $_configuration;
  166. // Inclusion of internationalization libraries
  167. require_once $libPath.'internationalization.lib.php';
  168. // Functions for internal use behind this API
  169. require_once $libPath.'internationalization_internal.lib.php';
  170. $_plugins = array();
  171. if ($alreadyInstalled) {
  172. /** Including service providers */
  173. require_once 'services.php';
  174. }
  175. $charset = 'UTF-8';
  176. // Preserving the value of the global variable $charset.
  177. $charset_initial_value = $charset;
  178. // Section (tabs in the main Chamilo menu)
  179. $app['this_section'] = SECTION_GLOBAL;
  180. // Manage Chamilo error messages
  181. $app->error(
  182. function (\Exception $e, $code) use ($app) {
  183. if ($app['debug']) {
  184. //return;
  185. }
  186. $message = null;
  187. if (isset($code)) {
  188. switch ($code) {
  189. case 401:
  190. $message = 'Unauthorized';
  191. break;
  192. case 404: // not found
  193. $message = 'The requested page could not be found.';
  194. break;
  195. default:
  196. //$message = 'We are sorry, but something went terribly wrong.';
  197. $message = $e->getMessage();
  198. }
  199. } else {
  200. $code = null;
  201. }
  202. Session::setSession($app['session']);
  203. //$code = ($e instanceof HttpException) ? $e->getStatusCode() : 500;
  204. // It seems that error() is executed first than the before() middleware
  205. // @ŧodo check this one
  206. $templateStyle = api_get_setting('template');
  207. $templateStyle = isset($templateStyle) && !empty($templateStyle) ? $templateStyle : 'default';
  208. if (!is_dir($app['sys_root'].'main/template/'.$templateStyle)) {
  209. $templateStyle = 'default';
  210. }
  211. $app['template_style'] = $templateStyle;
  212. // Default layout.
  213. $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
  214. /** @var Template $template */
  215. $template = $app['template'];
  216. $template->assign('error', array('code' => $code, 'message' => $message));
  217. $response = $template->render_layout('error.tpl');
  218. return new Response($response);
  219. }
  220. );
  221. // Checking if we have a valid language. If not we set it to the platform language.
  222. $cidReset = null;
  223. if ($alreadyInstalled) {
  224. // Initialization of the internationalization library.
  225. //api_initialize_internationalization();
  226. // Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
  227. //api_set_internationalization_default_encoding($charset);
  228. // require $includePath.'/local.inc.php';
  229. /** Loading languages and sublanguages **/
  230. // @todo improve the language loading
  231. // if we use the javascript version (without go button) we receive a get
  232. // if we use the non-javascript version (with the go button) we receive a post
  233. // Include all files (first english and then current interface language)
  234. //$app['this_script'] = isset($this_script) ? $this_script : null;
  235. // Sometimes the variable $language_interface is changed
  236. // temporarily for achieving translation in different language.
  237. // We need to save the genuine value of this variable and
  238. // to use it within the function get_lang(...).
  239. //$language_interface_initial_value = $language_interface;
  240. //$this_script = $app['this_script'];
  241. /* This will only work if we are in the page to edit a sub_language */
  242. /*
  243. if (isset($this_script) && $this_script == 'sub_language') {
  244. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  245. // getting the arrays of files i.e notification, trad4all, etc
  246. $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(
  247. api_get_path(SYS_LANG_PATH).'english',
  248. true
  249. );
  250. //getting parent info
  251. $languageId = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
  252. $parent_language = SubLanguageManager::get_all_information_of_language($languageId);
  253. $subLanguageId = isset($_REQUEST['sub_language_id']) ? $_REQUEST['sub_language_id'] : null;
  254. //getting sub language info
  255. $sub_language = SubLanguageManager::get_all_information_of_language($subLanguageId);
  256. $english_language_array = $parent_language_array = $sub_language_array = array();
  257. if (!empty($language_files_to_load)) {
  258. foreach ($language_files_to_load as $language_file_item) {
  259. $lang_list_pre = array_keys($GLOBALS);
  260. //loading english
  261. $path = $langPath.'english/'.$language_file_item.'.inc.php';
  262. if (file_exists($path)) {
  263. include $path;
  264. }
  265. $lang_list_post = array_keys($GLOBALS);
  266. $lang_list_result = array_diff($lang_list_post, $lang_list_pre);
  267. unset($lang_list_pre);
  268. // english language array
  269. $english_language_array[$language_file_item] = compact($lang_list_result);
  270. //cleaning the variables
  271. foreach ($lang_list_result as $item) {
  272. unset(${$item});
  273. }
  274. $parent_file = $langPath.$parent_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  275. if (file_exists($parent_file) && is_file($parent_file)) {
  276. include_once $parent_file;
  277. }
  278. // parent language array
  279. $parent_language_array[$language_file_item] = compact($lang_list_result);
  280. //cleaning the variables
  281. foreach ($lang_list_result as $item) {
  282. unset(${$item});
  283. }
  284. if (!empty($sub_language)) {
  285. $sub_file = $langPath.$sub_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  286. if (file_exists($sub_file) && is_file($sub_file)) {
  287. include $sub_file;
  288. }
  289. }
  290. // sub language array
  291. $sub_language_array[$language_file_item] = compact($lang_list_result);
  292. //cleaning the variables
  293. foreach ($lang_list_result as $item) {
  294. unset(${$item});
  295. }
  296. }
  297. }
  298. }*/
  299. } else {
  300. $app['language_interface'] = $language_interface = $language_interface_initial_value = 'english';
  301. }
  302. /**
  303. * Include all necessary language files
  304. * - trad4all
  305. * - notification
  306. * - custom tool language files
  307. */
  308. /*
  309. $language_files = array();
  310. $language_files[] = 'trad4all';
  311. $language_files[] = 'notification';
  312. $language_files[] = 'accessibility';
  313. if (isset($language_file)) {
  314. if (!is_array($language_file)) {
  315. $language_files[] = $language_file;
  316. } else {
  317. $language_files = array_merge($language_files, $language_file);
  318. }
  319. }
  320. if (isset($app['languages_file'])) {
  321. $language_files = array_merge($language_files, $app['languages_file']);
  322. }
  323. // if a set of language files has been properly defined
  324. if (is_array($language_files)) {
  325. // if the sub-language feature is on
  326. if (api_get_setting('allow_use_sub_language') == 'true') {
  327. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  328. $parent_path = SubLanguageManager::get_parent_language_path($language_interface);
  329. foreach ($language_files as $index => $language_file) {
  330. // include English
  331. include $langPath.'english/'.$language_file.'.inc.php';
  332. // prepare string for current language and its parent
  333. $lang_file = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  334. $parent_lang_file = $langPath.$parent_path.'/'.$language_file.'.inc.php';
  335. // load the parent language file first
  336. if (file_exists($parent_lang_file)) {
  337. include $parent_lang_file;
  338. }
  339. // overwrite the parent language translations if there is a child
  340. if (file_exists($lang_file)) {
  341. include $lang_file;
  342. }
  343. }
  344. } else {
  345. // if the sub-languages feature is not on, then just load the
  346. // set language interface
  347. foreach ($language_files as $index => $language_file) {
  348. // include English
  349. include $langPath.'english/'.$language_file.'.inc.php';
  350. // prepare string for current language
  351. $langFile = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  352. if (file_exists($langFile)) {
  353. include $langFile;
  354. }
  355. }
  356. }
  357. }*/
  358. // End loading languages
  359. /** Silex Middlewares. */
  360. /** A "before" middleware allows you to tweak the Request before the controller is executed. */
  361. use Symfony\Component\Translation\Loader\PoFileLoader;
  362. use Symfony\Component\Translation\Loader\MoFileLoader;
  363. use Symfony\Component\Finder\Finder;
  364. $app->before(
  365. function () use ($app) {
  366. /** @var Request $request */
  367. $request = $app['request'];
  368. // Checking configuration file. If does not exists redirect to the install folder.
  369. if (!file_exists($app['configuration_file']) && !file_exists($app['configuration_yml_file'])) {
  370. $url = str_replace('web', 'main/install', $request->getBasePath());
  371. return new RedirectResponse($url);
  372. }
  373. // Check the PHP version.
  374. if (api_check_php_version() == false) {
  375. $app->abort(500, "Incorrect PHP version.");
  376. }
  377. // Check data folder
  378. if (!is_writable($app['sys_data_path'])) {
  379. $app->abort(500, "data folder must be writable.");
  380. }
  381. // Checks temp folder permissions.
  382. if (!is_writable($app['sys_temp_path'])) {
  383. $app->abort(500, "data/temp folder must be writable.");
  384. }
  385. // Checking that configuration is loaded
  386. if (!isset($app['configuration'])) {
  387. $app->abort(500, '$configuration array must be set in the configuration.php file.');
  388. }
  389. $configuration = $app['configuration'];
  390. // Check if root_web exists
  391. if (!isset($configuration['root_web'])) {
  392. $app->abort(500, '$configuration[root_web] must be set in the configuration.php file.');
  393. }
  394. // Starting the session for more info see: http://silex.sensiolabs.org/doc/providers/session.html
  395. $request->getSession()->start();
  396. // Setting session obj
  397. Session::setSession($app['session']);
  398. UserManager::setEntityManager($app['orm.em']);
  399. /** @var ChamiloLMS\Component\DataFilesystem\DataFilesystem $filesystem */
  400. $filesystem = $app['chamilo.filesystem'];
  401. if ($app['debug']) {
  402. // Creates data/temp folders for every request if debug is on.
  403. $filesystem->createFolders($app['temp.paths']->folders);
  404. }
  405. // If Assetic is enabled copy folders from theme inside "web/"
  406. if ($app['assetic.auto_dump_assets']) {
  407. $filesystem->copyFolders($app['temp.paths']->copyFolders);
  408. }
  409. // Check and modify the date of user in the track.e.online table
  410. Online::loginCheck(api_get_user_id());
  411. // Setting access_url id (multiple url feature)
  412. if (api_get_multiple_access_url()) {
  413. $_configuration = $app['configuration'];
  414. $_configuration['access_url'] = 1;
  415. $access_urls = api_get_access_urls();
  416. //$protocol = ((!empty($_SERVER['HTTPS']) && strtoupper($_SERVER['HTTPS']) != 'OFF') ? 'https' : 'http').'://';
  417. $protocol = $request->getScheme().'://';
  418. $request_url1 = $protocol.$_SERVER['SERVER_NAME'].'/';
  419. $request_url2 = $protocol.$_SERVER['HTTP_HOST'].'/';
  420. foreach ($access_urls as & $details) {
  421. if ($request_url1 == $details['url'] or $request_url2 == $details['url']) {
  422. $_configuration['access_url'] = $details['id'];
  423. }
  424. }
  425. Session::write('url_id', $_configuration['access_url']);
  426. Session::write('url_info', api_get_current_access_url_info($_configuration['access_url']));
  427. } else {
  428. Session::write('url_id', 1);
  429. }
  430. // Loading portal settings from DB.
  431. $settings_refresh_info = api_get_settings_params_simple(array('variable = ?' => 'settings_latest_update'));
  432. $settings_latest_update = $settings_refresh_info ? $settings_refresh_info['selected_value'] : null;
  433. $_setting = Session::read('_setting');
  434. if (empty($_setting)) {
  435. api_set_settings_and_plugins();
  436. } else {
  437. if (isset($_setting['settings_latest_update']) && $_setting['settings_latest_update'] != $settings_latest_update) {
  438. api_set_settings_and_plugins();
  439. }
  440. }
  441. $app['plugins'] = Session::read('_plugins');
  442. // Default template style.
  443. $templateStyle = api_get_setting('template');
  444. $templateStyle = isset($templateStyle) && !empty($templateStyle) ? $templateStyle : 'default';
  445. if (!is_dir($app['sys_root'].'main/template/'.$templateStyle)) {
  446. $templateStyle = 'default';
  447. }
  448. $app['template_style'] = $templateStyle;
  449. // Default layout.
  450. $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
  451. // Setting languages.
  452. $app['api_get_languages'] = api_get_languages();
  453. $app['language_interface'] = $language_interface = api_get_language_interface();
  454. // Reconfigure template now that we know the user.
  455. $app['template.hide_global_chat'] = !api_is_global_chat_enabled();
  456. /** Setting the course quota */
  457. // Default quota for the course documents folder
  458. $default_quota = api_get_setting('default_document_quotum');
  459. // Just in case the setting is not correctly set
  460. if (empty($default_quota)) {
  461. $default_quota = 100000000;
  462. }
  463. define('DEFAULT_DOCUMENT_QUOTA', $default_quota);
  464. // Specification for usernames:
  465. // 1. ASCII-letters, digits, "." (dot), "_" (underscore) are acceptable, 40 characters maximum length.
  466. // 2. Empty username is formally valid, but it is reserved for the anonymous user.
  467. // 3. Checking the login_is_email portal setting in order to accept 100 chars maximum
  468. $default_username_length = 40;
  469. if (api_get_setting('login_is_email') == 'true') {
  470. $default_username_length = 100;
  471. }
  472. define('USERNAME_MAX_LENGTH', $default_username_length);
  473. $user = null;
  474. /** Security component. */
  475. /** @var Symfony\Component\Security\Core\SecurityContext $security */
  476. $security = $app['security'];
  477. if ($security->isGranted('IS_AUTHENTICATED_FULLY')) {
  478. // Checking token in order to get the current user.
  479. $token = $security->getToken();
  480. if (null !== $token) {
  481. /** @var Entity\User $user */
  482. $user = $token->getUser();
  483. }
  484. // For backward compatibility.
  485. $userInfo = api_get_user_info($user->getUserId());
  486. $userInfo['is_anonymous'] = false;
  487. Session::write('_user', $userInfo);
  488. $app['current_user'] = $userInfo;
  489. // Setting admin permissions.
  490. if ($security->isGranted('ROLE_ADMIN')) {
  491. Session::write('is_platformAdmin', true);
  492. }
  493. // Setting teachers permissions.
  494. if ($security->isGranted('ROLE_TEACHER')) {
  495. Session::write('is_allowedCreateCourse', true);
  496. }
  497. } else {
  498. Session::erase('_user');
  499. Session::erase('is_platformAdmin');
  500. Session::erase('is_allowedCreateCourse');
  501. }
  502. /** Translator component. */
  503. $app['translator.cache.enabled'] = false;
  504. $language = api_get_setting('platformLanguage');
  505. $iso = api_get_language_isocode($language);
  506. /** @var Symfony\Component\Translation\Translator $translator */
  507. $translator = $app['translator'];
  508. $translator->setLocale($iso);
  509. // From the login page
  510. $language = $request->get('language');
  511. if (!empty($language)) {
  512. $iso = api_get_language_isocode($language);
  513. $translator->setLocale($iso);
  514. }
  515. // From the user
  516. if ($user && $userInfo) {
  517. // @todo check why this does not works
  518. //$language = $user->getLanguage();
  519. $language = $userInfo['language'];
  520. $iso = api_get_language_isocode($language);
  521. $translator->setLocale($iso);
  522. }
  523. // From the course
  524. $courseInfo = api_get_course_info();
  525. if ($courseInfo && !empty($courseInfo)) {
  526. $iso = api_get_language_isocode($courseInfo['language']);
  527. $translator->setLocale($iso);
  528. }
  529. $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) {
  530. $locale = $translator->getLocale();
  531. /** @var Symfony\Component\Translation\Translator $translator */
  532. if ($app['translator.cache.enabled']) {
  533. //$phpFileDumper = new Symfony\Component\Translation\Dumper\PhpFileDumper();
  534. $dumper = new Symfony\Component\Translation\Dumper\MoFileDumper();
  535. $catalogue = new Symfony\Component\Translation\MessageCatalogue($locale);
  536. $catalogue->add(array('foo' => 'bar'));
  537. $dumper->dump($catalogue, array('path' => $app['sys_temp_path']));
  538. } else {
  539. $translator->addLoader('pofile', new PoFileLoader());
  540. $file = $app['root_sys'].'main/locale/'.$locale.'.po';
  541. if (file_exists($file)) {
  542. $translator->addResource('pofile', $file, $locale);
  543. }
  544. $customFile = $app['root_sys'].'main/locale/'.$locale.'.custom.po';
  545. if (file_exists($customFile)) {
  546. $translator->addResource('pofile', $customFile, $locale);
  547. }
  548. // Validators
  549. $file = $app['root_sys'].'vendor/symfony/validator/Symfony/Component/Validator/Resources/translations/validators.'.$locale.'.xlf';
  550. $translator->addLoader('xlf', new Symfony\Component\Translation\Loader\XliffFileLoader());
  551. if (file_exists($file)) {
  552. $translator->addResource('xlf', $file, $locale, 'validators');
  553. }
  554. /*$translator->addLoader('mofile', new MoFileLoader());
  555. $filePath = api_get_path(SYS_PATH).'main/locale/'.$locale.'.mo';
  556. if (!file_exists($filePath)) {
  557. $filePath = api_get_path(SYS_PATH).'main/locale/en.mo';
  558. }
  559. $translator->addResource('mofile', $filePath, $locale);*/
  560. return $translator;
  561. }
  562. }));
  563. // Check if we are inside a Chamilo course tool
  564. $isCourseTool = (strpos($request->getPathInfo(), 'courses/') === false) ? false : true;
  565. if (!$isCourseTool) {
  566. // @todo add a before in controller in order to load the courses and course_session object
  567. $isCourseTool = (strpos($request->getPathInfo(), 'question_manager/exercise_distribution/') === false) ? false : true;
  568. $isCourseTool = (strpos($request->getPathInfo(), 'question_manager/questions/') === false) ? false : true;
  569. }
  570. // Setting course entity for controllers and templates
  571. if ($isCourseTool) {
  572. // The course parameter is loaded
  573. $course = $request->get('course');
  574. if (empty($course)) {
  575. $course = $request->get('cidReq');
  576. }
  577. if (!empty($course)) {
  578. // Converting /courses/XXX/ to a Entity/Course object
  579. $course = $app['orm.em']->getRepository('Entity\Course')->findOneByCode($course);
  580. } else {
  581. $courseId = $request->get('courseId');
  582. // Converting /courses/XXX/ to a Entity/Course object
  583. $course = $app['orm.em']->getRepository('Entity\Course')->find($courseId);
  584. }
  585. $app['course'] = $course;
  586. $app['template']->assign('course', $course);
  587. $sessionId = $request->get('id_session');
  588. $session = $app['orm.em']->getRepository('Entity\Session')->findOneById($sessionId);
  589. $app['course_session'] = $session;
  590. $app['template']->assign('course_session', $session);
  591. }
  592. }
  593. );
  594. /** An after application middleware allows you to tweak the Response before it is sent to the client */
  595. $app->after(
  596. function (Request $request, Response $response) {
  597. }
  598. );
  599. /** A "finish" application middleware allows you to execute tasks after the Response has been sent to
  600. * the client (like sending emails or logging) */
  601. $app->finish(
  602. function (Request $request) use ($app) {
  603. }
  604. );
  605. // End Silex Middlewares
  606. // The global variable $charset has been defined in a language file too (trad4all.inc.php), this is legacy situation.
  607. // So, we have to reassign this variable again in order to keep its value right.
  608. $charset = $charset_initial_value;
  609. // The global variable $text_dir has been defined in the language file trad4all.inc.php.
  610. // For determing text direction correspondent to the current language we use now information from the internationalization library.
  611. $text_dir = api_get_text_direction();
  612. /** "Login as user" custom script */
  613. // @todo move this code in a controller
  614. /*
  615. if (!isset($_SESSION['login_as']) && isset($_user)) {
  616. // if $_SESSION['login_as'] is set, then the user is an admin logged as the user
  617. $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  618. $sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login
  619. WHERE login_user_id = '".api_get_user_id()."'
  620. ORDER BY login_date DESC LIMIT 0,1";
  621. $q_last_connection = Database::query($sql_last_connection);
  622. if (Database::num_rows($q_last_connection) > 0) {
  623. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  624. // is the latest logout_date still relevant?
  625. $sql_logout_date = "SELECT logout_date FROM $tbl_track_login WHERE login_id = $i_id_last_connection";
  626. $q_logout_date = Database::query($sql_logout_date);
  627. $res_logout_date = api_convert_sql_date(Database::result($q_logout_date, 0, 'logout_date'));
  628. if ($res_logout_date < time() - $app['configuration']['session_lifetime']) {
  629. // now that it's created, we can get its ID and carry on
  630. $q_last_connection = Database::query($sql_last_connection);
  631. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  632. }
  633. $now = api_get_utc_datetime();
  634. $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date = '$now' WHERE login_id = $i_id_last_connection";
  635. Database::query($s_sql_update_logout_date);
  636. }
  637. }*/
  638. // Add language_measure_frequency to your main/inc/conf/configuration.php in
  639. // order to generate language variables frequency measurements (you can then
  640. // see them through main/cron/lang/langstats.php)
  641. // The langstat object will then be used in the get_lang() function.
  642. // This block can be removed to speed things up a bit as it should only ever
  643. // be used in development versions.
  644. // @todo create a service provider to load this
  645. if (isset($app['configuration']['language_measure_frequency']) && $app['configuration']['language_measure_frequency'] == 1) {
  646. require_once api_get_path(SYS_CODE_PATH).'/cron/lang/langstats.class.php';
  647. $langstats = new langstats();
  648. }
  649. /** Setting the is_admin key */
  650. $app['is_admin'] = false;
  651. /** Including routes */
  652. require_once 'routes.php';
  653. // Setting doctrine2 extensions
  654. if (isset($app['configuration']['main_database']) && isset($app['db.event_manager'])) {
  655. // @todo improvement do not create every time this objects
  656. $sortableGroup = new Gedmo\Mapping\Annotation\SortableGroup(array());
  657. $sortablePosition = new Gedmo\Mapping\Annotation\SortablePosition(array());
  658. $tree = new Gedmo\Mapping\Annotation\Tree(array());
  659. $tree = new Gedmo\Mapping\Annotation\TreeParent(array());
  660. $tree = new Gedmo\Mapping\Annotation\TreeLeft(array());
  661. $tree = new Gedmo\Mapping\Annotation\TreeRight(array());
  662. $tree = new Gedmo\Mapping\Annotation\TreeRoot(array());
  663. $tree = new Gedmo\Mapping\Annotation\TreeLevel(array());
  664. $tree = new Gedmo\Mapping\Annotation\Versioned(array());
  665. $tree = new Gedmo\Mapping\Annotation\Loggable(array());
  666. $tree = new Gedmo\Loggable\Entity\LogEntry();
  667. // Setting Doctrine2 extensions
  668. $timestampableListener = new \Gedmo\Timestampable\TimestampableListener();
  669. // $app['db.event_manager']->addEventSubscriber($timestampableListener);
  670. $app['dbs.event_manager']['db_read']->addEventSubscriber($timestampableListener);
  671. $app['dbs.event_manager']['db_write']->addEventSubscriber($timestampableListener);
  672. $sluggableListener = new \Gedmo\Sluggable\SluggableListener();
  673. // $app['db.event_manager']->addEventSubscriber($sluggableListener);
  674. $app['dbs.event_manager']['db_read']->addEventSubscriber($sluggableListener);
  675. $app['dbs.event_manager']['db_write']->addEventSubscriber($sluggableListener);
  676. $sortableListener = new Gedmo\Sortable\SortableListener();
  677. // $app['db.event_manager']->addEventSubscriber($sortableListener);
  678. $app['dbs.event_manager']['db_read']->addEventSubscriber($sortableListener);
  679. $app['dbs.event_manager']['db_write']->addEventSubscriber($sortableListener);
  680. $treeListener = new \Gedmo\Tree\TreeListener();
  681. //$treeListener->setAnnotationReader($cachedAnnotationReader);
  682. // $app['db.event_manager']->addEventSubscriber($treeListener);
  683. $app['dbs.event_manager']['db_read']->addEventSubscriber($treeListener);
  684. $app['dbs.event_manager']['db_write']->addEventSubscriber($treeListener);
  685. $loggableListener = new \Gedmo\Loggable\LoggableListener();
  686. if (PHP_SAPI != 'cli') {
  687. //$userInfo = api_get_user_info();
  688. if (isset($userInfo) && !empty($userInfo['username'])) {
  689. //$loggableListener->setUsername($userInfo['username']);
  690. }
  691. }
  692. $app['dbs.event_manager']['db_read']->addEventSubscriber($loggableListener);
  693. $app['dbs.event_manager']['db_write']->addEventSubscriber($loggableListener);
  694. }
  695. return $app;