xref: /plugin/struct/meta/Schema.php (revision 7cbcfbdb68125878b37fede99d5e33997295c2f6)
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        foreach($rows as $row) {
118            if($row['class'] == 'Integer') {
119                $row['class'] = 'Decimal';
120            }
121
122            $class = 'dokuwiki\\plugin\\struct\\types\\' . $row['class'];
123            if(!class_exists($class)) {
124                // This usually never happens, except during development
125                msg('Unknown type "' . hsc($row['class']) . '" falling back to Text', -1);
126                $class = 'dokuwiki\\plugin\\struct\\types\\Text';
127            }
128
129            $config = json_decode($row['config'], true);
130            /** @var AbstractBaseType $type */
131            $type = new $class($config, $row['label'], $row['ismulti'], $row['tid']);
132            $column = new Column(
133                $row['sort'],
134                $type,
135                $row['colref'],
136                $row['enabled'],
137                $table
138            );
139            $type->setContext($column);
140
141            $this->columns[] = $column;
142            if($row['sort'] > $this->maxsort) $this->maxsort = $row['sort'];
143        }
144    }
145
146    /**
147     * @return string identifer for debugging purposes
148     */
149    function __toString() {
150        return __CLASS__ . ' ' . $this->table . ' (' . $this->id . ') ' . ($this->islookup ? 'LOOKUP' : 'DATA');
151    }
152
153    /**
154     * Cleans any unwanted stuff from table names
155     *
156     * @param string $table
157     * @return string
158     */
159    static public function cleanTableName($table) {
160        $table = strtolower($table);
161        $table = preg_replace('/[^a-z0-9_]+/', '', $table);
162        $table = preg_replace('/^[0-9_]+/', '', $table);
163        $table = trim($table);
164        return $table;
165    }
166
167    /**
168     * Gets a list of all available schemas
169     *
170     * @param string $filter either 'page' or 'lookup'
171     * @return \string[]
172     */
173    static public function getAll($filter = '') {
174        /** @var \helper_plugin_struct_db $helper */
175        $helper = plugin_load('helper', 'struct_db');
176        $db = $helper->getDB(false);
177        if(!$db) return array();
178
179        if($filter == 'page') {
180            $where = 'islookup = 0';
181        } elseif($filter == 'lookup') {
182            $where = 'islookup = 1';
183        } else {
184            $where = '1 = 1';
185        }
186
187        $res = $db->query("SELECT DISTINCT tbl FROM schemas WHERE $where ORDER BY tbl");
188        $tables = $db->res2arr($res);
189        $db->res_close($res);
190
191        $result = array();
192        foreach($tables as $row) {
193            $result[] = $row['tbl'];
194        }
195        return $result;
196    }
197
198    /**
199     * Delete all data associated with this schema
200     *
201     * This is really all data ever! Be careful!
202     */
203    public function delete() {
204        if(!$this->id) throw new StructException('can not delete unsaved schema');
205
206        $this->sqlite->query('BEGIN TRANSACTION');
207
208        $sql = "DROP TABLE ?";
209        $this->sqlite->query($sql, 'data_' . $this->table);
210        $this->sqlite->query($sql, 'multi_' . $this->table);
211
212        $sql = "DELETE FROM schema_assignments WHERE tbl = ?";
213        $this->sqlite->query($sql, $this->table);
214
215        $sql = "DELETE FROM schema_assignments_patterns WHERE tbl = ?";
216        $this->sqlite->query($sql, $this->table);
217
218        $sql = "SELECT T.id
219                  FROM types T, schema_cols SC, schemas S
220                 WHERE T.id = SC.tid
221                   AND SC.sid = S.id
222                   AND S.tbl = ?";
223        $sql = "DELETE FROM types WHERE id IN ($sql)";
224        $this->sqlite->query($sql, $this->table);
225
226        $sql = "SELECT id
227                  FROM schemas
228                 WHERE tbl = ?";
229        $sql = "DELETE FROM schema_cols WHERE sid IN ($sql)";
230        $this->sqlite->query($sql, $this->table);
231
232        $sql = "DELETE FROM schemas WHERE tbl = ?";
233        $this->sqlite->query($sql, $this->table);
234
235        $this->sqlite->query('COMMIT TRANSACTION');
236        $this->sqlite->query('VACUUM');
237
238        // a deleted schema should not be used anymore, but let's make sure it's somewhat sane anyway
239        $this->id = 0;
240        $this->chksum = '';
241        $this->columns = array();
242        $this->maxsort = 0;
243        $this->ts = 0;
244    }
245
246    /**
247     * @return string
248     */
249    public function getChksum() {
250        return $this->chksum;
251    }
252
253    /**
254     * @return int
255     */
256    public function getId() {
257        return $this->id;
258    }
259
260    /**
261     * @return int returns the timestamp this Schema was created at
262     */
263    public function getTimeStamp() {
264        return $this->ts;
265    }
266
267    /**
268     * @return bool is this a lookup schema?
269     */
270    public function isLookup() {
271        return $this->islookup;
272    }
273
274    /**
275     * @return string
276     */
277    public function getUser() {
278        return $this->user;
279    }
280
281    /**
282     * @return string
283     */
284    public function getEditors() {
285        return $this->editors;
286    }
287
288    /**
289     * Checks if the current user may edit data in this schema
290     *
291     * @return bool
292     */
293    public function isEditable() {
294        global $USERINFO;
295        if($this->editors == '') return true;
296        if(blank($_SERVER['REMOTE_USER'])) return false;
297        if(auth_isadmin()) return true;
298        return auth_isMember($this->editors, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
299    }
300
301    /**
302     * Returns a list of columns in this schema
303     *
304     * @param bool $withDisabled if false, disabled columns will not be returned
305     * @return Column[]
306     */
307    public function getColumns($withDisabled = true) {
308        if(!$withDisabled) {
309            return array_filter(
310                $this->columns,
311                function (Column $col) {
312                    return $col->isEnabled();
313                }
314            );
315        }
316
317        return $this->columns;
318    }
319
320    /**
321     * Find a column in the schema by its label
322     *
323     * Only enabled columns are returned!
324     *
325     * @param $name
326     * @return bool|Column
327     */
328    public function findColumn($name) {
329        foreach($this->columns as $col) {
330            if($col->isEnabled() && utf8_strtolower($col->getLabel()) == utf8_strtolower($name)) {
331                return $col;
332            }
333        }
334        return false;
335    }
336
337    /**
338     * @return string
339     */
340    public function getTable() {
341        return $this->table;
342    }
343
344    /**
345     * @return int the highest sort number used in this schema
346     */
347    public function getMaxsort() {
348        return $this->maxsort;
349    }
350
351    /**
352     * @return string the JSON representing this schema
353     */
354    public function toJSON() {
355        $data = array(
356            'structversion' => $this->structversion,
357            'schema' => $this->getTable(),
358            'id' => $this->getId(),
359            'user' => $this->getUser(),
360            'columns' => array()
361        );
362
363        foreach($this->columns as $column) {
364            $data['columns'][] = array(
365                'colref' => $column->getColref(),
366                'ismulti' => $column->isMulti(),
367                'isenabled' => $column->isEnabled(),
368                'sort' => $column->getSort(),
369                'label' => $column->getLabel(),
370                'class' => $column->getType()->getClass(),
371                'config' => $column->getType()->getConfig(),
372            );
373        }
374
375        return json_encode($data, JSON_PRETTY_PRINT);
376    }
377}
378