xref: /plugin/struct/meta/Schema.php (revision 7c080d6944fe1302e21893f424c042914e65877e)
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     * @param string $filter either 'page' or 'lookup'
153     * @return \string[]
154     */
155    static public function getAll($filter = '') {
156        /** @var \helper_plugin_struct_db $helper */
157        $helper = plugin_load('helper', 'struct_db');
158        $db = $helper->getDB();
159        if(!$db) return array();
160
161        if($filter == 'page') {
162            $where = 'islookup = 0';
163        } elseif($filter == 'lookup') {
164            $where = 'islookup = 1';
165        } else {
166            $where = '1 = 1';
167        }
168
169        $res = $db->query("SELECT DISTINCT tbl FROM schemas WHERE $where ORDER BY tbl");
170        $tables = $db->res2arr($res);
171        $db->res_close($res);
172
173        $result = array();
174        foreach($tables as $row) {
175            $result[] = $row['tbl'];
176        }
177        return $result;
178    }
179
180    /**
181     * Delete all data associated with this schema
182     *
183     * This is really all data ever! Be careful!
184     */
185    public function delete() {
186        if(!$this->id) throw new StructException('can not delete unsaved schema');
187
188        $this->sqlite->query('BEGIN TRANSACTION');
189
190        $sql = "DROP TABLE ?";
191        $this->sqlite->query($sql, 'data_' . $this->table);
192        $this->sqlite->query($sql, 'multi_' . $this->table);
193
194        $sql = "DELETE FROM schema_assignments WHERE tbl = ?";
195        $this->sqlite->query($sql, $this->table);
196
197        $sql = "DELETE FROM schema_assignments_patterns WHERE tbl = ?";
198        $this->sqlite->query($sql, $this->table);
199
200        $sql = "SELECT T.id
201                  FROM types T, schema_cols SC, schemas S
202                 WHERE T.id = SC.tid
203                   AND SC.sid = S.id
204                   AND S.tbl = ?";
205        $sql = "DELETE FROM types WHERE id IN ($sql)";
206        $this->sqlite->query($sql, $this->table);
207
208        $sql = "SELECT id
209                  FROM schemas
210                 WHERE tbl = ?";
211        $sql = "DELETE FROM schema_cols WHERE sid IN ($sql)";
212        $this->sqlite->query($sql, $this->table);
213
214        $sql = "DELETE FROM schemas WHERE tbl = ?";
215        $this->sqlite->query($sql, $this->table);
216
217        $this->sqlite->query('COMMIT TRANSACTION');
218        $this->sqlite->query('VACUUM');
219
220        // a deleted schema should not be used anymore, but let's make sure it's somewhat sane anyway
221        $this->id = 0;
222        $this->chksum = '';
223        $this->columns = array();
224        $this->maxsort = 0;
225        $this->ts = 0;
226    }
227
228    /**
229     * @return string
230     */
231    public function getChksum() {
232        return $this->chksum;
233    }
234
235    /**
236     * @return int
237     */
238    public function getId() {
239        return $this->id;
240    }
241
242    /**
243     * @return bool is this a lookup schema?
244     */
245    public function isLookup() {
246        return $this->islookup;
247    }
248
249    /**
250     * Returns a list of columns in this schema
251     *
252     * @param bool $withDisabled if false, disabled columns will not be returned
253     * @return Column[]
254     */
255    public function getColumns($withDisabled = true) {
256        if(!$withDisabled) {
257            return array_filter(
258                $this->columns,
259                function (Column $col) {
260                    return $col->isEnabled();
261                }
262            );
263        }
264
265        return $this->columns;
266    }
267
268    /**
269     * Find a column in the schema by its label
270     *
271     * Only enabled columns are returned!
272     *
273     * @param $name
274     * @return bool|Column
275     */
276    public function findColumn($name) {
277        foreach($this->columns as $col) {
278            if($col->isEnabled() && utf8_strtolower($col->getLabel()) == utf8_strtolower($name)) {
279                return $col;
280            }
281        }
282        return false;
283    }
284
285    /**
286     * @return string
287     */
288    public function getTable() {
289        return $this->table;
290    }
291
292    /**
293     * @return int the highest sort number used in this schema
294     */
295    public function getMaxsort() {
296        return $this->maxsort;
297    }
298
299    /**
300     * @return string the JSON representing this schema
301     */
302    public function toJSON() {
303        $data = array(
304            'structversion' => $this->structversion,
305            'schema' => $this->getTable(),
306            'id' => $this->getId(),
307            'columns' => array()
308        );
309
310        foreach($this->columns as $column) {
311            $data['columns'][] = array(
312                'colref' => $column->getColref(),
313                'ismulti' => $column->isMulti(),
314                'isenabled' => $column->isEnabled(),
315                'sort' => $column->getSort(),
316                'label' => $column->getLabel(),
317                'class' => $column->getType()->getClass(),
318                'config' => $column->getType()->getConfig(),
319            );
320        }
321
322        return json_encode($data, JSON_PRETTY_PRINT);
323    }
324}
325