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