xref: /plugin/bez/mdl/Thread.php (revision 3be16e0fcfd6542977ea03d1d93826140a52d61e)
1<?php
2
3namespace dokuwiki\plugin\bez\mdl;
4
5use dokuwiki\plugin\bez\meta\ConsistencyViolationException;
6use dokuwiki\plugin\bez\meta\PermissionDeniedException;
7use dokuwiki\plugin\bez\meta\ValidationException;
8
9class Thread extends Entity {
10
11    protected $id;
12
13    protected $original_poster, $coordinator, $closed_by;
14
15    protected $private, $lock;
16
17    protected $type, $state;
18
19    protected $create_date, $last_activity_date, $last_modification_date, $close_date;
20
21    protected $title, $content, $content_html;
22
23    protected $task_count, $task_count_closed, $task_sum_cost;
24
25    public static function get_columns() {
26        return array('id',
27                     'original_poster', 'coordinator', 'closed_by',
28                     'private', 'lock',
29                     'type', 'state',
30                     'create_date', 'last_activity_date', 'last_modification_date', 'close_date',
31                     'title', 'content', 'content_html',
32                     'task_count', 'task_count_closed', 'task_sum_cost');
33    }
34
35    public static function get_select_columns() {
36        $cols = parent::get_select_columns();
37        array_push($cols, 'label_id', 'label_name');
38        return $cols;
39    }
40
41    public static function get_states() {
42        return array('proposal', 'opened', 'done', 'closed', 'rejected');
43    }
44
45    public function __get($property) {
46        if($property == 'priority') {
47            return $this->$property;
48        }
49        return parent::__get($property);
50    }
51
52    public function user_is_coordinator() {
53        if ($this->coordinator === $this->model->user_nick ||
54           $this->model->get_level() >= BEZ_AUTH_ADMIN) {
55            return true;
56        }
57    }
58
59	public function __construct($model, $defaults=array()) {
60		parent::__construct($model);
61
62        $this->validator->set_rules(array(
63            'coordinator' => array(array('dw_user'), 'NULL'),
64            'title' => array(array('length', 200), 'NOT NULL'),
65            'content' => array(array('length', 10000), 'NOT NULL'),
66            'type' => array(array('select', array('issue', 'project')), 'NULL')
67        ));
68
69		//we've created empty object (new record)
70		if ($this->id === NULL) {
71			$this->original_poster = $this->model->user_nick;
72			$this->create_date = date('c');
73			$this->last_activity_date = $this->create_date;
74            $this->last_modification_date = $this->create_date;
75
76			$this->state = 'proposal';
77
78			$this->acl->grant('title', BEZ_PERMISSION_CHANGE);
79            $this->acl->grant('content', BEZ_PERMISSION_CHANGE);
80            $this->acl->grant('type', BEZ_PERMISSION_CHANGE);
81
82
83            if ($this->model->get_level() >= BEZ_AUTH_LEADER) {
84
85                $this->state = 'opened';
86
87                $this->acl->grant('coordinator', BEZ_PERMISSION_CHANGE);
88                $this->acl->grant('label_id', BEZ_PERMISSION_CHANGE);
89                $this->acl->grant('private', BEZ_PERMISSION_CHANGE);
90            }
91
92		} else {
93            //private threads
94            if ($this->model->level < BEZ_AUTH_ADMIN && $this->private == '1') {
95                if ($this->get_participant($this->model->user_nick) === false) {
96                    $this->acl->revoke(self::get_select_columns(), BEZ_AUTH_LEADER);
97                    return;
98                }
99            }
100
101		    if ($this->state == 'proposal' && $this->original_poster == $this->model->user_nick) {
102                $this->acl->grant('title', BEZ_PERMISSION_CHANGE);
103                $this->acl->grant('content', BEZ_PERMISSION_CHANGE);
104                $this->acl->grant('type', BEZ_PERMISSION_CHANGE);
105            }
106
107            if ($this->coordinator == $this->model->user_nick) {
108                $this->acl->grant('title', BEZ_PERMISSION_CHANGE);
109                $this->acl->grant('content', BEZ_PERMISSION_CHANGE);
110                $this->acl->grant('coordinator', BEZ_PERMISSION_CHANGE);
111                $this->acl->grant('label_id', BEZ_PERMISSION_CHANGE);
112                $this->acl->grant('private', BEZ_PERMISSION_CHANGE);
113
114                $this->acl->grant('state', BEZ_PERMISSION_CHANGE);
115                $this->acl->grant('type', BEZ_PERMISSION_CHANGE);
116            }
117        }
118	}
119
120	public function set_data($data, $filter=NULL) {
121        parent::set_data($data, $filter=NULL);
122
123        if (isset($data['coordinator']) && $this->state == 'proposal') {
124            $this->state = 'opened';
125        }
126
127		$this->content_html = p_render('xhtml',p_get_instructions($this->content), $ignore);
128
129        //update dates
130        $this->last_modification_date = date('c');
131        $this->last_activity_date = $this->last_modification_date;
132    }
133
134    public function set_state($state) {
135        if ($this->acl_of('state') < BEZ_PERMISSION_CHANGE) {
136            throw new PermissionDeniedException();
137        }
138
139        if (!in_array($state, array('opened', 'closed', 'rejected'))) {
140            throw new ValidationException('thread', array('state should be opened, closed or rejected'));
141        }
142
143        //nothing to do
144        if ($state == $this->state) {
145            return;
146        }
147
148        if ($state == 'closed' || $state == 'rejected') {
149            $this->state = $state;
150            $this->closed_by = $this->model->user_nick;
151            $this->close_date = date('c');
152
153            $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET state=?, closed_by=?, close_date=? WHERE id=?",
154                $state,
155                $this->closed_by,
156                $this->close_date,
157                $this->id);
158            //reopen the task
159        } else {
160            $this->state = $state;
161
162            $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET state=? WHERE id=?", $state, $this->id);
163        }
164
165        $this->state = $state;
166    }
167
168    public function set_private_flag($flag) {
169        $private = '0';
170        if ($flag) {
171            $private = '1';
172        }
173
174        if ($private == $this->private) {
175            return;
176        }
177
178        //update thread
179        $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET private=? WHERE id=?", $private, $this->id);
180
181        //update task
182        $this->model->sqlite->query("UPDATE task SET private=? WHERE thread_id=?", $private, $this->id);
183    }
184
185	public function update_last_activity() {
186        $this->last_activity_date = date('c');
187        $this->model->sqlite->query('UPDATE thread SET last_activity_date=? WHERE id=?',
188                                    $this->last_activity_date, $this->id);
189    }
190
191    public function get_participants($filter='') {
192        if ($this->id === NULL) {
193            return array();
194        }
195
196        $sql = 'SELECT * FROM thread_participant WHERE';
197        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
198        if ($filter != '') {
199            if (!in_array($filter, $possible_flags)) {
200                throw new \Exception("unknown flag $filter");
201            }
202            $sql .= " $filter=1 AND";
203        }
204        $sql .= ' thread_id=? AND removed=0 ORDER BY user_id';
205
206        $r = $this->model->sqlite->query($sql, $this->id);
207        $pars = $this->model->sqlite->res2arr($r);
208        $participants = array();
209        foreach ($pars as $par) {
210            $participants[$par['user_id']] = $par;
211        }
212
213        return $participants;
214    }
215
216    public function get_participant($user_id, $can_be_removed=false) {
217        if ($this->id === NULL) {
218            return array();
219        }
220
221        $q = 'SELECT * FROM thread_participant WHERE thread_id=? AND user_id=?';
222        if (!$can_be_removed) {
223            $q .= ' AND removed=0';
224        }
225        $r = $this->model->sqlite->query($q, $this->id, $user_id);
226        $par = $this->model->sqlite->res2row($r);
227        if (!is_array($par)) {
228            return false;
229        }
230
231        return $par;
232    }
233
234    public function is_subscribent($user_id=null) {
235        if ($user_id == null) {
236            $user_id = $this->model->user_nick;
237        }
238        $par = $this->get_participant($user_id);
239        if ($par['subscribent'] == 1) {
240            return true;
241        }
242        return false;
243    }
244
245    public function remove_participant_flags($user_id, $flags) {
246        //thread not saved yet
247        if ($this->id === NULL) {
248            throw new \Exception('cannot remove flags from not saved thread');
249        }
250
251        $participant = $this->get_participant($user_id, true);
252        if ($participant === false) {
253            throw new ConsistencyViolationException("$user_id isn't participant");
254        }
255
256        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
257        if (array_intersect($flags, $possible_flags) != $flags) {
258            throw new \Exception('unknown flags');
259        }
260
261        $set = implode(',', array_map(function ($v) { return "$v=0"; }, $flags));
262
263        $sql = "UPDATE thread_participant SET $set WHERE thread_id=? AND user_id=?";
264        $this->model->sqlite->query($sql, $this->id, $user_id);
265
266    }
267
268	public function set_participant_flags($user_id, $flags=array()) {
269        //thread not saved yet
270        if ($this->id === NULL) {
271            throw new \Exception('cannot add flags to not saved thread');
272        }
273
274        //validate user
275        if (!$this->model->userFactory->exists($user_id)) {
276            throw new \Exception("$user_id isn't dokuwiki user");
277        }
278
279        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
280        if (array_intersect($flags, $possible_flags) != $flags) {
281            throw new \Exception('unknown flags');
282        }
283
284        $participant = $this->get_participant($user_id, true);
285        if ($participant == false) {
286            $participant = array_fill_keys($possible_flags, 0);
287
288            $participant['thread_id'] = $this->id;
289            $participant['user_id'] = $user_id;
290            $participant['added_by'] = $this->model->user_nick;
291            $participant['added_date'] = date('c');
292
293            $values = array_merge($participant, array_fill_keys($flags, 1));
294
295            $this->model->sqlite->storeEntry('thread_participant', $values);
296        } else {
297            $set = implode(',', array_map(function($flag) { return "$flag=1"; }, $flags));
298
299            if ($participant['removed'] == '1') {
300                $set .= ',removed=0';
301            }
302
303            $q = "UPDATE thread_participant SET $set WHERE thread_id=? AND user_id=?";
304            $this->model->sqlite->query($q, $this->id, $user_id);
305        }
306
307	}
308
309	public function remove_participant($user_id) {
310        //thread not saved yet
311        if ($this->id === NULL) {
312            throw new \Exception('cannot remove flags from not saved thread');
313        }
314
315        $participant = $this->get_participant($user_id);
316        if ($participant === false) {
317            throw new ConsistencyViolationException("$user_id isn't participant");
318        }
319
320        if ($participant['coordinator'] == '1') {
321            throw new ConsistencyViolationException("cannot remove coordinator");
322        }
323
324        if ($participant['task_assignee'] == '1') {
325            throw new ConsistencyViolationException("cannot remove task_assignee");
326        }
327
328        $q = "UPDATE thread_participant SET removed=1 WHERE thread_id=? AND user_id=?";
329        $this->model->sqlite->query($q, $this->id, $user_id);
330
331    }
332
333    public function invite($client) {
334        $this->set_participant_flags($client, array('subscribent'));
335        $this->mail_notify_invite($client);
336    }
337
338    public function get_labels() {
339        //record not saved
340        if ($this->id === NULL) {
341           return array();
342        }
343
344        $labels = array();
345        $r = $this->model->sqlite->query('SELECT * FROM label JOIN thread_label ON label.id = thread_label.label_id
346                                            WHERE thread_label.thread_id=?', $this->id);
347        $arr = $this->model->sqlite->res2arr($r);
348        foreach ($arr as $label) {
349            $labels[$label['id']] = $label;
350        }
351
352        return $labels;
353    }
354
355    public function add_label($label_id) {
356         //issue not saved yet
357        if ($this->id === NULL) {
358            throw new \Exception('cannot add labels to not saved thread. use initial_save() instead');
359        }
360
361        $r = $this->model->sqlite->query('SELECT id FROM label WHERE id=?', $label_id);
362        $label_id = $this->model->sqlite->res2single($r);
363        if (!$label_id) {
364            throw new \Exception("label($label_id) doesn't exist");
365        }
366
367
368        $this->model->sqlite->storeEntry('thread_label',
369                                         array('thread_id' => $this->id,
370                                               'label_id' => $label_id));
371
372    }
373
374    public function remove_label($label_id) {
375        //issue not saved yet
376        if ($this->id === NULL) {
377            throw new \Exception('cannot remove labels from not saved thread. use initial_save() instead');
378        }
379
380        /** @var \PDOStatement $r */
381        $r = $this->model->sqlite->query('DELETE FROM thread_label WHERE thread_id=? AND label_id=?',$this->id, $label_id);
382        if ($r->rowCount() != 1) {
383            throw new \Exception('label was not assigned to this thread');
384        }
385
386    }
387
388    public function get_causes() {
389        $r = $this->model->sqlite->query("SELECT id FROM thread_comment WHERE type LIKE 'cause_%' AND thread_id=?",
390                                         $this->id);
391        $arr = $this->model->sqlite->res2arr($r);
392        $causes = array();
393        foreach ($arr as $cause) {
394            $causes[] = $cause['id'];
395        }
396
397        return $causes;
398    }
399
400    public function can_add_comments() {
401        return in_array($this->state, array('proposal', 'opened', 'done'));
402    }
403
404    public function can_add_causes() {
405        return $this->type == 'issue' && in_array($this->state, array('opened', 'done'));
406    }
407
408    public function can_add_tasks() {
409        return in_array($this->state, array('opened', 'done'));
410    }
411
412    public function can_add_participants() {
413        return in_array($this->state, array('opened', 'done'));
414    }
415
416    public function can_be_closed() {
417        $res = $this->model->sqlite->query("SELECT thread_comment.id FROM thread_comment
418                               LEFT JOIN task ON thread_comment.id = task.thread_comment_id
419                               WHERE thread_comment.thread_id = ? AND
420                                     thread_comment.type LIKE 'cause_%' AND task.id IS NULL", $this->id);
421
422        $causes_without_tasks = $this->model->sqlite->res2row($res) ? true : false;
423        return $this->state == 'done' &&
424            ! $causes_without_tasks;
425
426    }
427
428    public function can_be_rejected() {
429        return $this->state != 'rejected' && $this->task_count == 0;
430    }
431
432    public function can_be_reopened() {
433        return in_array($this->state, array('closed', 'rejected'));
434    }
435
436    public function closing_comment() {
437        $r = $this->model->thread_commentFactory->get_from_thread($this, array(), 'id DESC', 1);
438        $thread_comment = $r->fetch();
439
440        return $thread_comment->content_html;
441    }
442
443    //http://data.agaric.com/capture-all-sent-mail-locally-postfix
444    //https://askubuntu.com/questions/192572/how-do-i-read-local-email-in-thunderbird
445    public function mail_notify($content, $users=false, $attachedImages=array()) {
446        $mailer = new \Mailer();
447        $mailer->setBody($content, array(), array(), $content, false);
448
449        if ($users == FALSE) {
450            $users = $this->get_participants('subscribent');
451
452            //don't notify myself
453            unset($users[$this->model->user_nick]);
454        }
455
456        $emails = array_map(function($user) {
457            if (is_array($user)) {
458                $user = $user['user_id'];
459            }
460            return $this->model->userFactory->get_user_email($user);
461        }, $users);
462
463
464        $mailer->to($emails);
465        $mailer->subject('#'.$this->id. ' ' .$this->title);
466
467        foreach ($attachedImages as $img) {
468            $mailer->attachFile($img['path'], $img['mime'], $img['name'], $img['embed']);
469        }
470
471        $send = $mailer->send();
472        if ($send === false) {
473            //this may mean empty $emails
474            //throw new Exception("can't send email");
475        }
476    }
477
478    public function mail_thread_box(&$attachedImages) {
479        $tpl = $this->model->action->get_tpl();
480
481        //render style
482        $less = new \lessc();
483        $less->addImportDir(DOKU_PLUGIN . 'bez/style/');
484        $style = $less->compileFile(DOKU_PLUGIN . 'bez/style/thread.less');
485
486        //render content for mail
487        $old_content_html = $this->content_html;
488        $this->content_html = p_render('bez_xhtmlmail', p_get_instructions($this->content), $info);
489        $attachedImages = array_merge($attachedImages, $info['img']);
490
491        $tpl->set('thread', $this);
492        $tpl->set('style', $style);
493        $tpl->set('no_actions', true);
494        $thread_box = $this->model->action->bez_tpl_include('thread_box', true);
495
496        $this->content_html = $old_content_html;
497
498        return $thread_box;
499    }
500
501    public function mail_thread(&$attachedImages) {
502        $tpl = $this->model->action->get_tpl();
503
504        $thread_box = $this->mail_thread_box($attachedImages);
505
506        $tpl->set('content', $thread_box);
507        $content = $this->model->action->bez_tpl_include('mail/thread', true);
508
509        return $content;
510    }
511
512    public function mail_notify_change_state($action='') {
513        if (!$action) {
514            $action = 'mail_mail_notify_change_state_action';
515        }
516        $tpl = $this->model->action->get_tpl();
517
518        $tpl->set('who', $this->model->user_nick);
519        $tpl->set('action', $action);
520        $attachedImages = array();
521        $content = $this->mail_thread($attachedImages);
522        $this->mail_notify($content, false, $attachedImages);
523    }
524
525    public function mail_notify_invite($client) {
526        $tpl = $this->model->action->get_tpl();
527
528        $tpl->set('who', $this->model->user_nick);
529        $tpl->set('action', 'mail_mail_notify_invite_action');
530        $attachedImages = array();
531        $content = $this->mail_thread($attachedImages);
532        $this->mail_notify($content, array($client), $attachedImages);
533    }
534
535    public function mail_inform_coordinator() {
536        $tpl = $this->model->action->get_tpl();
537
538        $tpl->set('who', $this->model->user_nick);
539        $tpl->set('action', 'mail_mail_inform_coordinator_action');
540        $attachedImages = array();
541        $content = $this->mail_thread($attachedImages);
542        $this->mail_notify($content, array($this->coordinator), $attachedImages);
543    }
544
545    public function mail_inform_admins() {
546        $tpl = $this->model->action->get_tpl();
547
548        $tpl->set('who', $this->model->user_nick);
549        $tpl->set('action', 'mail_mail_inform_admins_action');
550        $attachedImages = array();
551        $content = $this->mail_thread($attachedImages);
552        $this->mail_notify($content, $this->model->userFactory->users_of_group(array('admin', 'bez_admin')), $attachedImages);
553    }
554
555    public function mail_notify_inactive($users=false) {
556        $tpl = $this->model->action->get_tpl();
557
558        $tpl->set('who', $this->model->user_nick);
559        $tpl->set('action', 'mail_mail_notify_issue_inactive');
560        $attachedImages = array();
561        $content = $this->mail_thread($attachedImages);
562        $this->mail_notify($content, $users, $attachedImages);
563    }
564
565    public function mail_notify_task_added(Task $task) {
566        $tpl = $this->model->action->get_tpl();
567
568        //we don't want who
569        $tpl->set('who', $this->model->user_nick);
570        $tpl->set('action', 'mail_thread_task_added');
571        $attachedImages = array();
572        $task_box = $task->mail_task_box($attachedImages);
573
574        $tpl->set('thread', $this);
575        $tpl->set('content', $task_box);
576        $content = $this->model->action->bez_tpl_include('mail/thread', true);
577
578        $this->mail_notify($content, false, $attachedImages);
579    }
580
581    public function mail_notify_task_state_changed(Task $task) {
582        $tpl = $this->model->action->get_tpl();
583
584        if ($task->state == 'done') {
585            $action = 'mail_thread_task_done';
586        } else {
587            $action = 'mail_thread_task_reopened';
588        }
589
590        //we don't want who
591        $tpl->set('who', $this->model->user_nick);
592        $tpl->set('action', $action);
593        $attachedImages = array();
594        $task_box = $task->mail_task_box($attachedImages);
595
596        $tpl->set('thread', $this);
597        $tpl->set('content', $task_box);
598        $content = $this->model->action->bez_tpl_include('mail/thread', true);
599
600        $this->mail_notify($content, false, $attachedImages);
601    }
602
603}
604