global.inc.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. //Including main and internationalization libs
  68. // Include the main Chamilo platform library file.
  69. require_once $includePath.'/lib/main_api.lib.php';
  70. // Inclusion of internationalization libraries
  71. require_once $includePath.'/lib/internationalization.lib.php';
  72. // Functions for internal use behind this API
  73. require_once $includePath.'/lib/internationalization_internal.lib.php';
  74. // Do not over-use this variable. It is only for this script's local use.
  75. $libPath = $includePath.'/lib/';
  76. // Loading config files
  77. if ($alreadyInstalled) {
  78. $configPath = $includePath.'/../../app/config/';
  79. $confFiles = array(
  80. 'auth.conf.php',
  81. 'events.conf.php',
  82. 'mail.conf.php',
  83. 'portfolio.conf.php',
  84. 'profile.conf.php'
  85. );
  86. foreach ($confFiles as $confFile) {
  87. if (file_exists($configPath.$confFile)) {
  88. require_once $configPath.$confFile;
  89. }
  90. }
  91. // Fixing $_configuration array
  92. //Fixes bug in Chamilo 1.8.7.1 array was not set
  93. $administrator['email'] = isset($administrator['email']) ? $administrator['email'] : 'admin@example.com';
  94. $administrator['name'] = isset($administrator['name']) ? $administrator['name'] : 'Admin';
  95. // Code for transitional purposes, it can be removed right before the 1.8.7 release.
  96. if (empty($_configuration['system_version'])) {
  97. $_configuration['system_version'] = (!empty($_configuration['dokeos_version']) ? $_configuration['dokeos_version'] : '');
  98. $_configuration['system_stable'] = (!empty($_configuration['dokeos_stable']) ? $_configuration['dokeos_stable'] : '');
  99. $_configuration['software_url'] = 'http://www.chamilo.org/';
  100. }
  101. // For backward compatibility.
  102. $_configuration['dokeos_version'] = $_configuration['system_version'];
  103. $_configuration['dokeos_stable'] = $_configuration['system_stable'];
  104. $userPasswordCrypted = (!empty($_configuration['password_encryption']) ? $_configuration['password_encryption'] : 'sha1');
  105. }
  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. //Pagerfanta settings
  296. use FranMoreno\Silex\Provider\PagerfantaServiceProvider;
  297. $app->register(new PagerfantaServiceProvider());
  298. $app['pagerfanta.view.options'] = array(
  299. 'routeName' => null,
  300. 'routeParams' => array(),
  301. 'pageParameter' => '[page]',
  302. 'proximity' => 3,
  303. 'next_message' => '&raquo;',
  304. 'prev_message' => '&laquo;',
  305. 'default_view' => 'twitter_bootstrap'
  306. );
  307. //$app['pagerfanta.view.router.name']
  308. //$app['pagerfanta.view.router.params']
  309. //Monolog only available if cache is writable
  310. if (is_writable($app['cache.path'])) {
  311. /*
  312. Adding Monolog service provider
  313. Monolog use examples
  314. $app['monolog']->addDebug('Testing the Monolog logging.');
  315. $app['monolog']->addInfo('Testing the Monolog logging.');
  316. $app['monolog']->addError('Testing the Monolog logging.');
  317. */
  318. $app->register(
  319. new Silex\Provider\MonologServiceProvider(),
  320. array(
  321. 'monolog.logfile' => $app['chamilo.log'],
  322. 'monolog.name' => 'chamilo',
  323. )
  324. );
  325. }
  326. //Setting Doctrine service provider (DBAL)
  327. if (isset($_configuration['main_database'])) {
  328. $app->register(new Silex\Provider\DoctrineServiceProvider(), array(
  329. 'db.options' => array(
  330. 'driver' => 'pdo_mysql',
  331. 'dbname' => $_configuration['main_database'],
  332. 'user' => $_configuration['db_user'],
  333. 'password' => $_configuration['db_password'],
  334. 'host' => $_configuration['db_host'],
  335. 'driverOptions' => array(
  336. 1002 => 'SET NAMES utf8'
  337. )
  338. )
  339. ));
  340. //Setting Doctrine ORM
  341. $app->register(new Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider, array(
  342. 'orm.auto_generate_proxies' => true,
  343. "orm.proxies_dir" => $app['db.orm.proxies_dir'],
  344. //'orm.proxies_namespace' => '\Doctrine\ORM\Proxy\Proxy',
  345. "orm.em.options" => array(
  346. "mappings" => array(
  347. array(
  348. //If true, only simple notations like @Entity will work. If false, more advanced notations and aliasing via use will work. (Example: use Doctrine\ORM\Mapping AS ORM, @ORM\Entity)
  349. 'use_simple_annotation_reader' => false,
  350. "type" => "annotation",
  351. "namespace" => "Entity",
  352. "path" => api_get_path(INCLUDE_PATH).'Entity',
  353. )
  354. ),
  355. ),
  356. ));
  357. //Temporal fix to load gedmo libs
  358. $sortableGroup = new Gedmo\Mapping\Annotation\SortableGroup(array());
  359. $sortablePosition = new Gedmo\Mapping\Annotation\SortablePosition(array());
  360. //Setting Doctrine2 extensions
  361. $timestampableListener = new \Gedmo\Timestampable\TimestampableListener();
  362. $app['db.event_manager']->addEventSubscriber($timestampableListener);
  363. $sluggableListener = new \Gedmo\Sluggable\SluggableListener();
  364. $app['db.event_manager']->addEventSubscriber($sluggableListener);
  365. $sortableListener = new Gedmo\Sortable\SortableListener();
  366. $app['db.event_manager']->addEventSubscriber($sortableListener);
  367. }
  368. define('IMAGE_PROCESSOR', 'gd'); // imagick or gd strings
  369. $app->register(new Grom\Silex\ImagineServiceProvider(), array(
  370. 'imagine.factory' => 'Gd',
  371. //'imagine.base_path' => __DIR__.'/vendor/imagine',
  372. ));
  373. $app['is_admin'] = false;
  374. //Creating a Chamilo service provider
  375. use Silex\ServiceProviderInterface;
  376. class ChamiloServiceProvider implements ServiceProviderInterface
  377. {
  378. public function register(Application $app)
  379. {
  380. //Template
  381. $app['template'] = $app->share(function () use ($app) {
  382. $template = new Template(null, $app);
  383. return $template;
  384. });
  385. $app['page_controller'] = $app->share(function () use ($app) {
  386. $pageController = new PageController($app);
  387. return $pageController;
  388. });
  389. }
  390. public function boot(Application $app)
  391. {
  392. }
  393. }
  394. //Registering Chamilo service provider
  395. $app->register(new ChamiloServiceProvider(), array());
  396. //Manage error messages
  397. $app->error(
  398. function (\Exception $e, $code) use ($app) {
  399. if ( $e instanceof PDOException) {
  400. }
  401. if ($app['debug']) {
  402. //return;
  403. }
  404. if (isset($code)) {
  405. switch ($code) {
  406. case 404:
  407. $message = 'The requested page could not be found.';
  408. break;
  409. default:
  410. //$message = 'We are sorry, but something went terribly wrong.';
  411. $message = $e->getMessage();
  412. }
  413. } else {
  414. $code = null;
  415. $message = null;
  416. }
  417. //$code = ($e instanceof HttpException) ? $e->getStatusCode() : 500;
  418. $app['template']->assign('error_code', $code);
  419. $app['template']->assign('error_message', $message);
  420. $response = $app['template']->render_layout('error.tpl');
  421. return new Response($response);
  422. }
  423. );
  424. //Prompts Doctrine SQL queries using monolog
  425. if ($app['debug'] && isset($_configuration['main_database'])) {
  426. $logger = new Doctrine\DBAL\Logging\DebugStack();
  427. $app['db.config']->setSQLLogger($logger);
  428. $app->after(function() use ($app, $logger) {
  429. // Log all queries as DEBUG.
  430. foreach ($logger->queries as $query) {
  431. $app['monolog']->debug($query['sql'], array('params' =>$query['params'], 'types' => $query['types']));
  432. }
  433. });
  434. }
  435. //Database constants
  436. require_once $libPath.'database.constants.inc.php';
  437. require_once $libPath.'events.lib.inc.php';
  438. // Connect to the server database and select the main chamilo database.
  439. if (!($conn_return = @Database::connect(
  440. array(
  441. 'server' => $_configuration['db_host'],
  442. 'username' => $_configuration['db_user'],
  443. 'password' => $_configuration['db_password'],
  444. 'persistent' => $_configuration['db_persistent_connection']
  445. // When $_configuration['db_persistent_connection'] is set, it is expected to be a boolean type.
  446. )
  447. ))
  448. ) {
  449. //$app->abort(500, "Database is unavailable"); //error 3
  450. }
  451. /*
  452. if (!$_configuration['db_host']) {
  453. //$app->abort(500, "Database is unavailable"); //error 3
  454. }*/
  455. /* RETRIEVING ALL THE CHAMILO CONFIG SETTINGS FOR MULTIPLE URLs FEATURE*/
  456. if (!empty($_configuration['multiple_access_urls'])) {
  457. $_configuration['access_url'] = 1;
  458. $access_urls = api_get_access_urls();
  459. $protocol = ((!empty($_SERVER['HTTPS']) && strtoupper($_SERVER['HTTPS']) != 'OFF') ? 'https' : 'http').'://';
  460. $request_url1 = $protocol.$_SERVER['SERVER_NAME'].'/';
  461. $request_url2 = $protocol.$_SERVER['HTTP_HOST'].'/';
  462. foreach ($access_urls as & $details) {
  463. if ($request_url1 == $details['url'] or $request_url2 == $details['url']) {
  464. $_configuration['access_url'] = $details['id'];
  465. }
  466. }
  467. } else {
  468. $_configuration['access_url'] = 1;
  469. }
  470. $charset = 'UTF-8';
  471. $checkConnection = false;
  472. if (isset($_configuration['main_database'])) {
  473. // The system has not been designed to use special SQL modes that were introduced since MySQL 5.
  474. Database::query("set session sql_mode='';");
  475. $checkConnection = @Database::select_db($_configuration['main_database'], $conn_return);
  476. if ($checkConnection) {
  477. // Initialization of the database encoding to be used.
  478. Database::query("SET SESSION character_set_server='utf8';");
  479. Database::query("SET SESSION collation_server='utf8_general_ci';");
  480. /* Initialization of the default encodings */
  481. // The platform's character set must be retrieved at this early moment.
  482. /*$sql = "SELECT selected_value FROM settings_current WHERE variable = 'platform_charset';";
  483. $result = Database::query($sql);
  484. while ($row = @Database::fetch_array($result)) {
  485. $charset = $row[0];
  486. }
  487. if (empty($charset)) {
  488. $charset = 'UTF-8';
  489. }*/
  490. //Charset is UTF-8
  491. if (api_is_utf8($charset)) {
  492. // 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.
  493. Database::query("SET NAMES 'utf8';");
  494. } else {
  495. Database::query("SET CHARACTER SET '".Database::to_db_encoding($charset)."';");
  496. }
  497. Database::query("SET NAMES 'utf8';");
  498. }
  499. }
  500. // Preserving the value of the global variable $charset.
  501. $charset_initial_value = $charset;
  502. // Initialization of the internationalization library.
  503. api_initialize_internationalization();
  504. // Initialization of the default encoding that will be used by the multibyte string routines in the internationalization library.
  505. api_set_internationalization_default_encoding($charset);
  506. // Start session after the internationalization library has been initialized
  507. //@todo use silex session provider instead of a custom class
  508. Chamilo::session()->start($alreadyInstalled);
  509. //Loading chamilo settings
  510. if ($alreadyInstalled && $checkConnection) {
  511. $settings_refresh_info = api_get_settings_params_simple(array('variable = ?' => 'settings_latest_update'));
  512. $settings_latest_update = $settings_refresh_info ? $settings_refresh_info['selected_value'] : null;
  513. $_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null;
  514. $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null;
  515. if (empty($_setting)) {
  516. api_set_settings_and_plugins();
  517. } else {
  518. if (isset($_setting['settings_latest_update']) && $_setting['settings_latest_update'] != $settings_latest_update) {
  519. api_set_settings_and_plugins();
  520. $_setting = isset($_SESSION['_setting']) ? $_SESSION['_setting'] : null;
  521. $_plugins = isset($_SESSION['_plugins']) ? $_SESSION['_plugins'] : null;
  522. }
  523. }
  524. }
  525. // Load allowed tag definitions for kses and/or HTMLPurifier.
  526. require_once $libPath.'formvalidator/Rule/allowed_tags.inc.php';
  527. // which will then be usable from the banner and header scripts
  528. $app['this_section'] = SECTION_GLOBAL;
  529. // include the local (contextual) parameters of this course or section
  530. require $includePath.'/local.inc.php';
  531. //Adding web profiler
  532. if (is_writable($app['cache.path'])) {
  533. //if ($app['debug']) {
  534. if (api_get_setting('allow_web_profiler') == 'true') {
  535. $app->register($p = new Silex\Provider\WebProfilerServiceProvider(), array(
  536. 'profiler.cache_dir' => $app['profiler.cache_dir'],
  537. ));
  538. $app->mount('/_profiler', $p);
  539. }
  540. //}
  541. }
  542. // Email service provider
  543. $app->register(new Silex\Provider\SwiftmailerServiceProvider(), array(
  544. 'swiftmailer.options' => array(
  545. 'host' => isset($platform_email['SMTP_HOST']) ? $platform_email['SMTP_HOST'] : null,
  546. 'port' => isset($platform_email['SMTP_PORT']) ? $platform_email['SMTP_PORT'] : null,
  547. 'username' => isset($platform_email['SMTP_USER']) ? $platform_email['SMTP_USER'] : null,
  548. 'password' => isset($platform_email['SMTP_PASS']) ? $platform_email['SMTP_PASS'] : null,
  549. 'encryption' => null,
  550. 'auth_mode' => null
  551. )
  552. ));
  553. //if (isset($platform_email['SMTP_MAILER']) && $platform_email['SMTP_MAILER'] == 'smtp') {
  554. $app['mailer'] = $app->share(function ($app) {
  555. return new \Swift_Mailer($app['swiftmailer.transport']);
  556. });
  557. // Check and modify the date of user in the track.e.online table
  558. if ($alreadyInstalled && !$x = strpos($_SERVER['PHP_SELF'], 'whoisonline.php')) {
  559. Online::LoginCheck(isset($_user['user_id']) ? $_user['user_id'] : '');
  560. }
  561. $app['api_get_languages'] = api_get_languages();
  562. /* Loading languages and sublanguages */
  563. // if we use the javascript version (without go button) we receive a get
  564. // if we use the non-javascript version (with the go button) we receive a post
  565. // Include all files (first english and then current interface language)
  566. $app['this_script'] = isset($this_script) ? $this_script : null;
  567. // Checking if we have a valid language. If not we set it to the platform language.
  568. if ($alreadyInstalled) {
  569. $app['language_interface'] = $language_interface = api_get_language_interface();
  570. } else {
  571. $app['language_interface'] = $language_interface = 'english';
  572. }
  573. // Sometimes the variable $language_interface is changed
  574. // temporarily for achieving translation in different language.
  575. // We need to save the genuine value of this variable and
  576. // to use it within the function get_lang(...).
  577. $language_interface_initial_value = $language_interface;
  578. $langPath = api_get_path(SYS_LANG_PATH);
  579. $this_script = $app['this_script'];
  580. $language_interface = $app['language_interface'];
  581. /* This will only work if we are in the page to edit a sub_language */
  582. if (isset($this_script) && $this_script == 'sub_language') {
  583. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  584. // getting the arrays of files i.e notification, trad4all, etc
  585. $language_files_to_load = SubLanguageManager:: get_lang_folder_files_list(
  586. api_get_path(SYS_LANG_PATH).'english',
  587. true
  588. );
  589. //getting parent info
  590. $languageId = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
  591. $parent_language = SubLanguageManager::get_all_information_of_language($languageId);
  592. $subLanguageId = isset($_REQUEST['sub_language_id']) ? $_REQUEST['sub_language_id'] : null;
  593. //getting sub language info
  594. $sub_language = SubLanguageManager::get_all_information_of_language($subLanguageId);
  595. $english_language_array = $parent_language_array = $sub_language_array = array();
  596. if (!empty($language_files_to_load))
  597. foreach ($language_files_to_load as $language_file_item) {
  598. $lang_list_pre = array_keys($GLOBALS);
  599. //loading english
  600. $path = $langPath.'english/'.$language_file_item.'.inc.php';
  601. if (file_exists($path)) {
  602. include $path;
  603. }
  604. $lang_list_post = array_keys($GLOBALS);
  605. $lang_list_result = array_diff($lang_list_post, $lang_list_pre);
  606. unset($lang_list_pre);
  607. // english language array
  608. $english_language_array[$language_file_item] = compact($lang_list_result);
  609. //cleaning the variables
  610. foreach ($lang_list_result as $item) {
  611. unset(${$item});
  612. }
  613. $parent_file = $langPath.$parent_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  614. if (file_exists($parent_file) && is_file($parent_file)) {
  615. include_once $parent_file;
  616. }
  617. // parent language array
  618. $parent_language_array[$language_file_item] = compact($lang_list_result);
  619. //cleaning the variables
  620. foreach ($lang_list_result as $item) {
  621. unset(${$item});
  622. }
  623. if (!empty($sub_language)) {
  624. $sub_file = $langPath.$sub_language['dokeos_folder'].'/'.$language_file_item.'.inc.php';
  625. if (file_exists($sub_file) && is_file($sub_file)) {
  626. include $sub_file;
  627. }
  628. }
  629. // sub language array
  630. $sub_language_array[$language_file_item] = compact($lang_list_result);
  631. //cleaning the variables
  632. foreach ($lang_list_result as $item) {
  633. unset(${$item});
  634. }
  635. }
  636. }
  637. /**
  638. * Include all necessary language files
  639. * - trad4all
  640. * - notification
  641. * - custom tool language files
  642. */
  643. $language_files = array();
  644. $language_files[] = 'trad4all';
  645. $language_files[] = 'notification';
  646. $language_files[] = 'accessibility';
  647. //@todo Added because userportal and index are loaded by a controller should be fixed when a $app['translator'] is configured
  648. $language_files[] = 'index';
  649. $language_files[] = 'courses';
  650. if (isset($language_file)) {
  651. if (!is_array($language_file)) {
  652. $language_files[] = $language_file;
  653. } else {
  654. $language_files = array_merge($language_files, $language_file);
  655. }
  656. }
  657. if (isset($app['languages_file'])) {
  658. $language_files = array_merge($language_files, $app['languages_file']);
  659. }
  660. // if a set of language files has been properly defined
  661. if (is_array($language_files)) {
  662. // if the sub-language feature is on
  663. if (api_get_setting('allow_use_sub_language') == 'true') {
  664. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  665. $parent_path = SubLanguageManager::get_parent_language_path($language_interface);
  666. foreach ($language_files as $index => $language_file) {
  667. // include English
  668. include $langPath.'english/'.$language_file.'.inc.php';
  669. // prepare string for current language and its parent
  670. $lang_file = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  671. $parent_lang_file = $langPath.$parent_path.'/'.$language_file.'.inc.php';
  672. // load the parent language file first
  673. if (file_exists($parent_lang_file)) {
  674. include $parent_lang_file;
  675. }
  676. // overwrite the parent language translations if there is a child
  677. if (file_exists($lang_file)) {
  678. include $lang_file;
  679. }
  680. }
  681. } else {
  682. // if the sub-languages feature is not on, then just load the
  683. // set language interface
  684. foreach ($language_files as $index => $language_file) {
  685. // include English
  686. include $langPath.'english/'.$language_file.'.inc.php';
  687. // prepare string for current language
  688. $langFile = $langPath.$language_interface.'/'.$language_file.'.inc.php';
  689. if (file_exists($langFile)) {
  690. include $langFile;
  691. }
  692. }
  693. }
  694. }
  695. /* End loading languages */
  696. // Specification for usernames:
  697. // 1. ASCII-letters, digits, "." (dot), "_" (underscore) are acceptable, 40 characters maximum length.
  698. // 2. Empty username is formally valid, but it is reserved for the anonymous user.
  699. // 3. Checking the login_is_email portal setting in order to accept 100 chars maximum
  700. $default_username_length = 40;
  701. if (api_get_setting('login_is_email') == 'true') {
  702. $default_username_length = 100;
  703. }
  704. define('USERNAME_MAX_LENGTH', $default_username_length);
  705. //Silex filters: before|after|finish
  706. $app->before(
  707. function () use ($app, $checkConnection) {
  708. if (!file_exists($app['configuration_file']) && !file_exists($app['configuration_yml_file'])) {
  709. return new RedirectResponse(api_get_path(WEB_CODE_PATH).'install');
  710. $app->abort(500, "Incorrect PHP version");
  711. }
  712. //Check the PHP version
  713. if (api_check_php_version() == false) {
  714. $app->abort(500, "Incorrect PHP version");
  715. }
  716. if ($checkConnection == false) {
  717. $app->abort(500, "Database not available");
  718. }
  719. if (!is_writable(api_get_path(SYS_ARCHIVE_PATH))) {
  720. $app->abort(500, "archive folder must be writeable");
  721. }
  722. //$app['request']->getSession()->start();
  723. }
  724. );
  725. $app->finish(
  726. function (Request $request) use ($app) {
  727. /*if ($request->get('_route') == 'logout') {
  728. }*/
  729. }
  730. );
  731. // The global variable $charset has been defined in a language file too (trad4all.inc.php), this is legacy situation.
  732. // So, we have to reassign this variable again in order to keep its value right.
  733. $charset = $charset_initial_value;
  734. // The global variable $text_dir has been defined in the language file trad4all.inc.php.
  735. // For determing text direction correspondent to the current language we use now information from the internationalization library.
  736. $text_dir = api_get_text_direction();
  737. //Update of the logout_date field in the table track_e_login (needed for the calculation of the total connection time)
  738. if (!isset($_SESSION['login_as']) && isset($_user)) {
  739. // if $_SESSION['login_as'] is set, then the user is an admin logged as the user
  740. $tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);
  741. $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";
  742. $q_last_connection = Database::query($sql_last_connection);
  743. if (Database::num_rows($q_last_connection) > 0) {
  744. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  745. // is the latest logout_date still relevant?
  746. $sql_logout_date = "SELECT logout_date FROM $tbl_track_login WHERE login_id=$i_id_last_connection";
  747. $q_logout_date = Database::query($sql_logout_date);
  748. $res_logout_date = convert_sql_date(Database::result($q_logout_date, 0, 'logout_date'));
  749. if ($res_logout_date < time() - $_configuration['session_lifetime']) {
  750. // it isn't, we should create a fresh entry
  751. event_login();
  752. // now that it's created, we can get its ID and carry on
  753. $q_last_connection = Database::query($sql_last_connection);
  754. $i_id_last_connection = Database::result($q_last_connection, 0, 'login_id');
  755. }
  756. $s_sql_update_logout_date = "UPDATE $tbl_track_login SET logout_date=NOW() WHERE login_id='$i_id_last_connection'";
  757. Database::query($s_sql_update_logout_date);
  758. }
  759. }
  760. // Add language_measure_frequency to your main/inc/conf/configuration.php in
  761. // order to generate language variables frequency measurements (you can then
  762. // see them through main/cron/lang/langstats.php)
  763. // The langstat object will then be used in the get_lang() function.
  764. // This block can be removed to speed things up a bit as it should only ever
  765. // be used in development versions.
  766. if (isset($_configuration['language_measure_frequency']) && $_configuration['language_measure_frequency'] == 1) {
  767. require_once api_get_path(SYS_CODE_PATH).'/cron/lang/langstats.class.php';
  768. $langstats = new langstats();
  769. }
  770. //Default quota for the course documents folder
  771. $default_quota = api_get_setting('default_document_quotum');
  772. //Just in case the setting is not correctly set
  773. if (empty($default_quota)) {
  774. $default_quota = 100000000;
  775. }
  776. define('DEFAULT_DOCUMENT_QUOTA', $default_quota);
  777. //Default template settings loaded in template.inc.php
  778. $app['template.show_header'] = true;
  779. $app['template.show_footer'] = true;
  780. $app['template.show_learnpath'] = false;
  781. $app['template.hide_global_chat'] = !api_is_global_chat_enabled();
  782. $app['template.load_plugins'] = true;
  783. //Default template style
  784. $app['template_style'] = 'default';
  785. //Default layout
  786. $app['default_layout'] = $app['template_style'].'/layout/layout_1_col.tpl';
  787. //Controller as services definitions
  788. $app['pages.controller'] = $app->share(function () use ($app) {
  789. return new PagesController($app['pages.repository']);
  790. });
  791. $app['index.controller'] = $app->share(function () use ($app) {
  792. return new ChamiloLMS\Controller\IndexController();
  793. });
  794. $app['legacy.controller'] = $app->share(function () use ($app) {
  795. return new ChamiloLMS\Controller\LegacyController();
  796. });
  797. $app['userPortal.controller'] = $app->share(function () use ($app) {
  798. return new ChamiloLMS\Controller\UserPortalController();
  799. });
  800. $app['learnpath.controller'] = $app->share(function () use ($app) {
  801. return new ChamiloLMS\Controller\LearnpathController();
  802. });
  803. $app['course_home.controller'] = $app->share(function () use ($app) {
  804. return new ChamiloLMS\Controller\CourseHomeController();
  805. });
  806. /*
  807. class PostController
  808. {
  809. protected $repo;
  810. public function __construct()
  811. {
  812. }
  813. public function indexJsonAction()
  814. {
  815. return 'ddd';
  816. }
  817. }
  818. $app['posts.controller'] = $app->share(function() use ($app) {
  819. return new PostController();
  820. });
  821. $app->mount('/', "posts.controller");*/
  822. //All calls made in Chamilo are manage in the src/ChamiloLMS/Controller/LegacyController.php file function classicAction
  823. $app->get('/', 'legacy.controller:classicAction');
  824. $app->post('/', 'legacy.controller:classicAction');
  825. //index.php
  826. $app->get('/index', 'index.controller:indexAction')->bind('index');
  827. //user_portal.php
  828. $app->get('/userportal', 'userPortal.controller:indexAction');
  829. $app->get('/userportal/{type}/{filter}/{page}', 'userPortal.controller:indexAction')
  830. ->value('type', 'courses')
  831. ->value('filter', 'current')
  832. ->value('page', '1')
  833. ->bind('userportal');
  834. //->assert('type', '.+'); //allowing slash "/"
  835. //Logout page
  836. $app->get('/logout', 'index.controller:logoutAction')->bind('logout');
  837. $app->match('/courses/{courseCode}/index.php', 'course_home.controller:indexAction', 'GET|POST');
  838. $app->match('/courses/{courseCode}', 'course_home.controller:indexAction', 'GET|POST');
  839. //LP controller
  840. $app->match('/learnpath/subscribe_users/{lpId}', 'learnpath.controller:indexAction', 'GET|POST')->bind('subscribe_users');
  841. return $app;