global.inc.php 35 KB

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