1<?php
2
3use \dokuwiki\plugin\bez;
4
5if(!defined('DOKU_INC')) die();
6
7define('BEZ_NOTIFICATIONS_COOKIE_NAME', 'bez_notifications');
8
9class action_plugin_bez_default extends action_plugin_bez_base {
10
11	protected $action = '';
12    protected $params = array();
13
14    protected $notifications = array();
15
16    protected $errors = array();
17
18    public function get_action() {
19        return $this->action;
20    }
21
22    public function get_param($id, $default='') {
23        return (isset($this->params[$id]) ? $this->params[$id] : $default);
24    }
25
26    private function add_notification($value, $header=NULL) {
27        if (isset($_COOKIE[BEZ_NOTIFICATIONS_COOKIE_NAME])) {
28            $notifs = unserialize($_COOKIE[BEZ_NOTIFICATIONS_COOKIE_NAME]);
29        } else {
30            $notifs = array();
31        }
32        $notifs[] = array('value' => $value, 'header' => $header);
33        setcookie(BEZ_NOTIFICATIONS_COOKIE_NAME, serialize($notifs));
34    }
35
36    private function flush_notifications() {
37        if (!isset($_COOKIE[BEZ_NOTIFICATIONS_COOKIE_NAME])) {
38            return array();
39        }
40        $this->notifications = unserialize($_COOKIE[BEZ_NOTIFICATIONS_COOKIE_NAME]);
41
42        //remove cookie
43        setcookie(BEZ_NOTIFICATIONS_COOKIE_NAME, serialize(array()));
44    }
45
46    private function add_error($value, $header=NULL) {
47        $this->errors[] = array('value' => $value, 'header' => $header);
48    }
49
50	/**
51	 * Register its handlers with the DokuWiki's event controller
52	 */
53	public function register(Doku_Event_Handler $controller)
54	{
55        $controller->register_hook('DOKUWIKI_STARTED', 'BEFORE', $this, 'setup_id');
56        $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'setup_enviroment');
57		$controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'action_act_preprocess');
58		$controller->register_hook('TPL_ACT_RENDER', 'BEFORE', $this, 'tpl_act_render');
59		$controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'tpl_pagetools_display');
60		$controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'include_dependencies', array());
61		$controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this,'_ajax_call');
62
63        $controller->register_hook('PLUGIN_NOTIFICATION_REGISTER_SOURCE', 'AFTER', $this, 'add_notifications_source');
64        $controller->register_hook('PLUGIN_NOTIFICATION_GATHER', 'AFTER', $this, 'add_notifications');
65        $controller->register_hook('PLUGIN_NOTIFICATION_CACHE_DEPENDENCIES', 'AFTER', $this, 'add_notification_cache_dependencies');
66	}
67
68	public function include_dependencies(Doku_Event $event) {
69		// Adding a stylesheet
70		$event->data["link"][] = array (
71		  "type" => "text/css",
72		  "rel" => "stylesheet",
73		  "href" => DOKU_BASE.
74			"lib/plugins/bez/lib/jquery.timepicker-1.11.9-0/jquery.timepicker.css",
75		);
76
77		// Adding a JavaScript File
78		$event->data["script"][] = array (
79		  "type" => "text/javascript",
80		  "src" => DOKU_BASE.
81			"lib/plugins/bez/lib/jquery.timepicker-1.11.9-0/jquery.timepicker.min.js",
82		  "defer" => "defer",
83		  "_data" => "",
84		);
85
86		// Adding a JavaScript File
87		$event->data["script"][] = array (
88		  "type" => "text/javascript",
89		  "src" => DOKU_BASE.
90			"lib/plugins/bez/lib/jquery.datepair/datepair.js",
91            "defer" => "defer",
92		  "_data" => "",
93		);
94
95		// Adding a JavaScript File
96		$event->data["script"][] = array (
97		  "type" => "text/javascript",
98		  "src" => DOKU_BASE.
99			"lib/plugins/bez/lib/jquery.datepair/jquery.datepair.js",
100            "defer" => "defer",
101		  "_data" => "",
102		);
103
104		$event->data["link"][] = array (
105		  "type" => "text/css",
106		  "rel" => "stylesheet",
107		  "href" => DOKU_BASE.
108			"lib/plugins/bez/lib/jquery.form-validator/theme-default.min.css",
109		);
110
111
112		$event->data["script"][] = array (
113		  "type" => "text/javascript",
114		  "src" => DOKU_BASE.
115			"lib/plugins/bez/lib/jquery.form-validator/jquery.form-validator.min.js",
116            "defer" => "defer",
117		  "_data" => "",
118		);
119	}
120
121	public function setup_id(Doku_Event $event, $param) {
122	    global $INFO, $ID;
123
124        $id = $_GET['id'];
125        $ex = explode(':', $id);
126
127        //check if we process BEZ
128        if ($ex[0] !== 'bez' && $ex[1] !== 'bez') {
129            return;
130        }
131
132        $INFO['id'] = $id;
133        $ID = $id;
134    }
135
136    public function setup_enviroment(Doku_Event $event, $param) {
137        global $ACT, $conf, $ID;
138
139        if ($ACT !== 'show') {
140            return;
141        }
142
143		$ex = explode(':', $ID);
144
145        //check if we process BEZ
146        if ($ex[0] !== 'bez' && $ex[1] !== 'bez') {
147            return;
148        }
149
150        if ($ex[1] === 'bez') {
151            //pl is default language
152            if ($ex[0] == 'pl') {
153                //throw out "pl" and "bez"
154                array_shift($ex);
155                array_shift($ex);
156
157                $url = call_user_func_array(array($this, 'url'), $ex);
158                header("Location: $url");
159            }
160            $conf['lang'] = array_shift($ex);
161
162            $this->localised = false;
163        }
164        //throw out "bez"
165        array_shift($ex);
166
167        $this->action = array_shift($ex);
168
169        if (count($ex) % 2 !== 0) {
170            throw new Exception('invalid params');
171        }
172
173        for ($i = 0; $i < count($ex); $i += 2) {
174            $this->params[$ex[$i]] = $ex[$i+1];
175        }
176
177        $this->setupLocale();
178        $this->createObjects();
179
180        if (empty($conf['baseurl'])) {
181            msg($this->getLang('info set baseurl'));
182        }
183        if (empty($conf['basedir'])) {
184            msg($this->getLang('info set basedir'));
185        }
186    }
187
188	/**
189	 * handle ajax requests
190	 */
191	public function _ajax_call(Doku_Event $event, $param) {
192		global $auth;
193		if ($event->data !== 'plugin_bez') {
194			return;
195		}
196		//no other ajax call handlers needed
197		$event->stopPropagation();
198		$event->preventDefault();
199
200	}
201
202	public function tpl_pagetools_display(Doku_Event $event, $param) {
203		if ($this->action !== '') {
204			$event->preventDefault();
205        }
206	}
207
208	protected $prevent_rendering = false;
209
210	public function action_act_preprocess(Doku_Event $event, $param)
211	{
212        global $conf;
213
214        if ($this->action === '') {
215            return;
216        }
217
218        $event->preventDefault();
219		try {
220            $this->flush_notifications();
221
222			$ctl = DOKU_PLUGIN."bez/ctl/".str_replace('/', '', $this->action).".php";
223
224			if (file_exists($ctl)) {
225				include $ctl;
226			}
227        } catch(bez\meta\ValidationException $e) {
228            foreach ($e->get_errors() as $field => $error_code) {
229                $lang = $this->getLang($field);
230                if ($lang != '') {
231                    $field = $lang;
232                }
233                $this->add_error(
234                    $this->getLang('validate_' . $error_code),
235                    $field);
236            }
237
238            $this->tpl->set_values($_POST);
239
240        } catch(bez\meta\PermissionDeniedException $e) {
241            dbglog('plugin_bez', $e);
242            header('Location: ' . DOKU_URL . 'doku.php?id=' . $_GET['id'] . '&do=login');
243//        } catch (\PHPMailer\PHPMailer\Exception $e) {
244//            msg($e->getMessage(), -1);
245		} catch(Exception $e) {
246            dbglog('plugin_bez', $e);
247            if ($conf['allowdebug']) {
248               dbg($e);
249            } else {
250                msg($e->getMessage(), -1);
251            }
252            $this->prevent_rendering = true;
253		}
254	}
255
256	public function tpl_act_render($event, $param)
257	{
258        global $conf;
259
260        if ($this->action === '') {
261            return false;
262        }
263        $event->preventDefault();
264
265        if ($this->prevent_rendering) return;
266
267		try {
268
269			foreach ($this->errors as $error) {
270				echo '<div class="error">';
271                if ($error['header'] === NULL) {
272					echo $error['value'];
273				} else {
274					echo '<strong>'.$error['header'].'</strong>: '.$error['value'];
275				}
276				echo '</div>';
277			}
278
279            foreach ($this->notifications as $note) {
280                echo '<div class="info">';
281				if ($note['header'] === NULL) {
282					echo $note['value'];
283				} else {
284					echo $note['header'].': <strong>'.$note['value'].'</strong>';
285				}
286				echo '</div>';
287            }
288
289			$this->bez_tpl_include(str_replace('/', '', $this->get_action()));
290
291        } catch(bez\meta\PermissionDeniedException $e) {
292            dbglog('plugin_bez', $e);
293		} catch(Exception $e) {
294			/*exception*/
295            dbglog('plugin_bez', $e);
296            if ($conf['allowdebug']) {
297               dbg($e);
298            }
299		}
300	}
301
302	public function add_notifications_source(Doku_Event $event)
303    {
304        $event->data[] = 'bez:problems_without_tasks';
305        $event->data[] = 'bez:problems_coming';
306        $event->data[] = 'bez:problems_outdated';
307        $event->data[] = 'bez:tasks_coming';
308        $event->data[] = 'bez:tasks_outdated';
309    }
310
311    public function add_notification_cache_dependencies(Doku_Event $event)
312    {
313        if (!preg_grep('/^bez:.*/', $event->data['plugins'])) return;
314
315        /** @var \helper_plugin_bez_db $db_helper */
316        $db_helper = plugin_load('helper', 'bez_db');
317        $event->data['dependencies'][] = $db_helper->getDB()->getAdapter()->getDbFile();
318    }
319
320    public function add_notifications(Doku_Event $event)
321    {
322        if (!preg_grep('/^bez:.*/', $event->data['plugins'])) return;
323
324        $user = $event->data['user'];
325        $this->createObjects(true);
326
327        if (in_array('bez:problems_without_tasks', $event->data['plugins'])) {
328            $threads = $this->get_model()->factory('thread')->get_all(array(
329                                                                          'type' => 'issue',
330                                                                          'task_count' => '0',
331                                                                          'state' => 'opened',
332                                                                          'coordinator' => $user
333                                                                      ));
334            /** @var bez\mdl\Thread $thread */
335            foreach ($threads as $thread) {
336                $link = '<a href="' . $this->url('thread', 'id', $thread->id) . '">';
337                $link .= '#' . $thread->id;
338                $link .= '</a>';
339
340                $full = sprintf($this->getLang('notification problems_without_tasks'), $link);
341                $event->data['notifications'][] = [
342                    'plugin' => 'bez:problems_without_tasks',
343                    'id' => 'thread:' . $thread->id,
344                    'full' => $full,
345                    'brief' => $link,
346                    'timestamp' => strtotime($thread->last_activity_date)
347                ];
348            }
349        }
350
351        if (in_array('bez:problems_coming', $event->data['plugins'])) {
352            $threads = $this->get_model()->factory('thread')->get_all(array(
353                'type' => 'issue',
354                'priority' => '1',
355                'coordinator' => $user
356            ));
357            /** @var bez\mdl\Thread $thread */
358            foreach ($threads as $thread) {
359                $link = '<a href="' . $this->url('thread', 'id', $thread->id) . '">';
360                $link .= '#' . $thread->id;
361                $link .= '</a>';
362
363                $full = sprintf($this->getLang('notification problems_coming'), $link);
364                $event->data['notifications'][] = [
365                    'plugin' => 'bez:problems_coming',
366                    'id' => 'thread:' . $thread->id,
367                    'full' => $full,
368                    'brief' => $link,
369                    'timestamp' => strtotime($thread->last_activity_date)
370                ];
371            }
372        }
373
374        if (in_array('bez:problems_outdated', $event->data['plugins'])) {
375            $threads = $this->get_model()->threadFactory->get_all(array(
376                'type' => 'issue',
377                'priority' => '2',
378                'coordinator' => $user
379            ));
380            /** @var bez\mdl\Thread $thread */
381            foreach ($threads as $thread) {
382                $link = '<a href="' . $this->url('thread', 'id', $thread->id) . '">';
383                $link .= '#' . $thread->id;
384                $link .= '</a>';
385
386                $full = sprintf($this->getLang('notification problems_outdated'), $link);
387                $event->data['notifications'][] = [
388                    'plugin' => 'bez:problems_outdated',
389                    'id' => 'thread:' . $thread->id,
390                    'full' => $full,
391                    'brief' => $link,
392                    'timestamp' => strtotime($thread->last_activity_date)
393                ];
394            }
395        }
396
397        if (in_array('bez:tasks_coming', $event->data['plugins'])) {
398            $tasks = $this->get_model()->factory('task')->get_all(array(
399                'priority' => '1',
400                'assignee' => $user
401            ));
402            /** @var bez\mdl\Thread $thread */
403            foreach ($tasks as $task) {
404                $link = '<a href="' . $this->url('task', 'tid', $task->id) . '">';
405                $link .= '#z' . $task->id;
406                $link .= '</a>';
407
408                $full = sprintf($this->getLang('notification tasks_coming'), $link);
409                $event->data['notifications'][] = [
410                    'plugin' => 'bez:tasks_coming',
411                    'id' => 'task:' . $task->id,
412                    'full' => $full,
413                    'brief' => $link,
414                    'timestamp' => strtotime($task->plan_date)
415                ];
416            }
417        }
418
419        if (in_array('bez:tasks_outdated', $event->data['plugins'])) {
420            $tasks = $this->get_model()->factory('task')->get_all(array(
421                'priority' => '2',
422                'assignee' => $user
423            ));
424            /** @var bez\mdl\Thread $thread */
425            foreach ($tasks as $task) {
426                $link = '<a href="' . $this->url('task', 'tid', $task->id) . '">';
427                $link .= '#z' . $task->id;
428                $link .= '</a>';
429
430                $full = sprintf($this->getLang('notification tasks_outdated'), $link);
431                $event->data['notifications'][] = [
432                    'plugin' => 'bez:tasks_outdated',
433                    'id' => 'task:' . $task->id,
434                    'full' => $full,
435                    'brief' => $link,
436                    'timestamp' => strtotime($task->plan_date)
437                ];
438            }
439        }
440    }
441}
442