1<?php
2/**
3 * DokuWiki Plugin structnotification (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Szymon Olewniczak <it@rid.pl>
7 */
8
9// must be run within Dokuwiki
10use dokuwiki\plugin\struct\meta\Search;
11use dokuwiki\plugin\struct\meta\Value;
12
13if (!defined('DOKU_INC')) {
14    die();
15}
16
17class action_plugin_structnotification_notification extends DokuWiki_Action_Plugin
18{
19
20    /**
21     * Registers a callback function for a given event
22     *
23     * @param Doku_Event_Handler $controller DokuWiki's event controller object
24     *
25     * @return void
26     */
27    public function register(Doku_Event_Handler $controller)
28    {
29        $controller->register_hook('PLUGIN_NOTIFICATION_REGISTER_SOURCE', 'AFTER', $this, 'add_notifications_source');
30        $controller->register_hook('PLUGIN_NOTIFICATION_GATHER', 'AFTER', $this, 'add_notifications');
31        $controller->register_hook('PLUGIN_NOTIFICATION_CACHE_DEPENDENCIES', 'AFTER', $this, 'add_notification_cache_dependencies');
32
33
34    }
35
36    public function add_notifications_source(Doku_Event $event)
37    {
38        $event->data[] = 'structnotification';
39    }
40
41    public function add_notification_cache_dependencies(Doku_Event $event)
42    {
43        if (!in_array('structnotification', $event->data['plugins'])) return;
44
45        try {
46            /** @var \helper_plugin_structnotification_db $db_helper */
47            $db_helper = plugin_load('helper', 'structnotification_db');
48            $sqlite = $db_helper->getDB();
49            $event->data['dependencies'][] = $sqlite->getAdapter()->getDbFile();
50        } catch (Exception $e) {
51            msg($e->getMessage(), -1);
52            return;
53        }
54    }
55
56    protected function getValueByLabel($values, $label)
57    {
58        /* @var Value $value */
59        foreach ($values as $value) {
60            $colLabel = $value->getColumn()->getLabel();
61            if ($colLabel == $label) {
62                return $value->getRawValue();
63            }
64        }
65        //nothing found
66        throw new Exception("column: $label not found in values");
67    }
68
69
70    public function add_notifications(Doku_Event $event)
71    {
72        if (!in_array('structnotification', $event->data['plugins'])) return;
73
74        try {
75            /** @var \helper_plugin_structnotification_db$db_helper */
76            $db_helper = plugin_load('helper', 'structnotification_db');
77            $sqlite = $db_helper->getDB();
78        } catch (Exception $e) {
79            msg($e->getMessage(), -1);
80            return;
81        }
82
83        $user = $event->data['user'];
84
85        $q = 'SELECT * FROM predicate';
86        $res = $sqlite->query($q);
87
88        $predicates = $sqlite->res2arr($res);
89
90        foreach ($predicates as $predicate) {
91            $schema = $predicate['schema'];
92            $field = $predicate['field'];
93            $operator = $predicate['operator'];
94            $days = $predicate['days'];
95            $users_and_groups = $predicate['users_and_groups'];
96            $message = $predicate['message'];
97
98             try {
99                $search = new Search();
100                $search->addSchema($schema);
101                $search->addColumn('*');
102                $result = $search->execute();
103                $result_pids = $search->getPids();
104
105                /* @var Value[] $row */
106                for ($i=0; $i<count($result); $i++) {
107                    $values = $result[$i];
108                    $pid = $result_pids[$i];
109
110                    $users_set = $this->users_set($users_and_groups, $values);
111                    if (!isset($users_set[$user])) continue;
112
113                    $rawDate = $this->getValueByLabel($values, $field);
114                    if ($this->predicateTrue($rawDate, $operator, $days)) {
115                        $message_with_replacements = $this->replacePlaceholders($message, $values);
116                        $message_with_replacements_html = p_render('xhtml',
117                            p_get_instructions($message_with_replacements), $info);
118                        $event->data['notifications'][] = [
119                            'plugin' => 'structnotification',
120                            'id' => $predicate['id'] . ':'. $schema . ':' . $pid . ':'  . $rawDate,
121                            'full' => $message_with_replacements_html,
122                            'brief' => $message_with_replacements_html,
123                            'timestamp' => (int) strtotime($rawDate)
124                        ];
125                    }
126                }
127            } catch (Exception $e) {
128                msg($e->getMessage(), -1);
129                return;
130            }
131        }
132    }
133
134    /**
135     * @return array
136     */
137    protected function users_set($user_and_groups, $values) {
138        /** @var DokuWiki_Auth_Plugin $auth */
139        global $auth;
140
141        //make substitutions
142        $user_and_groups = preg_replace_callback(
143            '/@@(.*?)@@/',
144            function ($matches) use ($values) {
145                list($schema, $field) = explode('.', trim($matches[1]));
146                if (!$field) return '';
147                /* @var Value $value */
148                foreach ($values as $value) {
149                    $column = $value->getColumn();
150                    $colLabel = $column->getLabel();
151                    $type = $column->getType();
152                    if ($colLabel == $field) {
153                        if (class_exists('\dokuwiki\plugin\structgroup\types\Group') &&
154                            $type instanceof \dokuwiki\plugin\structgroup\types\Group) {
155                            if ($column->isMulti()) {
156                                return implode(',', array_map(function ($rawValue) {
157                                    return '@' . $rawValue;
158                                }, $value->getRawValue()));
159                            } else {
160                                return '@' . $value->getRawValue();
161                            }
162                        }
163                        if ($column->isMulti()) {
164                            return implode(',', $value->getRawValue());
165                        } else {
166                            return $value->getRawValue();
167                        }
168                    }
169                }
170                return '';
171            },
172            $user_and_groups
173        );
174
175        $user_and_groups_set = array_map('trim', explode(',', $user_and_groups));
176        $users = [];
177        $groups = [];
178        foreach ($user_and_groups_set as $user_or_group) {
179            if ($user_or_group[0] == '@') {
180                $groups[] = substr($user_or_group, 1);
181            } else {
182                $users[] = $user_or_group;
183            }
184        }
185        $set = [];
186
187        $all_users = $auth->retrieveUsers();
188        foreach ($all_users as $user => $info) {
189            if (in_array($user, $users)) {
190                $set[$user] = $info;
191            } elseif (array_intersect($groups, $info['grps'])) {
192                $set[$user] = $info;
193            }
194        }
195
196        return $set;
197    }
198
199    protected function predicateTrue($date, $operator, $days) {
200        $date = date('Y-m-d', strtotime($date));
201
202        switch ($operator) {
203            case 'before':
204                $days = date('Y-m-d', strtotime("+$days days"));
205                return $days >= $date;
206            case 'after':
207                $days = date('Y-m-d', strtotime("-$days days"));
208                return $date <= $days;
209            default:
210                return false;
211        }
212    }
213
214    protected function replacePlaceholders($message, $values) {
215        $patterns = [];
216        $replacements = [];
217        /* @var Value $value */
218        foreach ($values as $value) {
219            $schema = $value->getColumn()->getTable();
220            $label = $value->getColumn()->getLabel();
221            $patterns[] = "/@@$schema.$label@@/";
222            $replacements[] = $value->getDisplayValue();
223        }
224
225        return preg_replace($patterns, $replacements, $message);
226    }
227
228}
229
230