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