Context.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /**
  3. * Context file.
  4. *
  5. * Provides a handy class with usefull data to be accessible from anywhere in the app.
  6. *
  7. * @author Iñigo Valentin <i@inigovalentin.com>
  8. * @license https://www.gnu.org/licenses/gpl-3.0.en.html GNU General Public License V3
  9. * @package IV
  10. */
  11. require_once(PATH::ENTITY . "User.php");
  12. /**
  13. * Application context.
  14. *
  15. * Stores usefull data to be retrieved anywhere in the app.
  16. *
  17. * @category Context
  18. */
  19. class Context {
  20. /**
  21. * @var SQLITE3 Database connection.
  22. */
  23. private $db;
  24. /**
  25. * Current site user profile.
  26. */
  27. private $user;
  28. /**
  29. * Two letter language code.
  30. */
  31. private $lang;
  32. /**
  33. * List of two letter language codes available in the application.
  34. * */
  35. private $available_languages = [];
  36. public function __construct(){
  37. // TODO: Validate language codes.
  38. $langs = parse_ini_file(__DIR__ . "/config/config.ini", true)["language"]["available"];
  39. $this->available_languages = explode("|", $langs);
  40. $this->lang = parse_ini_file(__DIR__ . "/config/config.ini", true)["language"]["default"];
  41. }
  42. /**
  43. * Retrieves the database connection.
  44. *
  45. * @return SQLITE3 The database connection.
  46. */
  47. public function get_db(){
  48. return $this->db;
  49. }
  50. /**
  51. * Sets the database connection
  52. *
  53. * @param SQLITE3 Database connection.
  54. */
  55. protected function set_db($db){
  56. $this->db = $db;
  57. Log::debug("Context database is set and accesible.");
  58. if ($this->db == null){
  59. Log::error("DB is null");
  60. }
  61. }
  62. public function get_user(){
  63. if ($this->user == null) $this->user = new User();
  64. return $this->user;
  65. }
  66. /**
  67. * Retrieves the language.
  68. *
  69. * @return string Two letter language code.
  70. */
  71. public function get_lang(){
  72. return $this->lang;
  73. }
  74. /**
  75. * Sets the anguage.
  76. * @param string $code Two letter language code.
  77. */
  78. public function set_lang($code){
  79. if (in_array(strtolower($code), $this->available_languages)){
  80. $this->lang = strtolower($code);
  81. setcookie("lang", $this->lang, time()+ 60 * 60 * 24 * 30, "/", $_SERVER["HTTP_HOST"]);
  82. }
  83. else Log::warn("Tried to set unsupported language '$code'");
  84. }
  85. /**
  86. * Retrieves the list of available languages.
  87. *
  88. * @return string Two letter language code of avilable languages.
  89. */
  90. public function get_available_langs(){
  91. return $this->available_languages;
  92. }
  93. }