xref: /plugin/bez/mdl/Task.php (revision a0cd8c785f18b483f73582b411767428d04a78f6)
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 Task extends Entity {
10
11    protected $id;
12
13	protected $original_poster, $assignee, $closed_by;
14
15	protected $private, $lock;
16
17	protected $state, $type;
18
19	protected $create_date, $last_activity_date, $last_modification_date, $close_date;
20
21	protected $cost, $plan_date, $all_day_event, $start_time, $finish_time;
22
23	protected $content, $content_html;
24
25	protected $thread_id, $thread_comment_id, $task_program_id;
26
27	/** @var \dokuwiki\plugin\bez\mdl\Thread */
28	protected $thread;
29
30	/** @var Thread_comment */
31	protected $thread_comment;
32
33	//virtual
34    protected $task_program_name, $priority, $coordinator;
35
36	public static function get_columns() {
37		return array('id',
38            'original_poster', 'assignee', 'closed_by',
39            'private', 'lock',
40            'state', 'type',
41            'create_date', 'last_activity_date', 'last_modification_date', 'close_date',
42            'cost', 'plan_date', 'all_day_event', 'start_time', 'finish_time',
43            'content', 'content_html',
44            'thread_id', 'thread_comment_id', 'task_program_id');
45	}
46
47	public static function get_types() {
48	    return array('correction', 'corrective', 'preventive', 'program');
49    }
50
51    public static function get_states() {
52        return array('opened', 'done');
53    }
54
55    public function __get($property) {
56        if ($property == 'thread') {
57            if ($this->thread_id == null) {
58                return null;
59            }
60            if ($this->thread == null) {
61                $this->thread = $this->model->threadFactory->get_one($this->thread_id);
62            }
63            return $this->thread;
64
65        } elseif($property == 'thread_comment') {
66            if ($this->thread_comment_id == null) {
67                return null;
68            }
69            if ($this->thread_comment == null) {
70                $this->thread_comment = $this->model->thread_commentFactory->get_one($this->thread_comment_id);
71            }
72            return $this->thread_comment;
73
74        } elseif($property == 'priority' || $property == 'coordinator' || $property == 'task_program_name') {
75            return $this->$property;
76        }
77        return parent::__get($property);
78    }
79
80	public function __construct($model, $defaults=array()) {
81		parent::__construct($model, $defaults);
82
83		//virutal ACL columns (not in select)
84		$this->acl->add_column('participants');
85
86		$this->validator->set_rules(array(
87            'assignee' => array(array('dw_user'), 'NOT NULL'),
88            'cost' => array(array('numeric'), 'NULL'),
89			'plan_date' => array(array('iso_date'), 'NOT NULL'),
90			'all_day_event' => array(array('select', array('0', '1')), 'NOT NULL'),
91			'start_time' => array(array('time'), 'NULL'),
92			'finish_time' => array(array('time'), 'NULL'),
93            'content' => array(array('length', 10000), 'NOT NULL'),
94            'thread_comment_id' => array(array('numeric'), 'NULL'),
95            'task_program_id' => array(array('numeric'), 'NULL')
96		));
97
98		//we've created empty object
99		if ($this->id === NULL) {
100            $this->original_poster = $this->model->user_nick;
101            $this->create_date = date('c');
102            $this->last_activity_date = $this->create_date;
103            $this->last_modification_date = $this->create_date;
104
105            $this->state = 'opened';
106
107            if (isset($defaults['thread'])) {
108                $this->thread = $defaults['thread'];
109                $this->thread_id = $this->thread->id;
110                $this->coordinator = $this->thread->coordinator;
111                $this->type = 'correction';
112
113                if (isset($defaults['thread_comment'])) {
114                    $this->thread_comment = $defaults['thread_comment'];
115                    $this->thread_comment_id = $this->thread_comment->id;
116
117                    if ($this->thread_comment->type == 'cause_real') {
118                        $this->type = 'corrective';
119                    } else {
120                        $this->type = 'preventive';
121                    }
122                }
123            } else {
124                $this->type = 'program';
125            }
126
127            //everyone can report their own program tasks
128            if ($this->type == 'program') {
129                $this->acl->grant('content', BEZ_PERMISSION_CHANGE);
130                $this->acl->grant('plan_date', BEZ_PERMISSION_CHANGE);
131                $this->acl->grant('start_time', BEZ_PERMISSION_CHANGE);
132                $this->acl->grant('finish_time', BEZ_PERMISSION_CHANGE);
133                $this->acl->grant('all_day_event', BEZ_PERMISSION_CHANGE);
134                $this->acl->grant('task_program_id', BEZ_PERMISSION_CHANGE);
135                $this->acl->grant('cost', BEZ_PERMISSION_CHANGE);
136            }
137
138            if ($this->type == 'program' && $this->model->get_level() >= BEZ_AUTH_LEADER) {
139                $this->acl->grant('assignee', BEZ_PERMISSION_CHANGE);
140                $this->acl->grant('participants', BEZ_PERMISSION_CHANGE);
141            }
142
143            if ($this->type != 'program' && $this->coordinator == $this->model->user_nick) {
144                $this->acl->grant('content', BEZ_PERMISSION_CHANGE);
145                $this->acl->grant('plan_date', BEZ_PERMISSION_CHANGE);
146                $this->acl->grant('start_time', BEZ_PERMISSION_CHANGE);
147                $this->acl->grant('finish_time', BEZ_PERMISSION_CHANGE);
148                $this->acl->grant('all_day_event', BEZ_PERMISSION_CHANGE);
149                $this->acl->grant('task_program_id', BEZ_PERMISSION_CHANGE);
150                $this->acl->grant('cost', BEZ_PERMISSION_CHANGE);
151
152                $this->acl->grant('assignee', BEZ_PERMISSION_CHANGE);
153                $this->acl->grant('participants', BEZ_PERMISSION_CHANGE);
154            }
155
156        //we get object form db
157		} else {
158            if (isset($defaults['thread']) && $this->thread_id == $defaults['thread']->id) {
159                $this->thread = $defaults['thread'];
160            }
161
162            if (isset($defaults['thread_comment']) && $this->thread_comment_id == $defaults['thread_comment']->id) {
163                $this->thread_comment = $defaults['thread_comment'];
164            }
165
166            //user can close their tasks
167            if ($this->assignee == $this->model->user_nick || $this->model->get_level() >= BEZ_AUTH_LEADER) {
168                $this->acl->grant('state', BEZ_PERMISSION_CHANGE);
169            }
170
171            if ($this->type == 'program' && $this->original_poster == $this->model->user_nick) {
172                $this->acl->grant('content', BEZ_PERMISSION_CHANGE);
173                $this->acl->grant('plan_date', BEZ_PERMISSION_CHANGE);
174                $this->acl->grant('start_time', BEZ_PERMISSION_CHANGE);
175                $this->acl->grant('finish_time', BEZ_PERMISSION_CHANGE);
176                $this->acl->grant('all_day_event', BEZ_PERMISSION_CHANGE);
177                $this->acl->grant('task_program_id', BEZ_PERMISSION_CHANGE);
178                $this->acl->grant('cost', BEZ_PERMISSION_CHANGE);
179            }
180
181            if (($this->type != 'program' && $this->coordinator == $this->model->user_nick) ||
182                ($this->model->get_level() >= BEZ_AUTH_LEADER)) {
183                $this->acl->grant('content', BEZ_PERMISSION_CHANGE);
184                $this->acl->grant('plan_date', BEZ_PERMISSION_CHANGE);
185                $this->acl->grant('start_time', BEZ_PERMISSION_CHANGE);
186                $this->acl->grant('finish_time', BEZ_PERMISSION_CHANGE);
187                $this->acl->grant('all_day_event', BEZ_PERMISSION_CHANGE);
188                $this->acl->grant('task_program_id', BEZ_PERMISSION_CHANGE);
189                $this->acl->grant('cost', BEZ_PERMISSION_CHANGE);
190
191                $this->acl->grant('assignee', BEZ_PERMISSION_CHANGE);
192                $this->acl->grant('participants', BEZ_PERMISSION_CHANGE);
193            }
194        }
195
196		if ($this->thread_id == '') {
197			$this->validator->set_rules(array(
198				'task_program_id' => array(array('numeric'), 'NOT NULL'),
199			));
200		    //this field is unused in program tasks
201            $this->validator->delete_rule('thread_comment_id');
202        }
203    }
204
205
206	public function set_data($post, $filter=NULL) {
207        //all day event
208        if (!isset($post['all_day_event'])) {
209            $post['all_day_event'] = '0';
210        }
211
212        parent::set_data($post);
213
214        $this->content_html = p_render('xhtml',p_get_instructions($this->content), $ignore);
215
216        if (!isset($post['assignee'])) {
217            $this->assignee = $this->model->user_nick;
218        }
219
220        //update dates
221        $this->last_modification_date = date('c');
222        $this->last_activity_date = $this->last_modification_date;
223
224		return true;
225	}
226
227    public function set_state($state) {
228	    if ($this->acl_of('state') < BEZ_PERMISSION_CHANGE) {
229	        throw new PermissionDeniedException();
230        }
231
232        if (!in_array($state, array('opened', 'done'))) {
233	        throw new ValidationException('task', array('sholud be opened or done'));
234        }
235
236        //nothing to do
237        if ($state == $this->state) {
238	        return;
239        }
240
241        if ($state == 'done') {
242            $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET state=?, closed_by=?, close_date=? WHERE id=?",
243                $state,
244                $this->model->user_nick,
245                date('c'),
246                $this->id);
247        //reopen the task
248        } else {
249            $this->model->sqlite->query("UPDATE {$this->get_table_name()} SET state=? WHERE id=?", $state, $this->id);
250        }
251
252        $this->state = $state;
253    }
254
255    public function update_last_activity() {
256        $this->last_activity_date = date('c');
257        $this->model->sqlite->query('UPDATE task SET last_activity_date=? WHERE id=?',
258                                    $this->last_activity_date, $this->id);
259    }
260
261    public function can_add_participants() {
262        return in_array($this->state, array('opened'));
263    }
264
265    public function get_participants($filter='') {
266        if ($this->id === NULL) {
267            return array();
268        }
269
270        $sql = 'SELECT * FROM task_participant WHERE';
271        $possible_flags = array('original_poster', 'assignee', 'commentator', 'subscribent');
272        if ($filter != '') {
273            if (!in_array($filter, $possible_flags)) {
274                throw new \Exception("unknown flag $filter");
275            }
276            $sql .= " $filter=1 AND";
277        }
278        $sql .= ' task_id=? ORDER BY user_id';
279
280        $r = $this->model->sqlite->query($sql, $this->id);
281        $pars = $this->model->sqlite->res2arr($r);
282        $participants = array();
283        foreach ($pars as $par) {
284            $participants[$par['user_id']] = $par;
285        }
286
287        return $participants;
288    }
289
290    public function get_participant($user_id) {
291        if ($this->id === NULL) {
292            return array();
293        }
294
295        $r = $this->model->sqlite->query('SELECT * FROM task_participant WHERE task_id=? AND user_id=?', $this->id, $user_id);
296        $par = $this->model->sqlite->res2row($r);
297        if (!is_array($par)) {
298            return false;
299        }
300
301        return $par;
302    }
303
304    public function is_subscribent($user_id=null) {
305        if ($user_id == null) {
306            $user_id = $this->model->user_nick;
307        }
308        $par = $this->get_participant($user_id);
309        if ($par['subscribent'] == 1) {
310            return true;
311        }
312        return false;
313    }
314
315    public function remove_participant_flags($user_id, $flags) {
316        //thread not saved yet
317        if ($this->id === NULL) {
318            throw new \Exception('cannot remove flags from not saved thread');
319        }
320
321        $possible_flags = array('original_poster', 'assignee', 'commentator', 'subscribent');
322        if (array_intersect($flags, $possible_flags) != $flags) {
323            throw new \Exception('unknown flags');
324        }
325
326        $set = implode(',', array_map(function ($v) { return "$v=0"; }, $flags));
327
328        $sql = "UPDATE task_participant SET $set WHERE task_id=? AND user_id=?";
329        $this->model->sqlite->query($sql, $this->id, $user_id);
330
331    }
332
333    public function set_participant_flags($user_id, $flags=array()) {
334        //thread not saved yet
335        if ($this->id === NULL) {
336            throw new \Exception('cannot add flags to not saved thread');
337        }
338
339        //validate user
340        if (!$this->model->userFactory->exists($user_id)) {
341            throw new \Exception("$user_id isn't dokuwiki user");
342        }
343
344        $possible_flags = array('original_poster', 'assignee', 'commentator', 'subscribent');
345        if (array_intersect($flags, $possible_flags) != $flags) {
346            throw new \Exception('unknown flags');
347        }
348
349        $participant = $this->get_participant($user_id);
350        if ($participant == false) {
351            $participant = array_fill_keys($possible_flags, 0);
352
353            $participant['task_id'] = $this->id;
354            $participant['user_id'] = $user_id;
355            $participant['added_by'] = $this->model->user_nick;
356            $participant['added_date'] = date('c');
357        }
358        $values = array_merge($participant, array_fill_keys($flags, 1));
359
360        $keys = join(',', array_keys($values));
361        $vals = join(',', array_fill(0,count($values),'?'));
362
363        $sql = "REPLACE INTO task_participant ($keys) VALUES ($vals)";
364        $this->model->sqlite->query($sql, array_values($values));
365    }
366
367    public function invite($client) {
368        $this->set_participant_flags($client, array('subscribent'));
369        $this->mail_notify_invite($client);
370    }
371
372    private function mail_notify($replacements=array(), $users=false, $attachedImages=array()) {
373        $plain = io_readFile($this->model->action->localFN('task-notification'));
374        $html = io_readFile($this->model->action->localFN('task-notification', 'html'));
375
376        $task_link = $this->model->action->url('task', 'tid', $this->id);
377
378        $reps = array(
379                        'task_id' => $this->id,
380                        'task_link' => $task_link,
381                        'who' => $this->original_poster
382                     );
383
384        //$replacements can override $reps
385        $rep = array_merge($reps, $replacements);
386
387        if (!isset($rep['who_full_name'])) {
388            $rep['who_full_name'] =
389                $this->model->userFactory->get_user_full_name($rep['who']);
390        }
391
392        //auto title
393        if (!isset($rep['subject'])) {
394//            if (isset($rep['content'])) {
395//                $rep['subject'] =  array_shift(explode('.', $rep['content'], 2));
396//            }
397            $rep['subject'] = '#z'.$this->id. ' ' . $this->task_program_name;
398        }
399
400        //we must do it manually becouse Mailer uses htmlspecialchars()
401        $html = str_replace('@TASK_TABLE@', $rep['task_table'], $html);
402
403        $mailer = new Mailer();
404        $mailer->setBody($plain, $rep, $rep, $html, false);
405
406        if ($users === FALSE) {
407            $users = $this->get_participants('subscribent');
408
409            //don't notify current user
410            unset($users[$this->model->user_nick]);
411        }
412
413        $emails = array_map(function($user) {
414            if (is_array($user)) {
415                $user = $user['user_id'];
416            }
417            return $this->model->userFactory->get_user_email($user);
418        }, $users);
419
420        $mailer->to($emails);
421        $mailer->subject($rep['subject']);
422
423        //add images
424        foreach ($attachedImages as $img) {
425            $mailer->attachFile($img['path'], $img['mime'], $img['name'], $img['embed']);
426        }
427
428        $send = $mailer->send();
429        if ($send === false) {
430            //this may mean empty $emails
431            //throw new Exception("can't send email");
432        }
433    }
434
435    protected function bez_html_array_to_style_list($arr) {
436        $output = '';
437        foreach ($arr as $k => $v) {
438            $output .= $k.': '. $v . ';';
439        }
440        return $output;
441    }
442
443    protected function bez_html_irrtable($style) {
444        $argv = func_get_args();
445        $argc = func_num_args();
446        if (isset($style['table'])) {
447            $output = '<table style="'.self::bez_html_array_to_style_list($style['table']).'">';
448        } else {
449            $output = '<table>';
450        }
451
452        $tr_style  = '';
453        if (isset($style['tr'])) {
454            $tr_style = 'style="'.self::bez_html_array_to_style_list($style['tr']).'"';
455        }
456
457        $td_style  = '';
458        if (isset($style['td'])) {
459            $td_style = 'style="'.self::bez_html_array_to_style_list($style['td']).'"';
460        }
461
462        $row_max = 0;
463
464        for ($i = 1; $i < $argc; $i++) {
465            $row = $argv[$i];
466            $c = count($row);
467            if ($c > $row_max) {
468                $row_max = $c;
469            }
470        }
471
472        for ($j = 1; $j < $argc; $j++) {
473            $row = $argv[$j];
474            $output .= '<tr '.$tr_style.'>' . NL;
475            $c = count($row);
476            for ($i = 0; $i < $c; $i++) {
477                //last element
478                if ($i === $c - 1 && $c < $row_max) {
479                    $output .= '<td '.$td_style.' colspan="' . ( $row_max - $c + 1 ) . '">' . NL;
480                } else {
481                    $output .= '<td '.$td_style.'>' . NL;
482                }
483                $output .= $row[$i] . NL;
484                $output .= '</td>' . NL;
485            }
486            $output .= '</tr>' . NL;
487        }
488        $output .= '</table>' . NL;
489        return $output;
490    }
491
492    public function mail_notify_task_box($users=false, $replacements=array()) {
493       $top_row = array(
494            '<strong>'.$this->model->action->getLang('executor').': </strong>' .
495            $this->model->userFactory->get_user_full_name($this->assignee),
496
497            '<strong>'.$this->model->action->getLang('reporter').': </strong>' .
498            $this->model->userFactory->get_user_full_name($this->original_poster)
499        );
500
501        if ($this->task_program_name != '') {
502            $top_row[] =
503                '<strong>'.$this->model->action->getLang('task_type').': </strong>' .
504                $this->task_program_name;
505        }
506
507        if ($this->cost != '') {
508            $top_row[] =
509                '<strong>'.$this->model->action->getLang('cost').': </strong>' .
510                $this->cost;
511        }
512
513        //BOTTOM ROW
514        $bottom_row = array(
515            '<strong>'.$this->model->action->getLang('plan_date').': </strong>' .
516            $this->plan_date
517        );
518
519        if ($this->all_day_event == '0') {
520            $bottom_row[] =
521                '<strong>'.$this->model->action->getLang('start_time').': </strong>' .
522                $this->start_time;
523            $bottom_row[] =
524                '<strong>'.$this->model->action->getLang('finish_time').': </strong>' .
525                $this->finish_time;
526        }
527
528        $info = array();
529        $content_html = p_render('bez_xhtmlmail', p_get_instructions($this->content), $info);
530        $attachedImages = $info['img'];
531
532        $rep = array(
533            'content' => $this->content,
534            'content_html' =>
535                '<h2 style="font-size: 1.2em;">'.
536	               '<a href="'.$this->model->action->url('task', 'tid', $this->id).'">' .
537		              '#z'.$this->id .
538	               '</a> ' .
539	lcfirst($this->model->action->getLang('task_type_' . $this->type)) . ' ' .
540    '(' .
541        lcfirst($this->model->action->getLang('task_' . $this->state)) .
542    ')' .
543                '</h2>' .
544                self::bez_html_irrtable(array(
545                    'table' => array(
546                        'border-collapse' => 'collapse',
547                        'font-size' => '0.8em',
548                        'width' => '100%'
549                    ),
550                    'td' => array(
551                        'border-top' => '1px solid #8bbcbc',
552                        'border-bottom' => '1px solid #8bbcbc',
553                        'padding' => '.3em .5em'
554                    )
555                ), $top_row, $bottom_row) . $content_html,
556            'who' => $this->model->user_nick,
557            'when' => $this->create_date,
558            'custom_content' => true
559        );
560
561        $rep['action_color'] = '#e4f4f4';
562        $rep['action_border_color'] = '#8bbcbc';
563
564        //$replacements can override $reps
565        $rep = array_merge($rep, $replacements);
566
567        $this->mail_notify($rep, $users, $attachedImages);
568    }
569
570    public function mail_notify_subscribents($replacements=array()) {
571        $this->mail_notify_task_box(false, $replacements);
572    }
573
574    public function mail_notify_add($users=false, $replacements=array()) {
575        $replacements['action'] = $this->model->action->getLang('mail_task_added');
576        $this->mail_notify_task_box($users, $replacements);
577    }
578
579    public function mail_notify_remind($users=false) {
580        $replacements = array();
581
582        $replacements['action'] = $this->model->action->getLang('mail_task_remind');
583        //we don't want any who
584        $replacements['who_full_name'] = '';
585
586        //$users = array($this->executor);
587        $this->mail_notify_task_box($users, $replacements);
588    }
589
590    public function mail_notify_invite($client) {
591        $replacements = array();
592
593        $replacements['action'] = $this->model->action->getLang('mail_task_invite');
594
595        $users = array($client);
596        $this->mail_notify_task_box($users, $replacements);
597    }
598}
599