-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmod_forumng_post.php
2599 lines (2334 loc) · 97 KB
/
mod_forumng_post.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Represents a single forum post.
* @see mod_forumng_discussion
* @see forum
* @package mod
* @subpackage forumng
* @copyright 2011 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class mod_forumng_post {
const PARENT_NOT_LOADED = 'not_loaded';
const PARENTPOST_DEPTH_PER_QUERY = 8;
// For option definitions, see forumngtype.php display_post function
const OPTION_EMAIL = 'email';
const OPTION_DIGEST = 'digest';
const OPTION_COMMAND_REPLY = 'command_reply';
const OPTION_COMMAND_EDIT = 'command_edit';
const OPTION_COMMAND_DELETE = 'command_delete';
const OPTION_COMMAND_UNDELETE = 'command_undelete';
const OPTION_COMMAND_SPLIT = 'command_split';
const OPTION_COMMAND_HISTORY = 'command_history';
const OPTION_COMMAND_REPORT = 'command_report';
const OPTION_COMMAND_DIRECTLINK = 'command_directlink';
const OPTION_VIEW_FULL_NAMES = 'view_full_names';
const OPTION_TIME_ZONE = 'time_zone';
const OPTION_SUMMARY = 'summary';
const OPTION_NO_COMMANDS = 'no_commands';
const OPTION_RATINGS_VIEW = 'ratings_view';
const OPTION_RATINGS_EDIT = 'ratings_edit';
const OPTION_VIEW_DELETED_INFO = 'deleted_info';
const OPTION_EXPANDED = 'short';
const OPTION_FLAG_CONTROL = 'flag_control';
const OPTION_READ_TIME = 'read_time';
const OPTION_CHILDREN_EXPANDED = 'children_expanded';
const OPTION_CHILDREN_COLLAPSED = 'children_collapsed';
const OPTION_INCLUDE_LOCK = 'include_lock';
const OPTION_EXPORT = 'export';
const OPTION_FULL_ADDRESSES = 'full_addresses';
const OPTION_DISCUSSION_SUBJECT = 'discussion_subject';
const OPTION_SELECTABLE = 'selectable';
const OPTION_VISIBLE_POST_NUMBERS = 'visible_post_numbers';
const OPTION_USER_IMAGE = 'user_image';
const OPTION_PRINTABLE_VERSION = 'printable_version';
const OPTION_JUMP_NEXT = 'jump_next';
const OPTION_JUMP_PREVIOUS = 'jump_previous';
const OPTION_JUMP_PARENT = 'jump_parent';
const OPTION_FIRST_UNREAD = 'first_unread';
const OPTION_UNREAD_NOT_HIGHLIGHTED = 'unread_not_highlighted';
const OPTION_SINGLE_POST = 'single_post';
const OPTION_PARTICIPATION = 'in_participation_screen';
const OPTION_DONT_DISPLAY_ROOTPOST = 'dont_display_rootpost';
const OPTION_COMMAND_TOTALREPLY = 'command_total_reply';
const OPTION_PARENT_POSTNUMBER = 'parent_post_number';
const OPTION_DONT_DISPLAY_COLLAPSED = 'dont_display_collapsed';
/** Constant indicating that post is not rated by user */
const NO_RATING = 999;
const OPTION_INDICATE_MODERATOR = 'indicate_moderator';
const OPTION_IS_ANON = 'is_anon';
const OPTION_VIEW_ANON_INFO = 'view_anon';
const OPTION_MAILTO_USERID = 'mailto_userid';
// Object variables and accessors
// Comment.
private $discussion, $parentpost, $postfields, $full, $children,
$forceexpand, $nextunread, $previousunread;
/** @return mod_forumng The forum that this post is in */
public function get_forum() {
return $this->discussion->get_forum();
}
/** @return mod_forumng_post Parent post*/
public function get_parent() {
if ($this->parentpost==self::PARENT_NOT_LOADED) {
throw new coding_exception('Parent post not loaded');
}
return $this->parentpost;
}
/** @return mod_forumng_discussion The discussion that this post is in */
public function get_discussion() {
return $this->discussion;
}
/** @return int ID of this post */
public function get_id() {
return $this->postfields->id;
}
/** @return string Subject or null if no change in subject */
public function get_subject() {
return $this->postfields->subject;
}
/** @return int Post number [within discussion] */
public function get_number() {
if (!property_exists($this->postfields, 'number')) {
throw new coding_exception('Post number not available here');
}
return $this->postfields->number;
}
/**
* Use to obtain link parameters when linking to any page that has anything
* to do with posts.
*/
public function get_link_params($type, $currentuser = false) {
global $USER;
$params = 'p=' . $this->postfields->id .
$this->get_forum()->get_clone_param($type);
if ($currentuser) {
$author = $this->get_user();
if ($author->id == $USER->id) {
$params .= '¤tuser=1';
}
}
return $params;
}
/**
* @return bool True if can flag
*/
public function can_flag() {
// Cannot flag for deleted post
if ($this->get_deleted() || $this->discussion->is_deleted()) {
return false;
}
// The guest user cannot flag
if (isguestuser()) {
return false;
}
return true;
}
/** @return bool True if post is flagged by current user */
public function is_flagged() {
if (!property_exists($this->postfields, 'flagged')) {
throw new coding_exception('Flagged information not available here');
}
return $this->postfields->flagged ? true : false;
}
/**
* @param bool $flag True to set flag
* @param int $userid User ID or 0 for current
*/
public function set_flagged($flag, $userid=0) {
global $DB;
$userid = mod_forumng_utils::get_real_userid($userid);
if ($flag) {
$transaction = $DB->start_delegated_transaction();
// Check there is not already a row
if (!$DB->record_exists('forumng_flags',
array('postid' => $this->get_id(), 'userid' => $userid))) {
// Insert new row
$newflag = (object)array('postid' => $this->get_id(),
'userid' => $userid, 'flagged' => time());
$DB->insert_record('forumng_flags', $newflag);
}
// Note: Under rare circumstances this could result in two rows
// for the same post and user, resulting in duplicates being
// returned. This is dealt with in mod_forumng::get_flagged_posts.
$transaction->allow_commit();
} else {
$DB->delete_records('forumng_flags',
array('postid' => $this->get_id(), 'userid' => $userid));
}
}
/**
* Obtains the subject to use for this post where a subject is required
* (should not be blank), such as in email. May be of the form Re:
* <parent subject>. This function call makes a database query if the full
* discussion was not loaded into memory.
* @param bool $expectingquery Set to true if you think this might make
* a db query (to prevent the warning)
* @return string Subject
*/
public function get_effective_subject($expectingquery = false) {
if (property_exists($this->postfields, 'effectivesubject')) {
return $this->postfields->effectivesubject;
}
// If subject is set in this post, return it
if (!is_null($this->postfields->subject)) {
$this->postfields->effectivesubject = $this->postfields->subject;
return $this->postfields->effectivesubject;
}
// See if we already have other posts loaded
if ($this->parentpost == self::PARENT_NOT_LOADED) {
// Posts are not loaded, do a database query
if (!$expectingquery) {
debugging('This get method made a DB query; if this is expected,
set the flag to say so', DEBUG_DEVELOPER);
}
$this->postfields->effectivesubject =
self::inner_get_recursive_subject($this->postfields->parentpostid);
return $this->postfields->effectivesubject;
} else {
// Posts are loaded, loop through them to find subject
for ($parent = $this->parentpost; $parent!=null;
$parent = $parent->parentpost) {
if ($parent->postfields->subject!==null) {
return get_string('re', 'forumng',
$parent->postfields->subject);
}
}
return '[subject error]'; // shouldn't get here
}
}
/**
* Given a post id - or the id of some ancestor of a post - this query
* obtains the next (up to) 8 ancestors and returns a 'Re:' subject line
* corresponding to the first ancestor which has a subject. If none of
* the 8 have a subject, it makes another query to retrieve the next 8,
* and so on.
* @param int $parentid ID of a child post that we are trying to find
* the subject from a parent of
* @return string Subject of post ('Re: something')
*/
private static function inner_get_recursive_subject($parentid) {
global $DB;
// Although the query looks scary because it has so many left joins,
// in testing it worked quickly. The db just does eight primary-key
// lookups. Analysis of existing posts in our database showed that
// doing 8 levels is currently sufficient for about 98.7% of posts.
$select = '';
$join = '';
$maxdepth = self::PARENTPOST_DEPTH_PER_QUERY;
for ($depth = 1; $depth <= $maxdepth; $depth++) {
$select .= "p$depth.subject AS s$depth, p$depth.deleted AS d$depth, ";
if ($depth >= 2) {
$prev = $depth - 1;
$join .= "LEFT JOIN {forumng_posts} p$depth
ON p$depth.id = p$prev.parentpostid ";
}
}
do {
$rec = $DB->get_record_sql("
SELECT
$select
p$maxdepth.parentpostid AS nextparent
FROM
{forumng_posts} p1
$join
WHERE
p1.id = ?
", array($parentid), MUST_EXIST);
for ($depth = 1; $depth <= $maxdepth; $depth++) {
$var = "s$depth";
$var2 = "d$depth";
if (isset($rec->{$var}) && $rec->{$var2}==0) {
return get_string('re', 'forumng', $rec->{$var});
}
}
$parentid = isset($rec->nextparent) ? $rec->nextparent : null;
} while ($parentid);
// If the database and memory representations are correct, we shouldn't
// really get here because the top-level post always has a subject
return '';
}
/** @return object User who created this post */
public function get_user() {
if (!property_exists($this->postfields, 'user')) {
throw new coding_exception('User is not available at this point.');
}
return $this->postfields->user;
}
/** @return object User who last edited this post or null if no edits */
public function get_edit_user() {
if (!property_exists($this->postfields, 'edituser')) {
throw new coding_exception('Edit user is not available at this point.');
}
return is_null($this->postfields->edituserid)
? null : $this->postfields->edituser;
}
/** @return int Time post was originally created */
public function get_created() {
return $this->postfields->created;
}
/** @return int Time post was most recently modified */
public function get_modified() {
return $this->postfields->modified;
}
/** @return int 0 if post is not deleted, otherwise time of deletion */
public function get_deleted() {
return $this->postfields->deleted;
}
/** @return object User object (basic fields) of deleter */
public function get_delete_user() {
return $this->postfields->deleteuser;
}
/** @return bool True if this is an old version of a post */
public function is_old_version() {
return $this->postfields->oldversion ? true : false;
}
/** @return bool True if the post is important */
public function is_important() {
return $this->postfields->important ? true : false;
}
/** @return string Message data from database (May be in arbitrary format) */
public function get_raw_message() {
return $this->postfields->message;
}
/** @return int Format of message (Moodle FORMAT_xx constant) */
public function get_format() {
return $this->postfields->messageformat;
}
/**
* @param array $options.
* @return string Message after format_text and replacing file URLs
*/
public function get_formatted_message($options = null) {
global $CFG;
require_once($CFG->dirroot . '/lib/filelib.php');
$foremail = false;
if (!empty($options) && array_key_exists(self::OPTION_EMAIL, $options)) {
$foremail = $options[self::OPTION_EMAIL];
}
$text = $this->postfields->message;
$forum = $this->get_forum();
// Add clone param to end of pluginfile requests
if ($forum->is_shared()) {
// "@@PLUGINFILE@@/cheese.gif?download=1"
$text = preg_replace('~([\'"]@@PLUGINFILE@@[^\'"?]+)\?~',
'$1?clone=' . $forum->get_course_module_id() . '&', $text);
// "@@PLUGINFILE@@/cheese.gif"
$text = preg_replace('~([\'"]@@PLUGINFILE@@[^\'"?]+)([\'"])~',
'$1?clone=' . $forum->get_course_module_id() . '$2', $text);
}
$id = $this->get_id();
if ($this->is_old_version()) {
// If old version get id of parent post as images stored against this.
$id = $this->get_parent()->get_id();
}
$context = $forum->get_context(true);
if ($foremail) {
$fileurlbase = 'mod/forumng/pluginfile.php';
} else {
$fileurlbase = 'pluginfile.php';
}
$text = file_rewrite_pluginfile_urls($text, $fileurlbase,
$context->id, 'mod_forumng', 'message', $id);
if ($foremail && (!isset($CFG->slasharguments) || $CFG->slasharguments != 0)) {
// Append hash if this post render for email.
$text = $this->add_hash_to_image($text);
}
$textoptions = new stdClass();
// Don't put a <p> tag round post
$textoptions->para = false;
if (trusttext_active() && $this->get_user() && has_capability('moodle/site:trustcontent',
$context, $this->get_user())) {
// Support trusted text when initial author is safe (post editors are not checked!).
$textoptions->trusted = true;
}
$textoptions->context = $context;
return format_text($text, $this->postfields->messageformat, $textoptions);
}
/**
* @return string Message after format_text_email and replacing file URLs
*/
public function get_email_message() {
global $CFG;
require_once($CFG->dirroot . '/lib/filelib.php');
$text = file_rewrite_pluginfile_urls($this->postfields->message, 'pluginfile.php',
$this->get_forum()->get_context(true)->id, 'mod_forumng', 'message',
$this->postfields->id);
return format_text_email($text, $this->postfields->messageformat);
}
/** @return bool True if this message has one or more attachments */
public function has_attachments() {
return $this->postfields->attachments ? true : false;
}
/**
* Gets the names of all attachments (if any)
* @return array Array of attachment names (may be empty). Names only,
* not including path to attachment folder
*/
public function get_attachment_names() {
$result = array();
if (!$this->has_attachments()) {
return $result;
}
$filecontext = $this->get_forum()->get_context(true);
$fs = get_file_storage();
foreach ($fs->get_area_files($filecontext->id, 'mod_forumng', 'attachment',
$this->get_id(), 'filename', false) as $file) {
$result[] = $file->get_filename();
}
return $result;
}
/**
* @param string $attachment Attachment name (will not be checked for existence)
* @return moodle_url URL to attachment
*/
public function get_attachment_url($attachment) {
$filecontext = $this->get_forum()->get_context(true);
$params = array();
if ($this->get_forum()->is_shared()) {
$params['clone'] = $this->get_forum()->get_course_module_id();
}
return new moodle_url('/pluginfile.php/' . $filecontext->id . '/mod_forumng/attachment/' .
$this->get_id() . '/' . rawurlencode($attachment), $params);
}
/**
* @return string URL of this discussion
*/
public function get_url() {
return $this->get_discussion()->get_url() . '#p' . $this->get_id();
}
/**
* Marks this post read.
* @param int $time Time to mark it read at (0 = now)
* @param int $userid User who's read the post (0 = current)
*/
public function mark_read($time = 0, $userid = 0) {
global $DB;
$userid = mod_forumng_utils::get_real_userid($userid);
if (!$time) {
$time = time();
}
$transaction = $DB->start_delegated_transaction();
// Check for existing record - should never have one, but do this in case.
$existing = $DB->get_record('forumng_read_posts', array('userid' => $userid,
'postid' => $this->get_id()), '*', IGNORE_MISSING);
if ($existing) {
$readrecord = new stdClass();
$readrecord->id = $existing->id;
$readrecord->time = $time;
$DB->update_record('forumng_read_posts', $readrecord);
} else {
$readrecord = new stdClass();
$readrecord->userid = $userid;
$readrecord->postid = $this->get_id();
$readrecord->time = $time;
$DB->insert_record('forumng_read_posts', $readrecord);
}
$transaction->allow_commit();
$this->log('read post');
}
/**
* Checks unread status (only available when requested as part of whole
* discussion).
* @return bool True if this post is unread
* @throws mod_forumng_exception If unread data is not available
*/
public function is_unread() {
// Your own posts are always read (note: technically you can request
// unread data for another user - so we use the id for whom data was
// requested, not $USER->id directly).
$userid = $this->discussion->get_unread_data_user_id();
if (($this->postfields->edituserid == $userid) ||
(!$this->postfields->edituserid
&& $this->postfields->userid==$userid)) {
return false;
}
// Posts past sell-by are always read
$deadline = mod_forumng::get_read_tracking_deadline();
if ($this->postfields->modified < $deadline) {
return false;
}
if ($this->get_deleted()) {
return false;
}
$timeread = $this->discussion->get_time_read();
// If later manual mark post as read record then use that as read time.
if (!empty($this->postfields->uread) && $this->postfields->uread > $timeread) {
$timeread = $this->postfields->uread;
}
// Compare date to discussion read data.
return $this->postfields->modified > $timeread;
}
/**
* Checks unread status of child posts (only available when requested as
* part of whole discussion). Not a recursive method - checks only one
* level of children.
* @return bool True if any of the children of this post are unread
*/
public function has_unread_child() {
$this->require_children();
foreach ($this->children as $child) {
if ($child->is_unread()) {
return true;
}
}
return false;
}
/**
* Checks if this post has any children (replies).
* @return bool True if post has one or more replies
*/
public function has_children() {
$this->require_children();
return count($this->children) > 0;
}
/**
* Marks this post as being expanded from the start.
*/
public function force_expand() {
$this->forceexpand = true;
}
/** @return bool True if this is the first post of a discussion */
public function is_root_post() {
return $this->postfields->parentpostid ? false : true;
}
/**
* @throws mod_forumng_exception If rating information wasn't queried
*/
private function check_ratings() {
if (!property_exists($this->postfields, 'averagerating')) {
throw new coding_exception('Rating information not retrieved');
}
}
/**
* @param bool $astext If true, returns a string rather than a number
* @return mixed Average rating as float, or a string description if
* $astext is true
* @throws mod_forumng_exception If rating information wasn't queried
*/
public function get_average_rating($astext = false) {
$this->check_ratings();
if ($astext) {
$options = $this->get_forum()->get_rating_options();
$value = (int)round($this->postfields->averagerating);
if (array_key_exists($value, $options)) {
return $options[$value];
} else {
return '?'; // Can occur if rating scale is changed
}
} else {
return $this->postfields->averagerating;
}
}
/**
* @return int Number of ratings of this post (may be 0)
*/
public function get_num_ratings() {
$this->check_ratings();
return $this->postfields->numratings;
}
/**
* @return int Current user's rating of this post or null if none
* @throws mod_forumng_exception If rating information wasn't queried
*/
public function get_own_rating() {
$this->check_ratings();
return $this->postfields->ownrating;
}
/**
* @param array $out Array that receives list of this post and all
* children (including nested children) in order
*/
public function build_linear_children(&$out) {
$this->require_children();
$out[count($out)] = $this;
foreach ($this->children as $child) {
$child->build_linear_children($out);
}
}
/**
* Finds a child post (or this one) with the specified ID.
* @param int $id Post ID
* @param bool $toplevel True for initial request (makes it throw
* exception if not found)
* @return mod_forumng_post Child post
*/
public function find_child($id, $toplevel=true) {
if ($this->postfields->id == $id) {
return $this;
}
$this->require_children();
foreach ($this->children as $child) {
$result = $child->find_child($id, false);
if ($result) {
return $result;
}
}
if ($toplevel) {
throw new coding_exception("Child id $id not found");
}
return null;
}
/**
* Finds which child post (or this) has the most recent modified date.
* @param mod_forumng_post &$newest Newest post (must be null when calling)
*/
public function find_newest_child(&$newest) {
if (!$newest || $newest->get_modified() < $this->get_modified()) {
$newest = $this;
}
$this->require_children();
foreach ($this->children as $child) {
$child->find_newest_child($newest);
}
}
/**
* Adds the ID of all children (and this post itself) to a list.
* @param array &$list List of IDs
*/
public function list_child_ids(&$list) {
$list[] = $this->get_id();
$this->require_children();
foreach ($this->children as $child) {
$child->list_child_ids($list);
}
}
/**
* @return mod_forumng_post Next unread post or null if there are no more
*/
public function get_next_unread() {
$this->require_children();
return $this->nextunread;
}
/**
* @return mod_forumng_post Previous unread post or null if there are no more
*/
public function get_previous_unread() {
$this->require_children();
return $this->previousunread;
}
/**
* Used by discussion to set up the unread posts.
* @param mod_forumng_post $nextunread
* @param mod_forumng_post $previousunread
*/
public function set_unread_list($nextunread, $previousunread) {
$this->nextunread = $nextunread;
$this->previousunread = $previousunread;
}
/** @return int forum ratings enabled */
public function get_ratings() {
return isset($this->postfields->rating) ? $this->postfields->rating : null;
}
// Factory method
/*///////////////*/
/**
* Creates a forum post object, forum object, and all related data from a
* single forum post ID. Intended when entering a page which uses post ID
* as a parameter.
* @param int $id ID of forum post
* @param int $cloneid If this is in a shared forum, must be the id of the
* clone forum currently in use, or CLONE_DIRECT; otherwise must be 0
* @param bool $wholediscussion If true, retrieves entire discussion
* instead of just this single post
* @param bool $usecache True to use cache when retrieving the discussion
* @param int $userid User ID to get post on behalf of (controls flag data
* retrieved)
* @param int $allowmissing Allow missing post or not, if not throw exception
* @return mod_forumng_post|boolean Post object
*/
public static function get_from_id($id, $cloneid,
$wholediscussion=false, $usecache=false, $userid=0, $allowmissing = false) {
global $CFG, $USER;
require_once($CFG->dirroot . '/rating/lib.php');
if ($wholediscussion) {
$discussion = mod_forumng_discussion::get_from_post_id($id, $cloneid,
$usecache, $usecache);
$root = $discussion->get_root_post();
return $root->find_child($id);
} else {
// Get post data (including extra data such as ratings and flags)
$records = self::query_posts('fp.id = ?', array($id), 'fp.id', true,
true, false, $userid);
if (count($records)!=1) {
if ($allowmissing === true) {
return false;
}
throw new coding_exception("Invalid post ID $id");
}
$postfields = reset($records);
$discussion = mod_forumng_discussion::get_from_id($postfields->discussionid, $cloneid);
// Load standard ratings.
$forum = $discussion->get_forum();
if ($forum->get_enableratings() == mod_forumng::FORUMNG_STANDARD_RATING) {
// If grading is 'No grading' or 'Teacher grades students'.
if ($forum->get_grading() == mod_forumng::GRADING_NONE ||
$forum->get_grading() == mod_forumng::GRADING_MANUAL) {
// Set the aggregation method.
if ($forum->get_rating_scale() > 0) {
$aggregate = RATING_AGGREGATE_AVERAGE;
} else {
$aggregate = RATING_AGGREGATE_COUNT;
}
} else {
$aggregate = $forum->get_grading();
}
$ratingoptions = new stdClass();
$ratingoptions->context = $forum->get_context(true);
$ratingoptions->component = 'mod_forumng';
$ratingoptions->ratingarea = 'post';
$ratingoptions->items = array('post' => $postfields);
$ratingoptions->aggregate = $aggregate;
$ratingoptions->scaleid = $forum->get_rating_scale();
$ratingoptions->userid = $USER->id;
$ratingoptions->id = $id;
$ratingoptions->assesstimestart = $forum->get_ratingfrom();
$ratingoptions->assesstimefinish = $forum->get_ratinguntil();
$ratingoptions->returnurl = $discussion->get_moodle_url();
$rm = new rating_manager();
$postwithratings = $rm->get_ratings($ratingoptions);
$postfields = $postwithratings['post'];// Update 'post' object.
}
$newpost = new mod_forumng_post($discussion, $postfields);
return $newpost;
}
}
// Object methods
/*///////////////*/
/**
* @param mod_forumng_discussion $discussion Discussion object
* @param object $postfields Post fields from DB table (may also include
* some extra fields provided by mod_forumng_post::query_posts)
* @param mod_forumng_post $parentpost Parent post or null if this is root post,
* or PARENT_NOT_LOADED if not available
*/
public function __construct($discussion, $postfields, $parentpost=self::PARENT_NOT_LOADED) {
$this->discussion = $discussion;
$this->postfields = $postfields;
// Extract the user details into Moodle user-like objects
if (property_exists($postfields, 'u_id')) {
$postfields->user = mod_forumng_utils::extract_subobject($postfields, 'u_');
$postfields->edituser = mod_forumng_utils::extract_subobject($postfields, 'eu_');
$postfields->deleteuser = mod_forumng_utils::extract_subobject($postfields, 'du_');
}
$this->parentpost = $parentpost;
$this->children = false;
}
/**
* Used to inform the post that all its children will be supplied.
* Call before calling add_child(), or even if there are no children.
*/
public function init_children() {
$this->children = array();
}
/**
* For internal use only. Adds a child to this post while constructing
* the tree of posts
* @param mod_forumng_post $child Child post
*/
public function add_child($child) {
$this->require_children();
$this->children[] = $child;
}
/**
* Checks that children are available.
* @throws mod_forumng_exception If children have not been loaded
*/
public function require_children() {
if (!is_array($this->children)) {
throw new coding_exception('Requires child post data');
}
}
/**
* Internal function. Queries for posts.
* @param string $where Where clause (fp is alias for post table)
* @param array $whereparams Parameters (values for ? parameters) in where clause
* @param string $order Sort order; the default is fp.id - note this is preferable
* to fp.timecreated because it works correctly if there are two posts in
* the same second
* @param bool $ratings True if ratings should be included in the query
* @param bool $flags True if flags should be included in the query
* @param bool $effectivesubjects True if the query should include the
* (complicated!) logic to obtain the 'effective subject'. This may result
* in additional queries afterward for posts which are very deeply nested.
* @param int $userid 0 = current user (at present this is only used for
* flags)
* @param bool $read True if read post record (time) is sought
* @return array Resulting posts as array of Moodle records, empty array
* if none
*/
public static function query_posts($where, $whereparams, $order='fp.id', $ratings=true,
$flags=false, $effectivesubjects=false,
$userid=0, $joindiscussion=false, $discussionsubject=false, $limitfrom='',
$limitnum='', $read = false) {
global $DB, $USER;
$userid = mod_forumng_utils::get_real_userid($userid);
$queryparams = array();
// We include ratings if these are enabled, otherwise save the database
// some effort and don't bother
if ($ratings) {
$ratingsquery = ",
(SELECT AVG(rating) FROM {forumng_ratings}
WHERE postid = fp.id) AS averagerating,
(SELECT COUNT(1) FROM {forumng_ratings}
WHERE postid = fp.id) AS numratings,
(SELECT rating FROM {forumng_ratings}
WHERE postid = fp.id AND userid = ?) AS ownrating";
// Add parameter to start of params list
$queryparams[] = $USER->id;
} else {
$ratingsquery = '';
}
if ($flags) {
$flagsjoin = "
LEFT JOIN {forumng_flags} ff ON ff.postid = fp.id AND ff.userid = ?";
$flagsquery = ", ff.flagged";
$queryparams[] = $userid;
} else {
$flagsjoin = '';
$flagsquery = '';
}
if ($joindiscussion) {
$discussionjoin = "
INNER JOIN {forumng_discussions} fd ON fp.discussionid = fd.id";
$discussionquery = ',' . mod_forumng_utils::select_discussion_fields('fd');
if ($discussionsubject) {
$discussionjoin .= "
INNER JOIN {forumng_posts} fdfp ON fd.postid = fdfp.id";
$discussionquery .= ', fdfp.subject AS fd_subject';
}
} else {
$discussionjoin = '';
$discussionquery = '';
}
if ($effectivesubjects) {
$maxdepth = self::PARENTPOST_DEPTH_PER_QUERY;
$subjectsjoin = '';
$subjectsquery = ", p$maxdepth.parentpostid AS nextparent ";
for ($depth = 2; $depth <= $maxdepth; $depth++) {
$subjectsquery .= ", p$depth.subject AS s$depth, p$depth.deleted AS d$depth";
$prev = 'p'. ($depth - 1);
if ($prev == 'p1') {
$prev = 'fp';
}
$subjectsjoin .= "LEFT JOIN {forumng_posts} p$depth
ON p$depth.id = $prev.parentpostid ";
}
} else {
$subjectsjoin = '';
$subjectsquery = '';
}
if ($read) {
$readquery = ', fr.time AS uread';
$readjoin = "LEFT JOIN {forumng_read_posts} fr ON fr.postid = fp.id AND fr.userid = ?";
$queryparams[] = $userid;
} else {
$readquery = '';
$readjoin = '';
}
// Retrieve posts from discussion with incorporated user information
// and ratings info if specified
$results = $DB->get_records_sql("
SELECT
fp.*,
".mod_forumng_utils::select_username_fields('u', true).",
".mod_forumng_utils::select_username_fields('eu').",
".mod_forumng_utils::select_username_fields('du')."
$ratingsquery
$flagsquery
$subjectsquery
$discussionquery
$readquery
FROM
{forumng_posts} fp
INNER JOIN {user} u ON fp.userid = u.id
LEFT JOIN {user} eu ON fp.edituserid = eu.id
LEFT JOIN {user} du ON fp.deleteuserid = du.id
$discussionjoin
$flagsjoin
$subjectsjoin
$readjoin
WHERE
$where
ORDER BY
$order
", array_merge($queryparams, $whereparams), $limitfrom, $limitnum);
if ($effectivesubjects) {
// Figure out the effective subject for each result
foreach ($results as $result) {
$got = false;
if ($result->subject !== null) {
$result->effectivesubject = $result->subject;
$got = true;
continue;
}
for ($depth = 2; $depth <= $maxdepth; $depth++) {
$var = "s$depth";
$var2 = "d$depth";
if (!$got && $result->{$var} !== null && $result->{$var2}==0) {
$result->effectivesubject = get_string('re', 'forumng', $result->{$var});
$got = true;
}
unset($result->{$var});
unset($result->{$var2});
}
if (!$got) {
// Do extra queries to pick up subjects for posts where it
// was unknown within the default depth. We can use the
// 'nextparent' to get the ID of the parent post of the last
// one that we checked already
$result->effectivesubject = self::inner_get_recursive_subject(
$result->nextparent);
}
}
}
return $results;
}
/**
* Replies to the post
* @param string $subject Subject
* @param string $message Message
* @param int $messageformat Moodle format used for message
* @param bool $attachments True if post contains attachments
* @param bool $setimportant If true, highlight the post
* @param bool $mailnow If true, sends mail ASAP
* @param int $userid User ID (0 = current)