controller_main.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. class controller_main extends Controller
  3. {
  4. public function __construct()
  5. {
  6. parent::__construct();
  7. if(empty($_SESSION['user'])){
  8. header('Location: /user/login');
  9. }
  10. $this->model = new Model_main();
  11. }
  12. function index()
  13. {
  14. $data['users'] = $this->get_users();
  15. $data['posts'] = $this->model->get_posts();
  16. $this->view->generate('main_view.php', $data);
  17. }
  18. public function createpost(){
  19. if(isset($_POST['caption'], $_POST['post'])){
  20. $this->model->create_post(htmlentities($_POST['caption']), htmlentities($_POST['post']));
  21. }
  22. header('Location: /');
  23. }
  24. public function post($id)
  25. {
  26. if(!$id) Route::ErrorPage404();
  27. $data['post'] = $this->model->get_post($id);
  28. if(!$data['post']) Route::ErrorPage404();
  29. $data['users'] = $this->get_users();
  30. $data['comments'] = $this->model->get_comments($id);
  31. $this->view->generate('post.php', $data);
  32. }
  33. public function add_comment($post_id)
  34. {
  35. if(isset($_POST['comment'])){
  36. $user_id = $_SESSION['user']['id'];
  37. $this->model->add_comment($post_id, $user_id, htmlentities($_POST['comment']));
  38. }
  39. header('Location: /main/post/' . $post_id);
  40. }
  41. private function get_users(): array
  42. {
  43. include 'app/models/model_user.php';
  44. $users_model = new Model_user();
  45. $users = $users_model->get_users();
  46. $ret = [];
  47. foreach ($users as $u)
  48. $ret[$u['id']] = $u['login'];
  49. return $ret;
  50. }
  51. }