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