xref: /plugin/bez/mdl/Thread.php (revision 9110c699cd10c9d460631d1a8b877de9c84f63ec)
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        $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET private=? WHERE id=?", $private, $this->id);
179
180    }
181
182	public function update_last_activity() {
183        $this->last_activity_date = date('c');
184        $this->model->sqlite->query('UPDATE thread SET last_activity_date=? WHERE id=?',
185                                    $this->last_activity_date, $this->id);
186    }
187
188    public function get_participants($filter='') {
189        if ($this->id === NULL) {
190            return array();
191        }
192
193        $sql = 'SELECT * FROM thread_participant WHERE';
194        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
195        if ($filter != '') {
196            if (!in_array($filter, $possible_flags)) {
197                throw new \Exception("unknown flag $filter");
198            }
199            $sql .= " $filter=1 AND";
200        }
201        $sql .= ' thread_id=? AND removed=0 ORDER BY user_id';
202
203        $r = $this->model->sqlite->query($sql, $this->id);
204        $pars = $this->model->sqlite->res2arr($r);
205        $participants = array();
206        foreach ($pars as $par) {
207            $participants[$par['user_id']] = $par;
208        }
209
210        return $participants;
211    }
212
213    public function get_participant($user_id, $can_be_removed=false) {
214        if ($this->id === NULL) {
215            return array();
216        }
217
218        $q = 'SELECT * FROM thread_participant WHERE thread_id=? AND user_id=?';
219        if (!$can_be_removed) {
220            $q .= ' AND removed=0';
221        }
222        $r = $this->model->sqlite->query($q, $this->id, $user_id);
223        $par = $this->model->sqlite->res2row($r);
224        if (!is_array($par)) {
225            return false;
226        }
227
228        return $par;
229    }
230
231    public function is_subscribent($user_id=null) {
232        if ($user_id == null) {
233            $user_id = $this->model->user_nick;
234        }
235        $par = $this->get_participant($user_id);
236        if ($par['subscribent'] == 1) {
237            return true;
238        }
239        return false;
240    }
241
242    public function remove_participant_flags($user_id, $flags) {
243        //thread not saved yet
244        if ($this->id === NULL) {
245            throw new \Exception('cannot remove flags from not saved thread');
246        }
247
248        $participant = $this->get_participant($user_id, true);
249        if ($participant === false) {
250            throw new ConsistencyViolationException("$user_id isn't participant");
251        }
252
253        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
254        if (array_intersect($flags, $possible_flags) != $flags) {
255            throw new \Exception('unknown flags');
256        }
257
258        $set = implode(',', array_map(function ($v) { return "$v=0"; }, $flags));
259
260        $sql = "UPDATE thread_participant SET $set WHERE thread_id=? AND user_id=?";
261        $this->model->sqlite->query($sql, $this->id, $user_id);
262
263    }
264
265	public function set_participant_flags($user_id, $flags=array()) {
266        //thread not saved yet
267        if ($this->id === NULL) {
268            throw new \Exception('cannot add flags to not saved thread');
269        }
270
271        //validate user
272        if (!$this->model->userFactory->exists($user_id)) {
273            throw new \Exception("$user_id isn't dokuwiki user");
274        }
275
276        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
277        if (array_intersect($flags, $possible_flags) != $flags) {
278            throw new \Exception('unknown flags');
279        }
280
281        $participant = $this->get_participant($user_id, true);
282        if ($participant == false) {
283            $participant = array_fill_keys($possible_flags, 0);
284
285            $participant['thread_id'] = $this->id;
286            $participant['user_id'] = $user_id;
287            $participant['added_by'] = $this->model->user_nick;
288            $participant['added_date'] = date('c');
289
290            $values = array_merge($participant, array_fill_keys($flags, 1));
291
292            $this->model->sqlite->storeEntry('thread_participant', $values);
293        } else {
294            $set = implode(',', array_map(function($flag) { return "$flag=1"; }, $flags));
295
296            if ($participant['removed'] == '1') {
297                $set .= ',removed=0';
298            }
299
300            $q = "UPDATE thread_participant SET $set WHERE thread_id=? AND user_id=?";
301            $this->model->sqlite->query($q, $this->id, $user_id);
302        }
303
304	}
305
306	public function remove_participant($user_id) {
307        //thread not saved yet
308        if ($this->id === NULL) {
309            throw new \Exception('cannot remove flags from not saved thread');
310        }
311
312        $participant = $this->get_participant($user_id);
313        if ($participant === false) {
314            throw new ConsistencyViolationException("$user_id isn't participant");
315        }
316
317        if ($participant['coordinator'] == '1') {
318            throw new ConsistencyViolationException("cannot remove coordinator");
319        }
320
321        if ($participant['task_assignee'] == '1') {
322            throw new ConsistencyViolationException("cannot remove task_assignee");
323        }
324
325        $q = "UPDATE thread_participant SET removed=1 WHERE thread_id=? AND user_id=?";
326        $this->model->sqlite->query($q, $this->id, $user_id);
327
328    }
329
330    public function invite($client) {
331        $this->set_participant_flags($client, array('subscribent'));
332        $this->mail_notify_invite($client);
333    }
334
335    public function get_labels() {
336        //record not saved
337        if ($this->id === NULL) {
338           return array();
339        }
340
341        $labels = array();
342        $r = $this->model->sqlite->query('SELECT * FROM label JOIN thread_label ON label.id = thread_label.label_id
343                                            WHERE thread_label.thread_id=?', $this->id);
344        $arr = $this->model->sqlite->res2arr($r);
345        foreach ($arr as $label) {
346            $labels[$label['id']] = $label;
347        }
348
349        return $labels;
350    }
351
352    public function add_label($label_id) {
353         //issue not saved yet
354        if ($this->id === NULL) {
355            throw new \Exception('cannot add labels to not saved thread. use initial_save() instead');
356        }
357
358        $r = $this->model->sqlite->query('SELECT id FROM label WHERE id=?', $label_id);
359        $label_id = $this->model->sqlite->res2single($r);
360        if (!$label_id) {
361            throw new \Exception("label($label_id) doesn't exist");
362        }
363
364
365        $this->model->sqlite->storeEntry('thread_label',
366                                         array('thread_id' => $this->id,
367                                               'label_id' => $label_id));
368
369    }
370
371    public function remove_label($label_id) {
372        //issue not saved yet
373        if ($this->id === NULL) {
374            throw new \Exception('cannot remove labels from not saved thread. use initial_save() instead');
375        }
376
377        /** @var \PDOStatement $r */
378        $r = $this->model->sqlite->query('DELETE FROM thread_label WHERE thread_id=? AND label_id=?',$this->id, $label_id);
379        if ($r->rowCount() != 1) {
380            throw new \Exception('label was not assigned to this thread');
381        }
382
383    }
384
385    public function get_causes() {
386        $r = $this->model->sqlite->query("SELECT id FROM thread_comment WHERE type LIKE 'cause_%' AND thread_id=?",
387                                         $this->id);
388        $arr = $this->model->sqlite->res2arr($r);
389        $causes = array();
390        foreach ($arr as $cause) {
391            $causes[] = $cause['id'];
392        }
393
394        return $causes;
395    }
396
397    public function can_add_comments() {
398        return in_array($this->state, array('proposal', 'opened', 'done'));
399    }
400
401    public function can_add_causes() {
402        return $this->type == 'issue' && in_array($this->state, array('opened', 'done'));
403    }
404
405    public function can_add_tasks() {
406        return in_array($this->state, array('opened', 'done'));
407    }
408
409    public function can_add_participants() {
410        return in_array($this->state, array('opened', 'done'));
411    }
412
413    public function can_be_closed() {
414        $res = $this->model->sqlite->query("SELECT thread_comment.id FROM thread_comment
415                               LEFT JOIN task ON thread_comment.id = task.thread_comment_id
416                               WHERE thread_comment.thread_id = ? AND
417                                     thread_comment.type LIKE 'cause_%' AND task.id IS NULL", $this->id);
418
419        $causes_without_tasks = $this->model->sqlite->res2row($res) ? true : false;
420        return $this->state == 'done' &&
421            ! $causes_without_tasks;
422
423    }
424
425    public function can_be_rejected() {
426        return $this->state != 'rejected' && $this->task_count == 0;
427    }
428
429    public function can_be_reopened() {
430        return in_array($this->state, array('closed', 'rejected'));
431    }
432
433    public function closing_comment() {
434        $r = $this->model->thread_commentFactory->get_from_thread($this, array(), 'id DESC', 1);
435        $thread_comment = $r->fetch();
436
437        return $thread_comment->content_html;
438    }
439
440    //http://data.agaric.com/capture-all-sent-mail-locally-postfix
441    //https://askubuntu.com/questions/192572/how-do-i-read-local-email-in-thunderbird
442    public function mail_notify($content, $users=false, $attachedImages=array()) {
443        $mailer = new \Mailer();
444        $mailer->setBody($content, array(), array(), $content, false);
445
446        if ($users == FALSE) {
447            $users = $this->get_participants('subscribent');
448
449            //don't notify myself
450            unset($users[$this->model->user_nick]);
451        }
452
453        $emails = array_map(function($user) {
454            if (is_array($user)) {
455                $user = $user['user_id'];
456            }
457            return $this->model->userFactory->get_user_email($user);
458        }, $users);
459
460
461        $mailer->to($emails);
462        $mailer->subject('#'.$this->id. ' ' .$this->title);
463
464        foreach ($attachedImages as $img) {
465            $mailer->attachFile($img['path'], $img['mime'], $img['name'], $img['embed']);
466        }
467
468        $send = $mailer->send();
469        if ($send === false) {
470            //this may mean empty $emails
471            //throw new Exception("can't send email");
472        }
473    }
474
475    public function mail_thread_box(&$attachedImages) {
476        $tpl = $this->model->action->get_tpl();
477
478        //render style
479        $less = new \lessc();
480        $less->addImportDir(DOKU_PLUGIN . 'bez/style/');
481        $style = $less->compileFile(DOKU_PLUGIN . 'bez/style/thread.less');
482
483        //render content for mail
484        $old_content_html = $this->content_html;
485        $this->content_html = p_render('bez_xhtmlmail', p_get_instructions($this->content), $info);
486        $attachedImages = array_merge($attachedImages, $info['img']);
487
488        $tpl->set('thread', $this);
489        $tpl->set('style', $style);
490        $tpl->set('no_actions', true);
491        $thread_box = $this->model->action->bez_tpl_include('thread_box', true);
492
493        $this->content_html = $old_content_html;
494
495        return $thread_box;
496    }
497
498    public function mail_thread(&$attachedImages) {
499        $tpl = $this->model->action->get_tpl();
500
501        $thread_box = $this->mail_thread_box($attachedImages);
502
503        $tpl->set('content', $thread_box);
504        $content = $this->model->action->bez_tpl_include('mail/thread', true);
505
506        return $content;
507    }
508
509    public function mail_notify_change_state($action='') {
510        if (!$action) {
511            $action = 'mail_mail_notify_change_state_action';
512        }
513        $tpl = $this->model->action->get_tpl();
514
515        $tpl->set('who', $this->model->user_nick);
516        $tpl->set('action', $action);
517        $attachedImages = array();
518        $content = $this->mail_thread($attachedImages);
519        $this->mail_notify($content, false, $attachedImages);
520    }
521
522    public function mail_notify_invite($client) {
523        $tpl = $this->model->action->get_tpl();
524
525        $tpl->set('who', $this->model->user_nick);
526        $tpl->set('action', 'mail_mail_notify_invite_action');
527        $attachedImages = array();
528        $content = $this->mail_thread($attachedImages);
529        $this->mail_notify($content, array($client), $attachedImages);
530    }
531
532    public function mail_inform_coordinator() {
533        $tpl = $this->model->action->get_tpl();
534
535        $tpl->set('who', $this->model->user_nick);
536        $tpl->set('action', 'mail_mail_inform_coordinator_action');
537        $attachedImages = array();
538        $content = $this->mail_thread($attachedImages);
539        $this->mail_notify($content, array($this->coordinator), $attachedImages);
540    }
541
542    public function mail_inform_admins() {
543        $tpl = $this->model->action->get_tpl();
544
545        $tpl->set('who', $this->model->user_nick);
546        $tpl->set('action', 'mail_mail_inform_admins_action');
547        $attachedImages = array();
548        $content = $this->mail_thread($attachedImages);
549        $this->mail_notify($content, $this->model->userFactory->users_of_group(array('admin', 'bez_admin')), $attachedImages);
550    }
551
552    public function mail_notify_inactive($users=false) {
553        $tpl = $this->model->action->get_tpl();
554
555        $tpl->set('who', $this->model->user_nick);
556        $tpl->set('action', 'mail_mail_notify_issue_inactive');
557        $attachedImages = array();
558        $content = $this->mail_thread($attachedImages);
559        $this->mail_notify($content, $users, $attachedImages);
560    }
561
562    public function mail_notify_task_added(Task $task) {
563        $tpl = $this->model->action->get_tpl();
564
565        //we don't want who
566        $tpl->set('who', $this->model->user_nick);
567        $tpl->set('action', 'mail_thread_task_added');
568        $attachedImages = array();
569        $task_box = $task->mail_task_box($attachedImages);
570
571        $tpl->set('thread', $this);
572        $tpl->set('content', $task_box);
573        $content = $this->model->action->bez_tpl_include('mail/thread', true);
574
575        $this->mail_notify($content, false, $attachedImages);
576    }
577
578    public function mail_notify_task_state_changed(Task $task) {
579        $tpl = $this->model->action->get_tpl();
580
581        if ($task->state == 'done') {
582            $action = 'mail_thread_task_done';
583        } else {
584            $action = 'mail_thread_task_reopened';
585        }
586
587        //we don't want who
588        $tpl->set('who', $this->model->user_nick);
589        $tpl->set('action', $action);
590        $attachedImages = array();
591        $task_box = $task->mail_task_box($attachedImages);
592
593        $tpl->set('thread', $this);
594        $tpl->set('content', $task_box);
595        $content = $this->model->action->bez_tpl_include('mail/thread', true);
596
597        $this->mail_notify($content, false, $attachedImages);
598    }
599
600}
601