global.inc.php 32 KB

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