Favourite.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. // {{{ License
  3. // This file is part of GNU social - https://www.gnu.org/software/social
  4. //
  5. // GNU social is free software: you can redistribute it and/or modify
  6. // it under the terms of the GNU Affero General Public License as published by
  7. // the Free Software Foundation, either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // GNU social is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU Affero General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU Affero General Public License
  16. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  17. // }}}
  18. namespace Plugin\Favourite;
  19. use App\Core\DB\DB;
  20. use App\Core\Event;
  21. use App\Core\Form;
  22. use App\Core\Module;
  23. use App\Entity\Favourite as Fave;
  24. use App\Entity\Note;
  25. use App\Util\Common;
  26. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  27. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  28. use Symfony\Component\HttpFoundation\Request;
  29. class Favourite extends Module
  30. {
  31. /**
  32. * HTML rendering event that adds the favourite form as a note
  33. * action, if a user is logged in
  34. */
  35. public function onAddNoteActions(Request $request, Note $note, array &$actions)
  36. {
  37. if (($user = Common::user()) == null) {
  38. return Event::next;
  39. }
  40. $opts = ['note_id' => $note->getId(), 'gsactor_id' => $user->getId()];
  41. $is_set = DB::find('favourite', $opts) != null;
  42. $form = Form::create([
  43. ['is_set', HiddenType::class, ['data' => $is_set ? '1' : '0']],
  44. ['note_id', HiddenType::class, ['data' => $note->getId()]],
  45. ['favourite', SubmitType::class, ['label' => ' ']],
  46. ]);
  47. // Form handler
  48. $ret = self::noteActionHandle($request, $form, $note, 'favourite', function ($note, $data) use ($opts) {
  49. $fave = DB::find('favourite', $opts);
  50. if (!$data['is_set'] && ($fave == null)) {
  51. DB::persist(Fave::create($opts));
  52. DB::flush();
  53. } else {
  54. DB::remove($fave);
  55. DB::flush();
  56. }
  57. return Event::stop;
  58. });
  59. if ($ret != null) {
  60. return $ret;
  61. }
  62. $actions[] = $form->createView();
  63. return Event::next;
  64. }
  65. }