bde944f0054b148e2071ac8db35586370107d933
[moodle.git] / mod / forum / classes / local / renderers / discussion_list.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Discussion list renderer.
19  *
20  * @package    mod_forum
21  * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
22  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 namespace mod_forum\local\renderers;
27 defined('MOODLE_INTERNAL') || die();
29 use mod_forum\local\entities\forum as forum_entity;
30 use mod_forum\local\factories\legacy_data_mapper as legacy_data_mapper_factory;
31 use mod_forum\local\factories\exporter as exporter_factory;
32 use mod_forum\local\factories\vault as vault_factory;
33 use mod_forum\local\factories\url as url_factory;
34 use mod_forum\local\managers\capability as capability_manager;
35 use mod_forum\local\vaults\discussion_list as discussion_list_vault;
36 use renderer_base;
37 use stdClass;
38 use core\output\notification;
39 use mod_forum\local\factories\builder as builder_factory;
41 require_once($CFG->dirroot . '/mod/forum/lib.php');
43 /**
44  * The discussion list renderer.
45  *
46  * @package    mod_forum
47  * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
48  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49  */
50 class discussion_list {
51     /** @var forum_entity The forum being rendered */
52     private $forum;
54     /** @var stdClass The DB record for the forum being rendered */
55     private $forumrecord;
57     /** @var renderer_base The renderer used to render the view */
58     private $renderer;
60     /** @var legacy_data_mapper_factory $legacydatamapperfactory Legacy data mapper factory */
61     private $legacydatamapperfactory;
63     /** @var exporter_factory $exporterfactory Exporter factory */
64     private $exporterfactory;
66     /** @var vault_factory $vaultfactory Vault factory */
67     private $vaultfactory;
69     /** @var capability_manager $capabilitymanager Capability manager */
70     private $capabilitymanager;
72     /** @var url_factory $urlfactory URL factory */
73     private $urlfactory;
75     /** @var array $notifications List of notification HTML */
76     private $notifications;
78     /** @var builder_factory $builderfactory Builder factory */
79     private $builderfactory;
81     /** @var callable $postprocessfortemplate Function to process exported posts before template rendering */
82     private $postprocessfortemplate;
84     /** @var string $template The template to use when displaying */
85     private $template;
87     /**
88      * Constructor for a new discussion list renderer.
89      *
90      * @param   forum_entity        $forum The forum entity to be rendered
91      * @param   renderer_base       $renderer The renderer used to render the view
92      * @param   legacy_data_mapper_factory $legacydatamapperfactory The factory used to fetch a legacy record
93      * @param   exporter_factory    $exporterfactory The factory used to fetch exporter instances
94      * @param   vault_factory       $vaultfactory The factory used to fetch the vault instances
95      * @param   builder_factory     $builderfactory The factory used to fetch the builder instances
96      * @param   capability_manager  $capabilitymanager The managed used to check capabilities on the forum
97      * @param   url_factory         $urlfactory The factory used to create URLs in the forum
98      * @param   string              $template
99      * @param   notification[]      $notifications A list of any notifications to be displayed within the page
100      * @param   callable|null       $postprocessfortemplate Callback function to process discussion lists for templates
101      */
102     public function __construct(
103         forum_entity $forum,
104         renderer_base $renderer,
105         legacy_data_mapper_factory $legacydatamapperfactory,
106         exporter_factory $exporterfactory,
107         vault_factory $vaultfactory,
108         builder_factory $builderfactory,
109         capability_manager $capabilitymanager,
110         url_factory $urlfactory,
111         string $template,
112         array $notifications = [],
113         callable $postprocessfortemplate = null
114     ) {
115         $this->forum = $forum;
116         $this->renderer = $renderer;
117         $this->legacydatamapperfactory = $legacydatamapperfactory;
118         $this->exporterfactory = $exporterfactory;
119         $this->vaultfactory = $vaultfactory;
120         $this->builderfactory = $builderfactory;
121         $this->capabilitymanager = $capabilitymanager;
123         $this->urlfactory = $urlfactory;
124         $this->notifications = $notifications;
125         $this->postprocessfortemplate = $postprocessfortemplate;
126         $this->template = $template;
128         $forumdatamapper = $this->legacydatamapperfactory->get_forum_data_mapper();
129         $this->forumrecord = $forumdatamapper->to_legacy_object($forum);
130     }
132     /**
133      * Render for the specified user.
134      *
135      * @param   stdClass    $user The user to render for
136      * @param   cm_info     $cm The course module info for this discussion list
137      * @param   int         $groupid The group to render
138      * @param   int         $sortorder The sort order to use when selecting the discussions in the list
139      * @param   int         $pageno The zero-indexed page number to use
140      * @param   int         $pagesize The number of discussions to show on the page
141      * @return  string      The rendered content for display
142      */
143     public function render(stdClass $user, \cm_info $cm, ?int $groupid, ?int $sortorder, ?int $pageno, ?int $pagesize) : string {
144         global $PAGE;
146         $forum = $this->forum;
148         $pagesize = $this->get_page_size($pagesize);
149         $pageno = $this->get_page_number($pageno);
151         $groupids = $this->get_groups_from_groupid($user, $groupid);
152         $forumexporter = $this->exporterfactory->get_forum_exporter(
153             $user,
154             $this->forum,
155             $groupid
156         );
158         // Count all forum discussion posts.
159         $alldiscussionscount = $this->get_count_all_discussions($user, $groupids);
161         // Get all forum discussions posts.
162         $discussions = $this->get_discussions($user, $groupids, $sortorder, $pageno, $pagesize);
164         $forumview = [
165             'forum' => (array) $forumexporter->export($this->renderer),
166             'groupchangemenu' => groups_print_activity_menu(
167                 $cm,
168                 $this->urlfactory->get_forum_view_url_from_forum($forum),
169                 true
170             ),
171             'hasmore' => ($alldiscussionscount > $pagesize),
172             'notifications' => $this->get_notifications($user, $groupid),
173         ];
175         if (!$discussions) {
176             return $this->renderer->render_from_template($this->template, $forumview);
177         }
179         if ($this->postprocessfortemplate !== null) {
180             // We've got some post processing to do!
181             $exportedposts = ($this->postprocessfortemplate) ($discussions, $user, $forum);
182         }
184         $forumview = array_merge(
185             $forumview,
186             [
187                 'pagination' => $this->renderer->render(new \paging_bar($alldiscussionscount, $pageno, $pagesize, $PAGE->url, 'p')),
188                 'newdiscussionhtml' => $this->get_discussion_form($user, $cm, $groupid)
189             ],
190             $exportedposts
191         );
193         return $this->renderer->render_from_template($this->template, $forumview);
194     }
196     private function get_discussion_form(stdClass $user, \cm_info $cm, ?int $groupid) {
197         global $PAGE;
199         $forum = $this->forum;
200         $forumrecord = $this->legacydatamapperfactory->get_forum_data_mapper()->to_legacy_object($forum);
201         $modcontext = \context_module::instance($cm->id);
202         $post = new stdClass();
203         $post->course        = $forum->get_course_id();
204         $post->forum         = $forum->get_id();
205         $post->discussion    = 0;           // Ie discussion # not defined yet.
206         $post->parent        = 0;
207         $post->subject       = '';
208         $post->userid        = $user->id;
209         $post->message       = '';
210         $post->messageformat = editors_get_preferred_format();
211         $post->messagetrust  = 0;
212         $post->groupid = $groupid;
214         $thresholdwarning = forum_check_throttling($forum, $cm);
215         //$forumrecord = $DB->get_record('forum', array('id' => $forum->get_id()));
216         $mformpost = new \mod_forum_post_form('post.php', array('course' => $forum->get_course_record(),
217             'cm' => $cm,
218             'coursecontext' => $forum->get_context(),
219             'modcontext' => $modcontext,
220             'forum' => $forumrecord,
221             'post' => $post,
222             'subscribe' => \mod_forum\subscriptions::is_subscribed($user->id, $forumrecord,
223                 null, $cm),
224             'thresholdwarning' => $thresholdwarning,
225             'edit' => 0), 'post', '', array('id' => 'mformforum'));
226         // Setup the file related components.
227         $draftitemid = file_get_submitted_draft_itemid('attachments');
228         $attachoptions = \mod_forum_post_form::attachment_options($forumrecord);
229         file_prepare_draft_area($draftitemid, $modcontext->id, 'mod_forum', 'attachment', null, $attachoptions);
231         $params = array('reply' => 0, 'forum' => $forumrecord->id, 'edit' => 0) +
232             (isset($post->groupid) ? array('groupid' => $post->groupid) : array());
233         $mformpost->set_data($params);
235         return $mformpost->render();
236     }
238     /**
239      * Get the list of groups to show based on the current user and requested groupid.
240      *
241      * @param   stdClass    $user The user viewing
242      * @param   int         $groupid The groupid requested
243      * @return  array       The list of groups to show
244      */
245     private function get_groups_from_groupid(stdClass $user, ?int $groupid) : ?array {
246         $forum = $this->forum;
247         $effectivegroupmode = $forum->get_effective_group_mode();
248         if (empty($effectivegroupmode)) {
249             // This forum is not in a group mode. Show all posts always.
250             return null;
251         }
253         if (null == $groupid) {
254             // No group was specified.
255             $showallgroups = (VISIBLEGROUPS == $effectivegroupmode);
256             $showallgroups = $showallgroups || $this->capabilitymanager->can_access_all_groups($user);
257             if ($showallgroups) {
258                 // Return null to show all groups.
259                 return null;
260             } else {
261                 // No group was specified. Only show the users current groups.
262                 return array_keys(
263                     groups_get_all_groups(
264                         $forum->get_course_id(),
265                         $user->id,
266                         $forum->get_course_module_record()->groupingid
267                     )
268                 );
269             }
270         } else {
271             // A group was specified. Just show that group.
272             return [$groupid];
273         }
274     }
276     /**
277      * Fetch the data used to display the discussions on the current page.
278      *
279      * @param   stdClass    $user The user to render for
280      * @param   int[]|null  $groupids The group ids for this list of discussions
281      * @param   int|null    $sortorder The sort order to use when selecting the discussions in the list
282      * @param   int|null    $pageno The zero-indexed page number to use
283      * @param   int|null    $pagesize The number of discussions to show on the page
284      * @return  stdClass    The data to use for display
285      */
286     private function get_discussions(stdClass $user, ?array $groupids, ?int $sortorder, ?int $pageno, ?int $pagesize) {
287         $forum = $this->forum;
288         $discussionvault = $this->vaultfactory->get_discussions_in_forum_vault();
289         if (null === $groupids) {
290             return $discussions = $discussionvault->get_from_forum_id(
291                 $forum->get_id(),
292                 $this->capabilitymanager->can_view_hidden_posts($user),
293                 $user->id,
294                 $sortorder,
295                 $this->get_page_size($pagesize),
296                 $this->get_page_number($pageno) * $this->get_page_size($pagesize));
297         } else {
298             return $discussions = $discussionvault->get_from_forum_id_and_group_id(
299                 $forum->get_id(),
300                 $groupids,
301                 $this->capabilitymanager->can_view_hidden_posts($user),
302                 $user->id,
303                 $sortorder,
304                 $this->get_page_size($pagesize),
305                 $this->get_page_number($pageno) * $this->get_page_size($pagesize));
306         }
307     }
309     /**
310      * Get a count of all discussions in a forum.
311      *
312      * @param   stdClass    $user The user to render for
313      * @param   array       $groupids The array of groups to render
314      * @return  int         The number of discussions in a forum
315      */
316     public function get_count_all_discussions(stdClass $user, ?array $groupids) {
317         $discussionvault = $this->vaultfactory->get_discussions_in_forum_vault();
318         if (null === $groupids) {
319             return $discussionvault->get_total_discussion_count_from_forum_id(
320                 $this->forum->get_id(),
321                 $this->capabilitymanager->can_view_hidden_posts($user),
322                 $user->id);
323         } else {
324             return $discussionvault->get_total_discussion_count_from_forum_id_and_group_id(
325                 $this->forum->get_id(),
326                 $groupids,
327                 $this->capabilitymanager->can_view_hidden_posts($user),
328                 $user->id);
329         }
330     }
332     /**
333      * Fetch the page size to use when displaying the page.
334      *
335      * @param   int         $pagesize The number of discussions to show on the page
336      * @return  int         The normalised page size
337      */
338     private function get_page_size(?int $pagesize) : int {
339         if (null === $pagesize || $pagesize <= 0) {
340             $pagesize = discussion_list_vault::PAGESIZE_DEFAULT;
341         }
343         return $pagesize;
344     }
346     /**
347      * Fetch the current page number (zero-indexed).
348      *
349      * @param   int         $pageno The zero-indexed page number to use
350      * @return  int         The normalised page number
351      */
352     private function get_page_number(?int $pageno) : int {
353         if (null === $pageno || $pageno < 0) {
354             $pageno = 0;
355         }
357         return $pageno;
358     }
360     /**
361      * Get the list of notification for display.
362      *
363      * @param stdClass $user The viewing user
364      * @param int|null $groupid The forum's group id
365      * @return      array
366      */
367     private function get_notifications(stdClass $user, ?int $groupid) : array {
368         $notifications = $this->notifications;
369         $forum = $this->forum;
370         $renderer = $this->renderer;
371         $capabilitymanager = $this->capabilitymanager;
373         if ($forum->is_cutoff_date_reached()) {
374             $notifications[] = (new notification(
375                     get_string('cutoffdatereached', 'forum'),
376                     notification::NOTIFY_INFO
377             ))->set_show_closebutton();
378         } else if ($forum->is_due_date_reached()) {
379             $notifications[] = (new notification(
380                     get_string('thisforumisdue', 'forum', userdate($forum->get_due_date())),
381                     notification::NOTIFY_INFO
382             ))->set_show_closebutton();
383         } else if ($forum->has_due_date()) {
384             $notifications[] = (new notification(
385                     get_string('thisforumhasduedate', 'forum', userdate($forum->get_due_date())),
386                     notification::NOTIFY_INFO
387             ))->set_show_closebutton();
388         }
390         if ($forum->has_blocking_enabled()) {
391             $notifications[] = (new notification(
392                 get_string('thisforumisthrottled', 'forum', [
393                     'blockafter' => $forum->get_block_after(),
394                     'blockperiod' => get_string('secondstotime' . $forum->get_block_period())
395                 ])
396             ))->set_show_closebutton();
397         }
399         if ($forum->is_in_group_mode() && !$capabilitymanager->can_access_all_groups($user)) {
400             if ($groupid === null) {
401                 if (!$capabilitymanager->can_post_to_my_groups($user)) {
402                     $notifications[] = (new notification(
403                         get_string('cannotadddiscussiongroup', 'mod_forum'),
404                         \core\output\notification::NOTIFY_WARNING
405                     ))->set_show_closebutton();
406                 } else {
407                     $notifications[] = (new notification(
408                         get_string('cannotadddiscussionall', 'mod_forum'),
409                         \core\output\notification::NOTIFY_WARNING
410                     ))->set_show_closebutton();
411                 }
412             } else if (!$capabilitymanager->can_access_group($user, $groupid)) {
413                 $notifications[] = (new notification(
414                     get_string('cannotadddiscussion', 'mod_forum'),
415                     \core\output\notification::NOTIFY_WARNING
416                 ))->set_show_closebutton();
417             }
418         }
420         if ('qanda' === $forum->get_type() && !$capabilitymanager->can_manage_forum($user)) {
421             $notifications[] = (new notification(
422                 get_string('qandanotify', 'forum'),
423                 notification::NOTIFY_INFO
424             ))->set_show_closebutton();
425         }
427         if ('eachuser' === $forum->get_type()) {
428             $notifications[] = (new notification(
429                 get_string('allowsdiscussions', 'forum'),
430                 notification::NOTIFY_INFO)
431             )->set_show_closebutton();
432         }
434         return array_map(function($notification) {
435             return $notification->export_for_template($this->renderer);
436         }, $notifications);
437     }