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