xref: /plugin/structnotification/action/notification.php (revision 2c65b6733af92d08e1e569a10002706440beccc7)
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 = $this->replacePlaceholders($message, $values);
116                        $message_html = p_render('xhtml',p_get_instructions($message), $info);
117                        $event->data['notifications'][] = [
118                            'plugin' => 'structnotification',
119                            'id' => $predicate['id'] . ':'. $schema . ':' . $pid . ':'  . $rawDate,
120                            'full' => $message_html,
121                            'brief' => $message_html,
122                            'timestamp' => (int) strtotime($rawDate)
123                        ];
124                    }
125                }
126            } catch (Exception $e) {
127                msg($e->getMessage(), -1);
128                return;
129            }
130        }
131    }
132
133    /**
134     * @return array
135     */
136    protected function users_set($user_and_groups, $values) {
137        /** @var DokuWiki_Auth_Plugin $auth */
138        global $auth;
139
140        //make substitutions
141        $user_and_groups = preg_replace_callback(
142            '/@@(.*?)@@/',
143            function ($matches) use ($values) {
144                list($schema, $field) = explode('.', trim($matches[1]));
145                if (!$field) return '';
146                /* @var Value $value */
147                foreach ($values as $value) {
148                    $colLabel = $value->getColumn()->getLabel();
149                    $type = $value->getColumn()->getType();
150                    if ($colLabel == $field) {
151                        if (class_exists('\dokuwiki\plugin\structgroup\types\Group') &&
152                            $type instanceof \dokuwiki\plugin\structgroup\types\Group) {
153                            return '@' . $value->getRawValue();
154                        }
155                        return $value->getRawValue();
156                    }
157                }
158                return '';
159            },
160            $user_and_groups
161        );
162
163        $user_and_groups_set = array_map('trim', explode(',', $user_and_groups));
164        $users = [];
165        $groups = [];
166        foreach ($user_and_groups_set as $user_or_group) {
167            if ($user_or_group[0] == '@') {
168                $groups[] = substr($user_or_group, 1);
169            } else {
170                $users[] = $user_or_group;
171            }
172        }
173        $set = [];
174
175        $all_users = $auth->retrieveUsers();
176        foreach ($all_users as $user => $info) {
177            if (in_array($user, $users)) {
178                $set[$user] = $info;
179            } elseif (array_intersect($groups, $info['grps'])) {
180                $set[$user] = $info;
181            }
182        }
183
184        return $set;
185    }
186
187    protected function predicateTrue($date, $operator, $days) {
188        $date = date('Y-m-d', strtotime($date));
189
190        switch ($operator) {
191            case 'before':
192                $days = date('Y-m-d', strtotime("+$days days"));
193                return $days >= $date;
194            case 'after':
195                $days = date('Y-m-d', strtotime("-$days days"));
196                return $date <= $days;
197            default:
198                return false;
199        }
200    }
201
202    protected function replacePlaceholders($message, $values) {
203        $patterns = [];
204        $replacements = [];
205        /* @var Value $value */
206        foreach ($values as $value) {
207            $schema = $value->getColumn()->getTable();
208            $label = $value->getColumn()->getLabel();
209            $patterns[] = "/@@$schema.$label@@/";
210            $replacements[] = $value->getDisplayValue();
211        }
212
213        return preg_replace($patterns, $replacements, $message);
214    }
215
216}
217
218