global.inc.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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/configuration.php or main/inc/configuration.yml
  7. * - mysql database (Using Doctrine DBAL/ORM or the Classic way: Database::query())
  8. * - Templates (Using Twig)
  9. * - Loading language files (No Symfony component)
  10. * - Loading mail settings (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. $settings_refresh_info = api_get_settings_params_simple(array('variable = ?' => 'settings_latest_update'));
  202. $settings_latest_update = $settings_refresh_info ? $settings_refresh_info['selected_value'] : null;
  203. $_setting = Session::read('_setting');
  204. if (empty($_setting)) {
  205. api_set_settings_and_plugins();
  206. } else {
  207. if (isset($_setting['settings_latest_update']) && $_setting['settings_latest_update'] != $settings_latest_update) {
  208. api_set_settings_and_plugins();
  209. }
  210. }
  211. $_setting = Session::read('_setting');
  212. $_plugins = Session::read('_plugins');
  213. // Default template style
  214. $templateStyle = api_get_setting('template');
  215. $templateStyle = isset($templateStyle) && !empty($templateStyle) ? $templateStyle : 'default';
  216. $app['template_style'] = $templateStyle;
  217. // Default layout
  218. $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
  219. $app['plugins'] = $_plugins;
  220. }
  221. $charset = 'UTF-8';
  222. // Manage Chamilo error messages
  223. $app->error(
  224. function (\Exception $e, $code) use ($app) {
  225. if ($app['debug']) {
  226. //return;
  227. }
  228. if (isset($code)) {
  229. switch ($code) {
  230. case 401:
  231. $message = 'Unauthorized';
  232. break;
  233. case 404: // not found
  234. $message = 'The requested page could not be found.';
  235. break;
  236. default:
  237. //$message = 'We are sorry, but something went terribly wrong.';
  238. $message = $e->getMessage();
  239. }
  240. } else {
  241. $code = null;
  242. $message = null;
  243. }
  244. //$code = ($e instanceof HttpException) ? $e->getStatusCode() : 500;
  245. $app['twig']->addGlobal('error_code', $code);
  246. $app['twig']->addGlobal('error_message', $message);
  247. $response = $app['template']->render_layout('error.tpl');
  248. return new Response($response);
  249. }
  250. );
  251. // Preserving the value of the global variable $charset.
  252. $charset_initial_value = $charset;
  253. // Section (tabs in the main chamilo menu)
  254. $app['this_section'] = SECTION_GLOBAL;
  255. // Inclusion of internationalization libraries
  256. require_once $libPath.'internationalization.lib.php';
  257. // Functions for internal use behind this API
  258. require_once $libPath.'internationalization_internal.lib.php';
  259. // Checking if we have a valid language. If not we set it to the platform language.
  260. $cidReset = null;
  261. if ($alreadyInstalled) {
  262. // Setting languages
  263. $app['api_get_languages'] = api_get_languages();
  264. $app['language_interface'] = $language_interface = api_get_language_interface();
  265. // Initialization of the internationalization library.
  266. //api_initialize_internationalization();
  267. // Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
  268. //api_set_internationalization_default_encoding($charset);
  269. // require $includePath.'/local.inc.php';
  270. // reconfigure template now we know the user
  271. $app['template.hide_global_chat'] = !api_is_global_chat_enabled();
  272. /** Loading languages and sublanguages **/
  273. // @todo improve the language loading
  274. // if we use the javascript version (without go button) we receive a get
  275. // if we use the non-javascript version (with the go button) we receive a post
  276. // Include all files (first english and then current interface language)
  277. //$app['this_script'] = isset($this_script) ? $this_script : null;
  278. // Sometimes the variable $language_interface is changed
  279. // temporarily for achieving translation in different language.
  280. // We need to save the genuine value of this variable and
  281. // to use it within the function get_lang(...).
  282. //$language_interface_initial_value = $language_interface;
  283. //$this_script = $app['this_script'];
  284. /* This will only work if we are in the page to edit a sub_language */
  285. /*
  286. if (isset($this_script) && $this_script == 'sub_language') {
  287. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  288. // getting the arrays of files i.e notification, trad4all, etc
  289. $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(
  290. api_get_path(SYS_LANG_PATH).'english',
  291. true
  292. );
  293. //getting parent info
  294. $languageId = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
  295. $parent_language = SubLanguageManager::get_all_information_of_language($languageId);
  296. $subLanguageId = isset($_REQUEST['sub_language_id']) ? $_REQUEST['sub_language_id'] : null;
  297. //getting sub language info
  298. $sub_language = SubLanguageManager::get_all_information_of_language($subLanguageId);
  299. $english_language_array = $parent_language_array = $sub_language_array = array();
  300. if (!empty($language_files_to_load)) {
  301. foreach ($language_files_to_load as $language_file_item) {
  302. $lang_list_pre = array_keys($GLOBALS);
  303. //loading english
  304. $path = $langPath.'english/'.$language_file_item.'.inc.php';
  305. if (file_exists($path)) {
  306. include $path;
  307. }
  308. $lang_list_post = array_keys($GLOBALS);
  309. $lang_list_result = array_diff($lang_list_post, $lang_list_pre);
  310. unset($lang_list_pre);
  311. // english language array
  312. $english_language_array[$language_file_item] = compact($lang_list_result);
  313. //cleaning the variables
  314. foreach ($lang_list_result as $item) {
  315. unset(${$item});
  316. }
  317. $parent_file = $langPath.$parent_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  318. if (file_exists($parent_file) && is_file($parent_file)) {
  319. include_once $parent_file;
  320. }
  321. // parent language array
  322. $parent_language_array[$language_file_item] = compact($lang_list_result);
  323. //cleaning the variables
  324. foreach ($lang_list_result as $item) {
  325. unset(${$item});
  326. }
  327. if (!empty($sub_language)) {
  328. $sub_file = $langPath.$sub_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  329. if (file_exists($sub_file) && is_file($sub_file)) {
  330. include $sub_file;
  331. }
  332. }
  333. // sub language array
  334. $sub_language_array[$language_file_item] = compact($lang_list_result);
  335. //cleaning the variables
  336. foreach ($lang_list_result as $item) {
  337. unset(${$item});
  338. }
  339. }
  340. }
  341. }*/
  342. } else {
  343. $app['language_interface'] = $language_interface = $language_interface_initial_value = 'english';
  344. }
  345. /**
  346. * Include all necessary language files
  347. * - trad4all
  348. * - notification
  349. * - custom tool language files
  350. */
  351. /*
  352. $language_files = array();
  353. $language_files[] = 'trad4all';
  354. $language_files[] = 'notification';
  355. $language_files[] = 'accessibility';
  356. // @todo Added because userportal and index are loaded by a controller should be fixed when a $app['translator'] is configured
  357. $language_files[] = 'index';
  358. $language_files[] = 'courses';
  359. $language_files[] = 'course_home';
  360. $language_files[] = 'exercice';
  361. if (isset($language_file)) {
  362. if (!is_array($language_file)) {
  363. $language_files[] = $language_file;
  364. } else {
  365. $language_files = array_merge($language_files, $language_file);
  366. }
  367. }
  368. if (isset($app['languages_file'])) {
  369. $language_files = array_merge($language_files, $app['languages_file']);
  370. }
  371. // if a set of language files has been properly defined
  372. if (is_array($language_files)) {
  373. // if the sub-language feature is on
  374. if (api_get_setting('allow_use_sub_language') == 'true') {
  375. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  376. $parent_path = SubLanguageManager::get_parent_language_path($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 and its parent
  381. $lang_file = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  382. $parent_lang_file = $langPath.$parent_path.'/'.$language_file.'.inc.php';
  383. // load the parent language file first
  384. if (file_exists($parent_lang_file)) {
  385. include $parent_lang_file;
  386. }
  387. // overwrite the parent language translations if there is a child
  388. if (file_exists($lang_file)) {
  389. include $lang_file;
  390. }
  391. }
  392. } else {
  393. // if the sub-languages feature is not on, then just load the
  394. // set language interface
  395. foreach ($language_files as $index => $language_file) {
  396. // include English
  397. include $langPath.'english/'.$language_file.'.inc.php';
  398. // prepare string for current language
  399. $langFile = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  400. if (file_exists($langFile)) {
  401. include $langFile;
  402. }
  403. }
  404. }
  405. }*/
  406. // End loading languages
  407. // Specification for usernames:
  408. // 1. ASCII-letters, digits, "." (dot), "_" (underscore) are acceptable, 40 characters maximum length.
  409. // 2. Empty username is formally valid, but it is reserved for the anonymous user.
  410. // 3. Checking the login_is_email portal setting in order to accept 100 chars maximum
  411. // @todo this should be configured somewhere else usermanager.class.php? a users.yml setting?
  412. $default_username_length = 40;
  413. if (api_get_setting('login_is_email') == 'true') {
  414. $default_username_length = 100;
  415. }
  416. @define('USERNAME_MAX_LENGTH', $default_username_length);
  417. /** Silex Middlewares. */
  418. /** A "before" middleware allows you to tweak the Request before the controller is executed. */
  419. // Handling po files (gettext)
  420. use Symfony\Component\Translation\Loader\PoFileLoader;
  421. use Symfony\Component\Translation\Loader\MoFileLoader;
  422. use Symfony\Component\Finder\Finder;
  423. $app->before(
  424. function () use ($app) {
  425. if (!file_exists($app['configuration_file']) && !file_exists($app['configuration_yml_file'])) {
  426. return new RedirectResponse(api_get_path(WEB_CODE_PATH).'install');
  427. $app->abort(500, "Configuration file was not found");
  428. }
  429. //Check the PHP version
  430. if (api_check_php_version() == false) {
  431. $app->abort(500, "Incorrect PHP version");
  432. }
  433. if (!is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
  434. $app->abort(500, "temp folder must be writable");
  435. }
  436. // Loop in the folder array and create temp folders.
  437. /** @var ChamiloLMS\Component\DataFilesystem\DataFilesystem $filesystem */
  438. $filesystem = $app['chamilo.filesystem'];
  439. /** @var Request $request */
  440. $request = $app['request'];
  441. // Creates temp folders for every request
  442. if ($app['debug']) {
  443. $filesystem->createFolders($app['temp.paths']->folders);
  444. }
  445. if ($app['assetic.auto_dump_assets']) {
  446. $filesystem->copyFolders($app['temp.paths']->copyFolders);
  447. }
  448. // Check and modify the date of user in the track.e.online table
  449. Online::loginCheck(api_get_user_id());
  450. $request->getSession()->start();
  451. //var_dump($app['security']->isGranted('IS_AUTHENTICATED_FULLY'));
  452. $user = null;
  453. if ($app['security']->isGranted('IS_AUTHENTICATED_FULLY')) {
  454. $token = $app['security']->getToken();
  455. if (null !== $token) {
  456. /** @var Entity\User $user */
  457. $user = $token->getUser();
  458. }
  459. // For backward compatibility
  460. $userInfo = api_get_user_info($user->getUserId());
  461. $userInfo['is_anonymous'] = false;
  462. Session::write('_user', $userInfo);
  463. $app['current_user'] = $userInfo;
  464. if ($app['security']->isGranted('ROLE_ADMIN')) {
  465. Session::write('is_platformAdmin', true);
  466. }
  467. if ($app['security']->isGranted('ROLE_TEACHER')) {
  468. Session::write('is_allowedCreateCourse', true);
  469. }
  470. } else {
  471. Session::erase('_user');
  472. Session::erase('is_platformAdmin');
  473. Session::erase('is_allowedCreateCourse');
  474. }
  475. // Platform lang
  476. $language = api_get_setting('platformLanguage');
  477. $iso = api_get_language_isocode($language);
  478. $app['translator']->setLocale($iso);
  479. // From the login page
  480. $language = $request->get('language');
  481. if (!empty($language)) {
  482. $iso = api_get_language_isocode($language);
  483. $app['translator']->setLocale($iso);
  484. }
  485. // From the user
  486. if ($user) {
  487. $language = $user->getLanguage();
  488. $iso = api_get_language_isocode($language);
  489. $app['translator']->setLocale($iso);
  490. }
  491. // From the course
  492. $courseInfo = api_get_course_info();
  493. if ($courseInfo && !empty($courseInfo)) {
  494. $iso = api_get_language_isocode($courseInfo['language']);
  495. $app['translator']->setLocale($iso);
  496. }
  497. $file = $request->get('file');
  498. $section = null;
  499. if (!empty($file)) {
  500. $info = pathinfo($file);
  501. $section = $info['dirname'];
  502. }
  503. // Default langs
  504. $languageFiles = array(
  505. 'trad4all',
  506. 'notification',
  507. 'accessibility'
  508. );
  509. $languageFilesToAdd = array();
  510. /* Loading translations depending of the "section" folder after main
  511. for example the section is exercice here: web/main/exercice/result.php
  512. */
  513. if (!empty($section)) {
  514. switch($section) {
  515. case 'admin':
  516. $languageFilesToAdd = array('admin');
  517. break;
  518. case 'document':
  519. $languageFilesToAdd = array('document');
  520. break;
  521. case 'dashboard':
  522. $languageFilesToAdd = array ('index', 'tracking', 'userInfo', 'admin', 'gradebook');
  523. break;
  524. case 'mySpace':
  525. $languageFilesToAdd = array('registration', 'index', 'tracking', 'admin');
  526. break;
  527. case 'course_info':
  528. case 'course_home':
  529. case 'course_description':
  530. case 'create_course':
  531. $languageFilesToAdd = array('create_course', 'registration', 'admin', 'exercice', 'course_description', 'course_info');
  532. break;
  533. case 'link':
  534. $languageFilesToAdd = array('link', 'admin');
  535. break;
  536. case 'session':
  537. $languageFilesToAdd = array('admin', 'registration');
  538. break;
  539. case 'user':
  540. $languageFilesToAdd = array('registration', 'admin', 'userInfo', 'registration');
  541. break;
  542. case 'social':
  543. $languageFilesToAdd = array('userInfo');
  544. break;
  545. case 'exercice':
  546. $languageFilesToAdd = array('exercice');
  547. break;
  548. }
  549. } else {
  550. $controllerName = $request->get('_controller');
  551. // Work around to load languages:
  552. switch($controllerName) {
  553. case 'index.controller:indexAction':
  554. case 'userPortal.controller::indexAction':
  555. $languageFilesToAdd = array('courses', 'index', 'admin');
  556. break;
  557. }
  558. }
  559. $languageFiles = array_merge($languageFiles, $languageFilesToAdd);
  560. $app['translator.cache.enabled'] = false;
  561. $app['translator'] = $app->share($app->extend('translator', function($translator, $app) use ($languageFiles) {
  562. $locale = $translator->getLocale();
  563. // Creating regex to parse sections (admin, exercice, etc)
  564. $languageFilesToString = '/'.implode('|', $languageFiles).'/';
  565. /** @var Symfony\Component\Translation\Translator $translator */
  566. if ($app['translator.cache.enabled']) {
  567. //$phpFileDumper = new Symfony\Component\Translation\Dumper\PhpFileDumper();
  568. $dumper = new Symfony\Component\Translation\Dumper\MoFileDumper();
  569. $catalogue = new Symfony\Component\Translation\MessageCatalogue($locale);
  570. $catalogue->add(array('foo' => 'bar'));
  571. $dumper->dump($catalogue, array('path' => $app['sys_temp_path']));
  572. } else {
  573. $translator->addLoader('pofile', new PoFileLoader());
  574. $finder = new Finder();
  575. $files = $finder->files()
  576. ->path($languageFilesToString)
  577. ->name('en.po')
  578. ->name($locale.'.po')
  579. ->in(api_get_path(SYS_PATH).'main/locale');
  580. foreach ($files as $entry) {
  581. $code = $entry->getBasename('.po');
  582. $translator->addResource('pofile', $entry->getPathname(), $code);
  583. }
  584. return $translator;
  585. }
  586. }));
  587. }
  588. );
  589. /** An after application middleware allows you to tweak the Response before it is sent to the client */
  590. $app->after(
  591. function (Request $request, Response $response) {
  592. }
  593. );
  594. /** A "finish" application middleware allows you to execute tasks after the Response has been sent to
  595. * the client (like sending emails or logging) */
  596. $app->finish(
  597. function (Request $request) use ($app) {
  598. }
  599. );
  600. // End Silex Middlewares
  601. // The global variable $charset has been defined in a language file too (trad4all.inc.php), this is legacy situation.
  602. // So, we have to reassign this variable again in order to keep its value right.
  603. $charset = $charset_initial_value;
  604. // The global variable $text_dir has been defined in the language file trad4all.inc.php.
  605. // For determing text direction correspondent to the current language we use now information from the internationalization library.
  606. $text_dir = api_get_text_direction();
  607. // Update of the logout_date field in the table track_e_login (needed for the calculation of the total connection time)
  608. /** "Login as user" custom script */
  609. // @todo move this code in a controller
  610. if (!isset($_SESSION['login_as']) && isset($_user)) {
  611. // if $_SESSION['login_as'] is set, then the user is an admin logged as the user
  612. $tbl_track_login = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  613. $sql_last_connection = "SELECT login_id, login_date FROM $tbl_track_login
  614. WHERE login_user_id = '".api_get_user_id()."'
  615. ORDER BY login_date DESC LIMIT 0,1";
  616. $q_last_connection = Database::query($sql_last_connection);
  617. if (Database::num_rows($q_last_connection) > 0) {
  618. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  619. // is the latest logout_date still relevant?
  620. $sql_logout_date = "SELECT logout_date FROM $tbl_track_login WHERE login_id = $i_id_last_connection";
  621. $q_logout_date = Database::query($sql_logout_date);
  622. $res_logout_date = api_convert_sql_date(Database::result($q_logout_date, 0, 'logout_date'));
  623. if ($res_logout_date < time() - $app['configuration']['session_lifetime']) {
  624. // now that it's created, we can get its ID and carry on
  625. $q_last_connection = Database::query($sql_last_connection);
  626. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  627. }
  628. $now = api_get_utc_datetime();
  629. $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date = '$now' WHERE login_id = $i_id_last_connection";
  630. Database::query($s_sql_update_logout_date);
  631. } else {
  632. // it isn't, we should create a fresh entry
  633. event_login();
  634. }
  635. }
  636. // Add language_measure_frequency to your main/inc/conf/configuration.php in
  637. // order to generate language variables frequency measurements (you can then
  638. // see them through main/cron/lang/langstats.php)
  639. // The langstat object will then be used in the get_lang() function.
  640. // This block can be removed to speed things up a bit as it should only ever
  641. // be used in development versions.
  642. // @todo create a service provider to load this
  643. if (isset($app['configuration']['language_measure_frequency']) && $app['configuration']['language_measure_frequency'] == 1) {
  644. require_once api_get_path(SYS_CODE_PATH).'/cron/lang/langstats.class.php';
  645. $langstats = new langstats();
  646. }
  647. /** Setting the course quota */
  648. // @todo move this somewhere else
  649. // Default quota for the course documents folder
  650. $default_quota = api_get_setting('default_document_quotum');
  651. // Just in case the setting is not correctly set
  652. if (empty($default_quota)) {
  653. $default_quota = 100000000;
  654. }
  655. @define('DEFAULT_DOCUMENT_QUOTA', $default_quota);
  656. /** Setting the is_admin key */
  657. $app['is_admin'] = false;
  658. /** Including routes */
  659. require_once 'routes.php';
  660. // Setting doctrine2 extensions
  661. if (isset($app['configuration']['main_database']) && isset($app['db.event_manager'])) {
  662. // @todo improvement do not create every time this objects
  663. $sortableGroup = new Gedmo\Mapping\Annotation\SortableGroup(array());
  664. $sortablePosition = new Gedmo\Mapping\Annotation\SortablePosition(array());
  665. $tree = new Gedmo\Mapping\Annotation\Tree(array());
  666. $tree = new Gedmo\Mapping\Annotation\TreeParent(array());
  667. $tree = new Gedmo\Mapping\Annotation\TreeLeft(array());
  668. $tree = new Gedmo\Mapping\Annotation\TreeRight(array());
  669. $tree = new Gedmo\Mapping\Annotation\TreeRoot(array());
  670. $tree = new Gedmo\Mapping\Annotation\TreeLevel(array());
  671. $tree = new Gedmo\Mapping\Annotation\Versioned(array());
  672. $tree = new Gedmo\Mapping\Annotation\Loggable(array());
  673. $tree = new Gedmo\Loggable\Entity\LogEntry();
  674. // Setting Doctrine2 extensions
  675. $timestampableListener = new \Gedmo\Timestampable\TimestampableListener();
  676. // $app['db.event_manager']->addEventSubscriber($timestampableListener);
  677. $app['dbs.event_manager']['db_read']->addEventSubscriber($timestampableListener);
  678. $app['dbs.event_manager']['db_write']->addEventSubscriber($timestampableListener);
  679. $sluggableListener = new \Gedmo\Sluggable\SluggableListener();
  680. // $app['db.event_manager']->addEventSubscriber($sluggableListener);
  681. $app['dbs.event_manager']['db_read']->addEventSubscriber($sluggableListener);
  682. $app['dbs.event_manager']['db_write']->addEventSubscriber($sluggableListener);
  683. $sortableListener = new Gedmo\Sortable\SortableListener();
  684. // $app['db.event_manager']->addEventSubscriber($sortableListener);
  685. $app['dbs.event_manager']['db_read']->addEventSubscriber($sortableListener);
  686. $app['dbs.event_manager']['db_write']->addEventSubscriber($sortableListener);
  687. $treeListener = new \Gedmo\Tree\TreeListener();
  688. //$treeListener->setAnnotationReader($cachedAnnotationReader);
  689. // $app['db.event_manager']->addEventSubscriber($treeListener);
  690. $app['dbs.event_manager']['db_read']->addEventSubscriber($treeListener);
  691. $app['dbs.event_manager']['db_write']->addEventSubscriber($treeListener);
  692. $loggableListener = new \Gedmo\Loggable\LoggableListener();
  693. $userInfo = api_get_user_info();
  694. if (isset($userInfo) && !empty($userInfo['username'])) {
  695. $loggableListener->setUsername($userInfo['username']);
  696. }
  697. //$app['db.event_manager']->addEventSubscriber($loggableListener);
  698. $app['dbs.event_manager']['db_read']->addEventSubscriber($loggableListener);
  699. $app['dbs.event_manager']['db_write']->addEventSubscriber($loggableListener);
  700. }
  701. // Fixes uses of $_course in the scripts.
  702. $_course = api_get_course_info();
  703. $_cid = api_get_course_id();
  704. return $app;