xref: /plugin/struct/meta/Schema.php (revision 06fee43a4802b3338be3c05d8b6be3f01981337a)
1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4
5use dokuwiki\plugin\struct\types\AbstractBaseType;
6
7if(!defined('JSON_PRETTY_PRINT')) define('JSON_PRETTY_PRINT', 0); // PHP 5.3 compatibility
8
9/**
10 * Class Schema
11 *
12 * Represents the schema of a single data table and all its properties. It defines what can be stored in
13 * the represented data table and how those contents are formatted.
14 *
15 * It can be initialized with a timestamp to access the schema as it looked at that particular point in time.
16 *
17 * @package dokuwiki\plugin\struct\meta
18 */
19class Schema {
20
21    /** @var \helper_plugin_sqlite|null */
22    protected $sqlite;
23
24    /** @var int The ID of this schema */
25    protected $id = 0;
26
27    /** @var string the user who last edited this schema */
28    protected $user = '';
29
30    /** @var string name of the associated table */
31    protected $table = '';
32
33    /** @var bool is this a lookup schema? */
34    protected $islookup = false;
35
36    /**
37     * @var string the current checksum of this schema
38     */
39    protected $chksum = '';
40
41    /** @var Column[] all the colums */
42    protected $columns = array();
43
44    /** @var int */
45    protected $maxsort = 0;
46
47    /** @var int */
48    protected $ts = 0;
49
50    /** @var string struct version info */
51    protected $structversion = '?';
52
53    /** @var string comma separated list of allowed editors */
54    protected $editors = '';
55
56    /**
57     * Schema constructor
58     *
59     * @param string $table The table this schema is for
60     * @param int $ts The timestamp for when this schema was valid, 0 for current
61     * @param bool $islookup only used when creating a new schema, makes the new schema a lookup
62     */
63    public function __construct($table, $ts = 0, $islookup = false) {
64        /** @var \helper_plugin_struct_db $helper */
65        $helper = plugin_load('helper', 'struct_db');
66        $info = $helper->getInfo();
67        $this->structversion = $info['date'];
68        $this->sqlite = $helper->getDB();
69        $table = self::cleanTableName($table);
70        $this->table = $table;
71        $this->ts = $ts;
72
73        // load info about the schema itself
74        if($ts) {
75            $sql = "SELECT *
76                      FROM schemas
77                     WHERE tbl = ?
78                       AND ts <= ?
79                  ORDER BY ts DESC
80                     LIMIT 1";
81            $opt = array($table, $ts);
82        } else {
83            $sql = "SELECT *
84                      FROM schemas
85                     WHERE tbl = ?
86                  ORDER BY ts DESC
87                     LIMIT 1";
88            $opt = array($table);
89        }
90        $res = $this->sqlite->query($sql, $opt);
91        if($this->sqlite->res2count($res)) {
92            $schema = $this->sqlite->res2arr($res);
93            $result = array_shift($schema);
94            $this->id = $result['id'];
95            $this->user = $result['user'];
96            $this->chksum = $result['chksum'];
97            $this->islookup = $result['islookup'];
98            $this->ts = $result['ts'];
99            $this->editors = $result['editors'];
100        } else {
101            $this->islookup = $islookup;
102        }
103        $this->sqlite->res_close($res);
104        if(!$this->id) return;
105
106        // load existing columns
107        $sql = "SELECT SC.*, T.*
108                  FROM schema_cols SC,
109                       types T
110                 WHERE SC.sid = ?
111                   AND SC.tid = T.id
112              ORDER BY SC.sort";
113        $res = $this->sqlite->query($sql, $this->id);
114        $rows = $this->sqlite->res2arr($res);
115        $this->sqlite->res_close($res);
116
117        $typeclasses = Column::allTypes();
118        foreach($rows as $row) {
119            if($row['class'] == 'Integer') {
120                $row['class'] = 'Decimal';
121            }
122
123            $class = $typeclasses[$row['class']];
124            if(!class_exists($class)) {
125                // This usually never happens, except during development
126                msg('Unknown type "' . hsc($row['class']) . '" falling back to Text', -1);
127                $class = 'dokuwiki\\plugin\\struct\\types\\Text';
128            }
129
130            $config = json_decode($row['config'], true);
131            /** @var AbstractBaseType $type */
132            $type = new $class($config, $row['label'], $row['ismulti'], $row['tid']);
133            $column = new Column(
134                $row['sort'],
135                $type,
136                $row['colref'],
137                $row['enabled'],
138                $table
139            );
140            $type->setContext($column);
141
142            $this->columns[] = $column;
143            if($row['sort'] > $this->maxsort) $this->maxsort = $row['sort'];
144        }
145    }
146
147    /**
148     * @return string identifer for debugging purposes
149     */
150    function __toString() {
151        return __CLASS__ . ' ' . $this->table . ' (' . $this->id . ') ' . ($this->islookup ? 'LOOKUP' : 'DATA');
152    }
153
154    /**
155     * Cleans any unwanted stuff from table names
156     *
157     * @param string $table
158     * @return string
159     */
160    static public function cleanTableName($table) {
161        $table = strtolower($table);
162        $table = preg_replace('/[^a-z0-9_]+/', '', $table);
163        $table = preg_replace('/^[0-9_]+/', '', $table);
164        $table = trim($table);
165        return $table;
166    }
167
168    /**
169     * Gets a list of all available schemas
170     *
171     * @param string $filter either 'page' or 'lookup'
172     * @return \string[]
173     */
174    static public function getAll($filter = '') {
175        /** @var \helper_plugin_struct_db $helper */
176        $helper = plugin_load('helper', 'struct_db');
177        $db = $helper->getDB(false);
178        if(!$db) return array();
179
180        if($filter == 'page') {
181            $where = 'islookup = 0';
182        } elseif($filter == 'lookup') {
183            $where = 'islookup = 1';
184        } else {
185            $where = '1 = 1';
186        }
187
188        $res = $db->query("SELECT DISTINCT tbl FROM schemas WHERE $where ORDER BY tbl");
189        $tables = $db->res2arr($res);
190        $db->res_close($res);
191
192        $result = array();
193        foreach($tables as $row) {
194            $result[] = $row['tbl'];
195        }
196        return $result;
197    }
198
199    /**
200     * Delete all data associated with this schema
201     *
202     * This is really all data ever! Be careful!
203     */
204    public function delete() {
205        if(!$this->id) throw new StructException('can not delete unsaved schema');
206
207        $this->sqlite->query('BEGIN TRANSACTION');
208
209        $sql = "DROP TABLE ?";
210        $this->sqlite->query($sql, 'data_' . $this->table);
211        $this->sqlite->query($sql, 'multi_' . $this->table);
212
213        $sql = "DELETE FROM schema_assignments WHERE tbl = ?";
214        $this->sqlite->query($sql, $this->table);
215
216        $sql = "DELETE FROM schema_assignments_patterns WHERE tbl = ?";
217        $this->sqlite->query($sql, $this->table);
218
219        $sql = "SELECT T.id
220                  FROM types T, schema_cols SC, schemas S
221                 WHERE T.id = SC.tid
222                   AND SC.sid = S.id
223                   AND S.tbl = ?";
224        $sql = "DELETE FROM types WHERE id IN ($sql)";
225        $this->sqlite->query($sql, $this->table);
226
227        $sql = "SELECT id
228                  FROM schemas
229                 WHERE tbl = ?";
230        $sql = "DELETE FROM schema_cols WHERE sid IN ($sql)";
231        $this->sqlite->query($sql, $this->table);
232
233        $sql = "DELETE FROM schemas WHERE tbl = ?";
234        $this->sqlite->query($sql, $this->table);
235
236        $this->sqlite->query('COMMIT TRANSACTION');
237        $this->sqlite->query('VACUUM');
238
239        // a deleted schema should not be used anymore, but let's make sure it's somewhat sane anyway
240        $this->id = 0;
241        $this->chksum = '';
242        $this->columns = array();
243        $this->maxsort = 0;
244        $this->ts = 0;
245    }
246
247    /**
248     * @return string
249     */
250    public function getChksum() {
251        return $this->chksum;
252    }
253
254    /**
255     * @return int
256     */
257    public function getId() {
258        return $this->id;
259    }
260
261    /**
262     * @return int returns the timestamp this Schema was created at
263     */
264    public function getTimeStamp() {
265        return $this->ts;
266    }
267
268    /**
269     * @return bool is this a lookup schema?
270     */
271    public function isLookup() {
272        return $this->islookup;
273    }
274
275    /**
276     * @return string
277     */
278    public function getUser() {
279        return $this->user;
280    }
281
282    /**
283     * @return string
284     */
285    public function getEditors() {
286        return $this->editors;
287    }
288
289    /**
290     * Checks if the current user may edit data in this schema
291     *
292     * @return bool
293     */
294    public function isEditable() {
295        global $USERINFO;
296        if($this->editors == '') return true;
297        if(blank($_SERVER['REMOTE_USER'])) return false;
298        if(auth_isadmin()) return true;
299        return auth_isMember($this->editors, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
300    }
301
302    /**
303     * Returns a list of columns in this schema
304     *
305     * @param bool $withDisabled if false, disabled columns will not be returned
306     * @return Column[]
307     */
308    public function getColumns($withDisabled = true) {
309        if(!$withDisabled) {
310            return array_filter(
311                $this->columns,
312                function (Column $col) {
313                    return $col->isEnabled();
314                }
315            );
316        }
317
318        return $this->columns;
319    }
320
321    /**
322     * Find a column in the schema by its label
323     *
324     * Only enabled columns are returned!
325     *
326     * @param $name
327     * @return bool|Column
328     */
329    public function findColumn($name) {
330        foreach($this->columns as $col) {
331            if($col->isEnabled() && utf8_strtolower($col->getLabel()) == utf8_strtolower($name)) {
332                return $col;
333            }
334        }
335        return false;
336    }
337
338    /**
339     * @return string
340     */
341    public function getTable() {
342        return $this->table;
343    }
344
345    /**
346     * @return int the highest sort number used in this schema
347     */
348    public function getMaxsort() {
349        return $this->maxsort;
350    }
351
352    /**
353     * @return string the JSON representing this schema
354     */
355    public function toJSON() {
356        $data = array(
357            'structversion' => $this->structversion,
358            'schema' => $this->getTable(),
359            'id' => $this->getId(),
360            'user' => $this->getUser(),
361            'columns' => array()
362        );
363
364        foreach($this->columns as $column) {
365            $data['columns'][] = array(
366                'colref' => $column->getColref(),
367                'ismulti' => $column->isMulti(),
368                'isenabled' => $column->isEnabled(),
369                'sort' => $column->getSort(),
370                'label' => $column->getLabel(),
371                'class' => $column->getType()->getClass(),
372                'config' => $column->getType()->getConfig(),
373            );
374        }
375
376        return json_encode($data, JSON_PRETTY_PRINT);
377    }
378}
379