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