twig.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. require_once 'session.php';
  3. require_once 'database.php';
  4. require_once 'date.php';
  5. require_once 'parsedown.php';
  6. require_once 'template/Twig/Autoloader.php';
  7. require_once 'htmlpurifier/HTMLPurifier.standalone.php';
  8. Twig_Autoloader::register();
  9. $twig = new Twig_Environment(
  10. new Twig_Loader_Filesystem('./template/'), // Path to templates
  11. array('cache' => './cache/template/')); // Path to templates cache
  12. // GLOBALS =================================================================
  13. // A global variable is like any other template variable, except that it's
  14. // available in all templates and macros.
  15. $twig->addGlobal ('user', Session::get_user ());
  16. // FILTERS =================================================================
  17. // A filter transforms the passed value to something else
  18. // Convert a date to "[date] ago"
  19. $twig->addFilter ('ago', new Twig_Filter_Function (function ($datetime) {
  20. return Date::ago (strtotime ($datetime));
  21. }));
  22. // Format Markdown to HTML
  23. $twig->addFilter ('markdown', new Twig_Filter_Function(function ($markdown) {
  24. $parsedown = new Parsedown ();
  25. $purifier_settings = HTMLPurifier_Config::createDefault ();
  26. $purifier_settings->set ('Core', 'EscapeInvalidTags', true);
  27. $purifier = new HTMLPurifier ($purifier_settings);
  28. return $purifier->purify ($parsedown->text ($markdown));
  29. }));
  30. // Return document root
  31. $twig->addFilter ('docroot', new Twig_Filter_Function (function ($url) {
  32. $path = dirname ($_SERVER['SCRIPT_NAME']);
  33. /* This check is required because production server ends the path with
  34. * a slash, whereas my local setup does not.
  35. */
  36. if ('/' != substr ($path, -1))
  37. $path .= '/';
  38. return $path . $url;
  39. }));
  40. // FUNCTIONS ===============================================================
  41. // Return the number of new messages (received, but not read)
  42. $twig->addFunction (new Twig_SimpleFunction ('new_messages', function () {
  43. if (!Session::is_valid ())
  44. return 0;
  45. $db = new Database ();
  46. $db->connect ();
  47. return $db->count_unread_messages (Session::get_userid ());
  48. }));