xref: /plugin/bez/mdl/Thread.php (revision 16c7b168a60daa2c9b9ddcfa51e05d123a2a17dc)
1<?php
2
3namespace dokuwiki\plugin\bez\mdl;
4
5use dokuwiki\plugin\bez\meta\Mailer;
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 $priority;
24
25    protected $task_count, $task_count_closed, $task_sum_cost;
26
27    /*new labels to add when object saved*/
28    //protected $new_label_ids;
29    protected $labels;
30
31    public static function get_columns() {
32        return array('id',
33                     'original_poster', 'coordinator', 'closed_by',
34                     'private', 'lock',
35                     'type', 'state',
36                     'create_date', 'last_activity_date', 'last_modification_date', 'close_date',
37                     'title', 'content', 'content_html',
38                     'priority',
39                     'task_count', 'task_count_closed', 'task_sum_cost');
40    }
41
42    public static function get_select_columns() {
43        $cols = parent::get_select_columns();
44        array_push($cols, 'label_id', 'label_name');
45        return $cols;
46    }
47
48    public static function get_states() {
49        return array('proposal', 'opened', 'done', 'closed', 'rejected');
50    }
51
52    public function user_is_coordinator() {
53        if ($this->coordinator === $this->model->user_nick ||
54           $this->model->acl->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        ));
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
78            if ($this->model->acl->get_level() >= BEZ_AUTH_LEADER) {
79                if (!$this->model->userFactory->exists($defaults['coordinator'])) {
80                    throw new ValidationException('thread', array('coordinator' => 'is_null'));
81                }
82                $this->coordinator = $defaults['coordinator'];
83                $this->state = 'opened';
84            }
85		}
86	}
87
88	public function set_data($data, $filter=NULL) {
89        $input = array('title', 'content', 'coordinator');
90        $val_data = $this->validator->validate($data, $input);
91
92		if ($val_data === false) {
93			throw new ValidationException('thread',	$this->validator->get_errors());
94        }
95
96
97        //change coordinator at the end(!)
98        if (isset($val_data['coordinator'])) {
99            $val_coordinator = $val_data['coordinator'];
100            unset($val_data['coordinator']);
101        }
102
103        $this->set_property_array($val_data);
104
105        if (isset($val_coordinator)) {
106           $this->set_property('coordinator', $val_coordinator);
107        }
108
109		$this->content_html = p_render('xhtml',p_get_instructions($this->content), $ignore);
110
111        //update dates
112        $this->last_modification_date = date('c');
113        $this->last_activity_date = $this->last_modification_date;
114    }
115
116    public function set_state($state) {
117        if ($this->acl_of('state') < BEZ_PERMISSION_CHANGE) {
118            throw new PermissionDeniedException();
119        }
120
121        if (!in_array($state, array('opened', 'closed', 'rejected'))) {
122            throw new ValidationException('task', array('sholud be opened, closed or rejected'));
123        }
124
125        //nothing to do
126        if ($state == $this->state) {
127            return;
128        }
129
130        if ($state == 'closed' || $state == 'rejected') {
131            $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET state=?, closed_by=?, close_date=? WHERE id=?",
132                $state,
133                $this->model->user_nick,
134                date('c'),
135                $this->id);
136            //reopen the task
137        } else {
138            $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET state=? WHERE id=?", $state, $this->id);
139        }
140
141        $this->state = $state;
142    }
143
144	public function update_last_activity() {
145        $this->last_activity_date = date('c');
146        $this->model->sqlite->query('UPDATE thread SET last_activity_date=? WHERE id=?',
147                                    $this->last_activity_date, $this->id);
148    }
149
150    public function get_participants($filter='') {
151        if ($this->acl_of('participants') < BEZ_PERMISSION_VIEW) {
152            throw new PermissionDeniedException();
153        }
154        if ($this->id === NULL) {
155            return array();
156        }
157
158        $sql = 'SELECT * FROM thread_participant WHERE';
159        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
160        if ($filter != '') {
161            if (!in_array($filter, $possible_flags)) {
162                throw new \Exception("unknown flag $filter");
163            }
164            $sql .= " $filter=1 AND";
165        }
166        $sql .= ' thread_id=? ORDER BY user_id';
167
168        $r = $this->model->sqlite->query($sql, $this->id);
169        $pars = $this->model->sqlite->res2arr($r);
170        $participants = array();
171        foreach ($pars as $par) {
172            $participants[$par['user_id']] = $par;
173        }
174
175        return $participants;
176    }
177
178    public function get_participant($user_id) {
179        if ($this->acl_of('participants') < BEZ_PERMISSION_VIEW) {
180            throw new PermissionDeniedException();
181        }
182        if ($this->id === NULL) {
183            return array();
184        }
185
186        $r = $this->model->sqlite->query('SELECT * FROM thread_participant WHERE thread_id=? AND user_id=?', $this->id, $user_id);
187        $par = $this->model->sqlite->res2row($r);
188        if (!is_array($par)) {
189            return false;
190        }
191
192        return $par;
193    }
194
195    public function is_subscribent($user_id=null) {
196        if ($user_id == null) {
197            $user_id = $this->model->user_nick;
198        }
199        $par = $this->get_participant($user_id);
200        if ($par['subscribent'] == 1) {
201            return true;
202        }
203        return false;
204    }
205
206    public function remove_participant_flags($user_id, $flags) {
207        if ($this->acl_of('participants') < BEZ_PERMISSION_CHANGE) {
208            throw new PermissionDeniedException();
209        }
210
211        //thread not saved yet
212        if ($this->id === NULL) {
213            throw new \Exception('cannot remove flags from not saved thread');
214        }
215
216        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
217        if (array_intersect($flags, $possible_flags) != $flags) {
218            throw new \Exception('unknown flags');
219        }
220
221        $set = implode(',', array_map(function ($v) { return "$v=0"; }, $flags));
222
223        $sql = "UPDATE thread_participant SET $set WHERE thread_id=? AND user_id=?";
224        $this->model->sqlite->query($sql, $this->id, $user_id);
225
226    }
227
228	public function set_participant_flags($user_id, $flags=array()) {
229        if ($this->acl_of('participants') < BEZ_PERMISSION_CHANGE) {
230            throw new PermissionDeniedException();
231        }
232
233        //thread not saved yet
234        if ($this->id === NULL) {
235            throw new \Exception('cannot add flags to not saved thread');
236        }
237
238        //validate user
239        if (!$this->model->userFactory->exists($user_id)) {
240            throw new \Exception("$user_id isn't dokuwiki user");
241        }
242
243        $possible_flags = array('original_poster', 'coordinator', 'commentator', 'task_assignee', 'subscribent');
244        if (array_intersect($flags, $possible_flags) != $flags) {
245            throw new \Exception('unknown flags');
246        }
247
248        $participant = $this->get_participant($user_id);
249        if ($participant == false) {
250            $participant = array_fill_keys($possible_flags, 0);
251
252            $participant['thread_id'] = $this->id;
253            $participant['user_id'] = $user_id;
254            $participant['added_by'] = $this->model->user_nick;
255            $participant['added_date'] = date('c');
256        }
257        $values = array_merge($participant, array_fill_keys($flags, 1));
258
259        $keys = join(',', array_keys($values));
260        $vals = join(',', array_fill(0,count($values),'?'));
261
262        $sql = "REPLACE INTO thread_participant ($keys) VALUES ($vals)";
263        $this->model->sqlite->query($sql, array_values($values));
264	}
265
266
267    public function invite($client) {
268        $this->set_participant_flags($client, array('subscribent'));
269        $this->mail_notify_invite($client);
270    }
271
272    public function get_labels() {
273        if ($this->acl_of('labels') < BEZ_PERMISSION_VIEW) {
274            throw new PermissionDeniedException();
275        }
276
277        //record not saved
278        if ($this->id === NULL) {
279           return array();
280        }
281
282        $labels = array();
283        $r = $this->model->sqlite->query('SELECT * FROM label JOIN thread_label ON label.id = thread_label.label_id
284                                            WHERE thread_label.thread_id=?', $this->id);
285        $arr = $this->model->sqlite->res2arr($r);
286        foreach ($arr as $label) {
287            $labels[$label['id']] = $label;
288        }
289
290        return $labels;
291    }
292
293    public function add_label($label_id) {
294        if ($this->acl_of('labels') < BEZ_PERMISSION_CHANGE) {
295            throw new PermissionDeniedException();
296        }
297
298
299        //issue not saved yet
300        if ($this->id === NULL) {
301            throw new \Exception('cannot add labels to not saved thread. use initial_save() instead');
302        }
303
304        $r = $this->model->sqlite->query('SELECT id FROM label WHERE id=?', $label_id);
305        $label_id = $this->model->sqlite->res2single($r);
306        if (!$label_id) {
307            throw new \Exception("label($label_id) doesn't exist");
308        }
309
310
311        $this->model->sqlite->storeEntry('thread_label',
312                                         array('thread_id' => $this->id,
313                                               'label_id' => $label_id));
314
315    }
316
317    public function remove_label($label_id) {
318        if ($this->acl_of('labels') < BEZ_PERMISSION_CHANGE) {
319            throw new PermissionDeniedException();
320        }
321
322        //issue not saved yet
323        if ($this->id === NULL) {
324            throw new \Exception('cannot remove labels from not saved thread. use initial_save() instead');
325        }
326
327        /** @var \PDOStatement $r */
328        $r = $this->model->sqlite->query('DELETE FROM thread_label WHERE thread_id=? AND label_id=?',$this->id, $label_id);
329        if ($r->rowCount() != 1) {
330            throw new \Exception('label was not assigned to this thread');
331        }
332
333    }
334
335    public function get_causes() {
336        $r = $this->model->sqlite->query("SELECT id FROM thread_comment WHERE type LIKE 'cause_%' AND thread_id=?",
337                                         $this->id);
338        $arr = $this->model->sqlite->res2arr($r);
339        $causes = array();
340        foreach ($arr as $cause) {
341            $causes[] = $cause['id'];
342        }
343
344        return $causes;
345    }
346
347    public function can_be_closed() {
348        $res = $this->model->sqlite->query("SELECT thread_comment.id FROM thread_comment
349                               LEFT JOIN task ON thread_comment.id = task.thread_comment_id
350                               WHERE thread_comment.thread_id = ? AND
351                                     thread_comment.type LIKE 'cause_%' AND task.id IS NULL", $this->id);
352
353        $causes_without_tasks = $this->model->sqlite->res2row($res) ? true : false;
354        return $this->state == 'opened' &&
355            ($this->task_count - $this->task_count_closed == 0) &&
356            $this->state != 'proposal' &&
357            ! $causes_without_tasks &&
358            $this->task_count > 0;
359
360    }
361
362    public function can_be_rejected() {
363        return $this->state == 'opened' && $this->task_count == 0;
364    }
365
366    public function closing_comment() {
367        $r = $this->model->thread_commentFactory->get_from_thread($this, array(), 'id', true, 1);
368        $thread_comment = $r->fetch();
369
370        return $thread_comment->content_html;
371    }
372
373    //http://data.agaric.com/capture-all-sent-mail-locally-postfix
374    //https://askubuntu.com/questions/192572/how-do-i-read-local-email-in-thunderbird
375    public function mail_notify($replacements=array(), $users=false) {
376        $plain = io_readFile($this->model->action->localFN('thread-notification'));
377        $html = io_readFile($this->model->action->localFN('thread-notification', 'html'));
378
379        $thread_reps = array(
380                                'thread_id' => $this->id,
381                                'thread_link' => $this->model->action->url('thread', 'id', $this->id),
382                                'thread_unsubscribe' =>
383                                    $this->model->action->url('thread', 'id', $this->id, 'action', 'unsubscribe'),
384                                'custom_content' => false,
385                                'action_border_color' => 'transparent',
386                                'action_color' => 'transparent',
387                           );
388
389        //$replacements can override $issue_reps
390        $rep = array_merge($thread_reps, $replacements);
391        //auto title
392        if (!isset($rep['subject'])) {
393            $rep['subject'] =  '#'.$this->id. ' ' .$this->title;
394        }
395        if (!isset($rep['content_html'])) {
396            $rep['content_html'] = $rep['content'];
397        }
398        if (!isset($rep['who_full_name'])) {
399            $rep['who_full_name'] =
400                $this->model->userFactory->get_user_full_name($rep['who']);
401        }
402
403        //format when
404        $rep['when'] =  dformat(strtotime($rep['when']), '%Y-%m-%d %H:%M');
405
406        if ($rep['custom_content'] === false) {
407            $html = str_replace('@CONTENT_HTML@', '
408                <div style="margin: 5px 0;">
409                    <strong>@WHO_FULL_NAME@</strong> <br>
410                    <span style="color: #888">@WHEN@</span>
411                </div>
412                @CONTENT_HTML@
413            ', $html);
414        }
415
416        //we must do it manually becouse Mailer uses htmlspecialchars()
417        $html = str_replace('@CONTENT_HTML@', $rep['content_html'], $html);
418
419        $mailer = new Mailer();
420        $mailer->setBody($plain, $rep, $rep, $html, false);
421
422        if ($users == FALSE) {
423            $users = array_map(function($par) {
424                return $par['user_id'];
425            }, $this->get_participants('subscribent'));
426
427            //don't notify myself
428            unset($users[$this->model->user_nick]);
429        }
430
431        $emails = array_map(function($user_id) {
432            return $this->model->userFactory->get_user_email($user_id);
433        }, $users);
434
435
436        $mailer->to($emails);
437        $mailer->subject($rep['subject']);
438
439        $send = $mailer->send();
440        if ($send === false) {
441            //this may mean empty $emails
442            //throw new Exception("can't send email");
443        }
444    }
445
446    protected function mail_issue_box_reps($replacements=array()) {
447        $replacements['custom_content'] = true;
448
449        $html =  '<h2 style="font-size: 1.2em;">';
450	    $html .=    '<a style="font-size:115%" href="@THREAD_LINK@">#@THREAD_ID@</a> ';
451
452        if ( ! empty($this->type_string)) {
453            $html .= $this->type_string;
454        } else {
455            $html .= '<i style="color: #777"> '.
456                        $this->model->action->getLang('issue_type_no_specified').
457                    '</i>';
458        }
459
460        $html .= ' ('. $this->model->action->getLang('state_' . $this->state ) .') ';
461
462        $html .= '<span style="color: #777; font-weight: normal; font-size: 90%;">';
463        $html .= $this->model->action->getLang('coordinator') . ': ';
464        $html .= '<span style="font-weight: bold;">';
465
466        if ($this->state == 'proposal') {
467            $html .= '<i style="font-weight: normal;">' .
468                $this->model->action->getLang('proposal') .
469                '</i>';
470        } else {
471            $html .= $this->model->userFactory->get_user_full_name($this->coordinator);
472        }
473        $html .= '</span></span></h2>';
474
475        $html .= '<h2 style="font-size: 1.2em;border-bottom: 1px solid @ACTION_BORDER_COLOR@">' . $this->title . '</h2>';
476
477        $html .= $this->content_html;
478
479        $replacements['content_html'] = $html;
480
481
482         switch ($this->priority) {
483            case '0':
484                $replacements['action_color'] = '#F8E8E8';
485                $replacements['action_border_color'] = '#F0AFAD';
486                break;
487            case '1':
488                $replacements['action_color'] = '#ffd';
489                $replacements['action_border_color'] = '#dd9';
490                break;
491            case '2':
492                $replacements['action_color'] = '#EEF6F0';
493                $replacements['action_border_color'] = '#B0D2B6';
494                break;
495            case 'None':
496                $replacements['action_color'] = '#e7f1ff';
497                $replacements['action_border_color'] = '#a3c8ff';
498                break;
499            default:
500                $replacements['action_color'] = '#fff';
501                $replacements['action_border_color'] = '#bbb';
502                break;
503        }
504
505        return $replacements;
506    }
507
508    public function mail_notify_change_state() {
509        $this->mail_notify($this->mail_issue_box_reps(array(
510            'who' => $this->model->user_nick,
511            'action' => $this->model->action->getLang('mail_mail_notify_change_state_action'),
512            //'subject' => $this->model->action->getLang('mail_mail_notify_change_state_subject') . ' #'.$this->id
513        )));
514    }
515
516    public function mail_notify_invite($client) {
517        $this->mail_notify($this->mail_issue_box_reps(array(
518            'who' => $this->model->user_nick,
519            'action' => $this->model->action->getLang('mail_mail_notify_invite_action'),
520            //'subject' => $this->model->action->getLang('mail_mail_notify_invite_subject') . ' #'.$this->id
521        )), array($client));
522    }
523
524    public function mail_inform_coordinator() {
525        $this->mail_notify($this->mail_issue_box_reps(array(
526            'who' => $this->model->user_nick,
527            'action' => $this->model->action->getLang('mail_mail_inform_coordinator_action'),
528            //'subject' => $this->model->action->getLang('mail_mail_inform_coordinator_subject') . ' #'.$this->id
529        )), array($this->coordinator));
530    }
531
532    public function mail_notify_issue_inactive($users=false) {
533        $this->mail_notify($this->mail_issue_box_reps(array(
534            'who' => '',
535            'action' => $this->model->action->getLang('mail_mail_notify_issue_inactive'),
536        )), $users);
537    }
538
539}
540