global.inc.php 34 KB

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