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                // add special columns
103                $special_columns = ['%pageid%', '%title%', '%lastupdate%', '%lasteditor%', '%lastsummary%', '%rowid%'];
104                foreach ($special_columns as $special_column) {
105                    $search->addColumn($special_column);
106                }
107                $result = $search->execute();
108                $result_pids = $search->getPids();
109
110                /* @var Value[] $row */
111                for ($i=0; $i<count($result); $i++) {
112                    $values = $result[$i];
113                    $pid = $result_pids[$i];
114
115                    $users_set = $this->users_set($users_and_groups, $values);
116                    if (!isset($users_set[$user])) continue;
117
118                    $rawDate = $this->getValueByLabel($values, $field);
119                    if ($this->predicateTrue($rawDate, $operator, $days)) {
120                        $message_with_replacements = $this->replacePlaceholders($message, $values);
121                        $message_with_replacements_html = p_render('xhtml',
122                            p_get_instructions($message_with_replacements), $info);
123                        $event->data['notifications'][] = [
124                            'plugin' => 'structnotification',
125                            'id' => $predicate['id'] . ':'. $schema . ':' . $pid . ':'  . $rawDate,
126                            'full' => $message_with_replacements_html,
127                            'brief' => $message_with_replacements_html,
128                            'timestamp' => (int) strtotime($rawDate)
129                        ];
130                    }
131                }
132            } catch (Exception $e) {
133                msg($e->getMessage(), -1);
134                return;
135            }
136        }
137    }
138
139    /**
140     * @return array
141     */
142    protected function users_set($user_and_groups, $values) {
143        /** @var DokuWiki_Auth_Plugin $auth */
144        global $auth;
145
146        //make substitutions
147        $user_and_groups = preg_replace_callback(
148            '/@@(.*?)@@/',
149            function ($matches) use ($values) {
150                list($schema, $field) = explode('.', trim($matches[1]));
151                if (!$field) return '';
152                /* @var Value $value */
153                foreach ($values as $value) {
154                    $column = $value->getColumn();
155                    $colLabel = $column->getLabel();
156                    $type = $column->getType();
157                    if ($colLabel == $field) {
158                        if (class_exists('\dokuwiki\plugin\structgroup\types\Group') &&
159                            $type instanceof \dokuwiki\plugin\structgroup\types\Group) {
160                            if ($column->isMulti()) {
161                                return implode(',', array_map(function ($rawValue) {
162                                    return '@' . $rawValue;
163                                }, $value->getRawValue()));
164                            } else {
165                                return '@' . $value->getRawValue();
166                            }
167                        }
168                        if ($column->isMulti()) {
169                            return implode(',', $value->getRawValue());
170                        } else {
171                            return $value->getRawValue();
172                        }
173                    }
174                }
175                return '';
176            },
177            $user_and_groups
178        );
179
180        $user_and_groups_set = array_map('trim', explode(',', $user_and_groups));
181        $users = [];
182        $groups = [];
183        foreach ($user_and_groups_set as $user_or_group) {
184            if ($user_or_group[0] == '@') {
185                $groups[] = substr($user_or_group, 1);
186            } else {
187                $users[] = $user_or_group;
188            }
189        }
190        $set = [];
191
192        $all_users = $auth->retrieveUsers();
193        foreach ($all_users as $user => $info) {
194            if (in_array($user, $users)) {
195                $set[$user] = $info;
196            } elseif (array_intersect($groups, $info['grps'])) {
197                $set[$user] = $info;
198            }
199        }
200
201        return $set;
202    }
203
204    protected function predicateTrue($date, $operator, $days) {
205        $date = date('Y-m-d', strtotime($date));
206
207        switch ($operator) {
208            case 'before':
209                $days = date('Y-m-d', strtotime("+$days days"));
210                return $days >= $date;
211            case 'after':
212                $days = date('Y-m-d', strtotime("-$days days"));
213                return $date <= $days;
214            default:
215                return false;
216        }
217    }
218
219    protected function replacePlaceholders($message, $values) {
220        $patterns = [];
221        $replacements = [];
222        /* @var Value $value */
223        foreach ($values as $value) {
224            $schema = $value->getColumn()->getTable();
225            $label = $value->getColumn()->getLabel();
226            $patterns[] = "/@@$schema.$label@@/";
227            $replacements[] = $value->getDisplayValue();
228        }
229
230        return preg_replace($patterns, $replacements, $message);
231    }
232
233}
234
235