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