xref: /plugin/struct/meta/Schema.php (revision 636c8abaee782e24109aa0fe69bdb75a977992fa)
1083afc55SAndreas Gohr<?php
2083afc55SAndreas Gohr
3ba766201SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
4d486d6d7SAndreas Gohr
5ba766201SAndreas Gohruse dokuwiki\plugin\struct\types\AbstractBaseType;
6083afc55SAndreas Gohr
745560cc7SAndreas Gohrif(!defined('JSON_PRETTY_PRINT')) define('JSON_PRETTY_PRINT', 0); // PHP 5.3 compatibility
845560cc7SAndreas Gohr
97182938bSAndreas Gohr/**
107182938bSAndreas Gohr * Class Schema
117182938bSAndreas Gohr *
127182938bSAndreas Gohr * Represents the schema of a single data table and all its properties. It defines what can be stored in
137182938bSAndreas Gohr * the represented data table and how those contents are formatted.
147182938bSAndreas Gohr *
157182938bSAndreas Gohr * It can be initialized with a timestamp to access the schema as it looked at that particular point in time.
167182938bSAndreas Gohr *
17ba766201SAndreas Gohr * @package dokuwiki\plugin\struct\meta
187182938bSAndreas Gohr */
19083afc55SAndreas Gohrclass Schema {
20083afc55SAndreas Gohr
21083afc55SAndreas Gohr    /** @var \helper_plugin_sqlite|null */
22083afc55SAndreas Gohr    protected $sqlite;
23083afc55SAndreas Gohr
24083afc55SAndreas Gohr    /** @var int The ID of this schema */
25083afc55SAndreas Gohr    protected $id = 0;
26083afc55SAndreas Gohr
27fa7b96aaSMichael Grosse    /** @var string the user who last edited this schema */
28fa7b96aaSMichael Grosse    protected $user = '';
29fa7b96aaSMichael Grosse
30083afc55SAndreas Gohr    /** @var string name of the associated table */
31083afc55SAndreas Gohr    protected $table = '';
32083afc55SAndreas Gohr
3388b7d2aaSAndreas Gohr    /** @var bool is this a lookup schema? */
3488b7d2aaSAndreas Gohr    protected $islookup = false;
3588b7d2aaSAndreas Gohr
36083afc55SAndreas Gohr    /**
37083afc55SAndreas Gohr     * @var string the current checksum of this schema
38083afc55SAndreas Gohr     */
39083afc55SAndreas Gohr    protected $chksum = '';
40083afc55SAndreas Gohr
411c502704SAndreas Gohr    /** @var Column[] all the colums */
42083afc55SAndreas Gohr    protected $columns = array();
43083afc55SAndreas Gohr
44083afc55SAndreas Gohr    /** @var int */
45083afc55SAndreas Gohr    protected $maxsort = 0;
46083afc55SAndreas Gohr
47250c83c2SAndreas Gohr    /** @var int */
48250c83c2SAndreas Gohr    protected $ts = 0;
49250c83c2SAndreas Gohr
50d486d6d7SAndreas Gohr    /** @var string struct version info */
51d486d6d7SAndreas Gohr    protected $structversion = '?';
52d486d6d7SAndreas Gohr
53e2c90eebSAndreas Gohr    /** @var string comma separated list of allowed editors */
54e2c90eebSAndreas Gohr    protected $editors = '';
55e2c90eebSAndreas Gohr
56083afc55SAndreas Gohr    /**
57083afc55SAndreas Gohr     * Schema constructor
587182938bSAndreas Gohr     *
59083afc55SAndreas Gohr     * @param string $table The table this schema is for
60083afc55SAndreas Gohr     * @param int $ts The timestamp for when this schema was valid, 0 for current
6188b7d2aaSAndreas Gohr     * @param bool $islookup only used when creating a new schema, makes the new schema a lookup
62083afc55SAndreas Gohr     */
6388b7d2aaSAndreas Gohr    public function __construct($table, $ts = 0, $islookup = false) {
64083afc55SAndreas Gohr        /** @var \helper_plugin_struct_db $helper */
65083afc55SAndreas Gohr        $helper = plugin_load('helper', 'struct_db');
66d486d6d7SAndreas Gohr        $info = $helper->getInfo();
67d486d6d7SAndreas Gohr        $this->structversion = $info['date'];
68083afc55SAndreas Gohr        $this->sqlite = $helper->getDB();
69083afc55SAndreas Gohr        $table = self::cleanTableName($table);
70083afc55SAndreas Gohr        $this->table = $table;
71250c83c2SAndreas Gohr        $this->ts = $ts;
72083afc55SAndreas Gohr
73083afc55SAndreas Gohr        // load info about the schema itself
74083afc55SAndreas Gohr        if($ts) {
75083afc55SAndreas Gohr            $sql = "SELECT *
76083afc55SAndreas Gohr                      FROM schemas
77083afc55SAndreas Gohr                     WHERE tbl = ?
78083afc55SAndreas Gohr                       AND ts <= ?
79083afc55SAndreas Gohr                  ORDER BY ts DESC
80083afc55SAndreas Gohr                     LIMIT 1";
81083afc55SAndreas Gohr            $opt = array($table, $ts);
82083afc55SAndreas Gohr        } else {
83083afc55SAndreas Gohr            $sql = "SELECT *
84083afc55SAndreas Gohr                      FROM schemas
85083afc55SAndreas Gohr                     WHERE tbl = ?
86083afc55SAndreas Gohr                  ORDER BY ts DESC
87083afc55SAndreas Gohr                     LIMIT 1";
88083afc55SAndreas Gohr            $opt = array($table);
89083afc55SAndreas Gohr        }
90083afc55SAndreas Gohr        $res = $this->sqlite->query($sql, $opt);
91083afc55SAndreas Gohr        if($this->sqlite->res2count($res)) {
924e2abec0SMichael Große            $schema = $this->sqlite->res2arr($res);
934e2abec0SMichael Große            $result = array_shift($schema);
94083afc55SAndreas Gohr            $this->id = $result['id'];
95fa7b96aaSMichael Grosse            $this->user = $result['user'];
96083afc55SAndreas Gohr            $this->chksum = $result['chksum'];
9788b7d2aaSAndreas Gohr            $this->islookup = $result['islookup'];
98587e314dSAndreas Gohr            $this->ts = $result['ts'];
99e2c90eebSAndreas Gohr            $this->editors = $result['editors'];
10088b7d2aaSAndreas Gohr        } else {
10188b7d2aaSAndreas Gohr            $this->islookup = $islookup;
102083afc55SAndreas Gohr        }
103083afc55SAndreas Gohr        $this->sqlite->res_close($res);
104083afc55SAndreas Gohr        if(!$this->id) return;
105083afc55SAndreas Gohr
106083afc55SAndreas Gohr        // load existing columns
107083afc55SAndreas Gohr        $sql = "SELECT SC.*, T.*
108083afc55SAndreas Gohr                  FROM schema_cols SC,
109083afc55SAndreas Gohr                       types T
1101c502704SAndreas Gohr                 WHERE SC.sid = ?
1111c502704SAndreas Gohr                   AND SC.tid = T.id
112083afc55SAndreas Gohr              ORDER BY SC.sort";
1131c502704SAndreas Gohr        $res = $this->sqlite->query($sql, $this->id);
114083afc55SAndreas Gohr        $rows = $this->sqlite->res2arr($res);
115083afc55SAndreas Gohr        $this->sqlite->res_close($res);
116083afc55SAndreas Gohr
117*636c8abaSAndreas Gohr        $typeclasses = Column::allTypes();
118083afc55SAndreas Gohr        foreach($rows as $row) {
119328db41bSAndreas Gohr            if($row['class'] == 'Integer') {
120328db41bSAndreas Gohr                $row['class'] = 'Decimal';
121328db41bSAndreas Gohr            }
122328db41bSAndreas Gohr
123*636c8abaSAndreas Gohr            $class = $typeclasses[$row['class']];
12498eaa57dSAndreas Gohr            if(!class_exists($class)) {
12598eaa57dSAndreas Gohr                // This usually never happens, except during development
12698eaa57dSAndreas Gohr                msg('Unknown type "' . hsc($row['class']) . '" falling back to Text', -1);
127ba766201SAndreas Gohr                $class = 'dokuwiki\\plugin\\struct\\types\\Text';
12898eaa57dSAndreas Gohr            }
12998eaa57dSAndreas Gohr
130083afc55SAndreas Gohr            $config = json_decode($row['config'], true);
131bbf3d6aaSAndreas Gohr            /** @var AbstractBaseType $type */
132bbf3d6aaSAndreas Gohr            $type = new $class($config, $row['label'], $row['ismulti'], $row['tid']);
133bbf3d6aaSAndreas Gohr            $column = new Column(
1341c502704SAndreas Gohr                $row['sort'],
135bbf3d6aaSAndreas Gohr                $type,
1361c502704SAndreas Gohr                $row['colref'],
13763d51bbfSAndreas Gohr                $row['enabled'],
13863d51bbfSAndreas Gohr                $table
1391c502704SAndreas Gohr            );
140bbf3d6aaSAndreas Gohr            $type->setContext($column);
1411c502704SAndreas Gohr
1427629557eSAndreas Gohr            $this->columns[] = $column;
143083afc55SAndreas Gohr            if($row['sort'] > $this->maxsort) $this->maxsort = $row['sort'];
144083afc55SAndreas Gohr        }
145083afc55SAndreas Gohr    }
146083afc55SAndreas Gohr
147083afc55SAndreas Gohr    /**
14867641668SAndreas Gohr     * @return string identifer for debugging purposes
14967641668SAndreas Gohr     */
15067641668SAndreas Gohr    function __toString() {
15167641668SAndreas Gohr        return __CLASS__ . ' ' . $this->table . ' (' . $this->id . ') ' . ($this->islookup ? 'LOOKUP' : 'DATA');
15267641668SAndreas Gohr    }
15367641668SAndreas Gohr
15467641668SAndreas Gohr    /**
155083afc55SAndreas Gohr     * Cleans any unwanted stuff from table names
156083afc55SAndreas Gohr     *
157083afc55SAndreas Gohr     * @param string $table
158083afc55SAndreas Gohr     * @return string
159083afc55SAndreas Gohr     */
160083afc55SAndreas Gohr    static public function cleanTableName($table) {
1612af472dcSAndreas Gohr        $table = strtolower($table);
162083afc55SAndreas Gohr        $table = preg_replace('/[^a-z0-9_]+/', '', $table);
163083afc55SAndreas Gohr        $table = preg_replace('/^[0-9_]+/', '', $table);
164083afc55SAndreas Gohr        $table = trim($table);
165083afc55SAndreas Gohr        return $table;
166083afc55SAndreas Gohr    }
167083afc55SAndreas Gohr
168083afc55SAndreas Gohr    /**
169097f4a53SAndreas Gohr     * Gets a list of all available schemas
170097f4a53SAndreas Gohr     *
1717c080d69SAndreas Gohr     * @param string $filter either 'page' or 'lookup'
1727c080d69SAndreas Gohr     * @return \string[]
173097f4a53SAndreas Gohr     */
1747c080d69SAndreas Gohr    static public function getAll($filter = '') {
175097f4a53SAndreas Gohr        /** @var \helper_plugin_struct_db $helper */
176097f4a53SAndreas Gohr        $helper = plugin_load('helper', 'struct_db');
1777cbcfbdbSAndreas Gohr        $db = $helper->getDB(false);
178097f4a53SAndreas Gohr        if(!$db) return array();
179097f4a53SAndreas Gohr
1807c080d69SAndreas Gohr        if($filter == 'page') {
1817c080d69SAndreas Gohr            $where = 'islookup = 0';
1827c080d69SAndreas Gohr        } elseif($filter == 'lookup') {
1837c080d69SAndreas Gohr            $where = 'islookup = 1';
1847c080d69SAndreas Gohr        } else {
1857c080d69SAndreas Gohr            $where = '1 = 1';
1867c080d69SAndreas Gohr        }
1877c080d69SAndreas Gohr
1887c080d69SAndreas Gohr        $res = $db->query("SELECT DISTINCT tbl FROM schemas WHERE $where ORDER BY tbl");
189097f4a53SAndreas Gohr        $tables = $db->res2arr($res);
190097f4a53SAndreas Gohr        $db->res_close($res);
191097f4a53SAndreas Gohr
192097f4a53SAndreas Gohr        $result = array();
193097f4a53SAndreas Gohr        foreach($tables as $row) {
194097f4a53SAndreas Gohr            $result[] = $row['tbl'];
195097f4a53SAndreas Gohr        }
196097f4a53SAndreas Gohr        return $result;
197097f4a53SAndreas Gohr    }
198097f4a53SAndreas Gohr
199097f4a53SAndreas Gohr    /**
200d5a1a6dcSAndreas Gohr     * Delete all data associated with this schema
201d5a1a6dcSAndreas Gohr     *
202d5a1a6dcSAndreas Gohr     * This is really all data ever! Be careful!
203d5a1a6dcSAndreas Gohr     */
204d5a1a6dcSAndreas Gohr    public function delete() {
205d5a1a6dcSAndreas Gohr        if(!$this->id) throw new StructException('can not delete unsaved schema');
206d5a1a6dcSAndreas Gohr
207d5a1a6dcSAndreas Gohr        $this->sqlite->query('BEGIN TRANSACTION');
208d5a1a6dcSAndreas Gohr
209d5a1a6dcSAndreas Gohr        $sql = "DROP TABLE ?";
210d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, 'data_' . $this->table);
211d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, 'multi_' . $this->table);
212d5a1a6dcSAndreas Gohr
213d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schema_assignments WHERE tbl = ?";
214d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
215d5a1a6dcSAndreas Gohr
216d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schema_assignments_patterns WHERE tbl = ?";
217d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
218d5a1a6dcSAndreas Gohr
219d5a1a6dcSAndreas Gohr        $sql = "SELECT T.id
220d5a1a6dcSAndreas Gohr                  FROM types T, schema_cols SC, schemas S
221d5a1a6dcSAndreas Gohr                 WHERE T.id = SC.tid
222d5a1a6dcSAndreas Gohr                   AND SC.sid = S.id
223d5a1a6dcSAndreas Gohr                   AND S.tbl = ?";
224d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM types WHERE id IN ($sql)";
225d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
226d5a1a6dcSAndreas Gohr
227d5a1a6dcSAndreas Gohr        $sql = "SELECT id
228d5a1a6dcSAndreas Gohr                  FROM schemas
229d5a1a6dcSAndreas Gohr                 WHERE tbl = ?";
230d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schema_cols WHERE sid IN ($sql)";
231d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
232d5a1a6dcSAndreas Gohr
233d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schemas WHERE tbl = ?";
234d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
235d5a1a6dcSAndreas Gohr
236d5a1a6dcSAndreas Gohr        $this->sqlite->query('COMMIT TRANSACTION');
237d5a1a6dcSAndreas Gohr        $this->sqlite->query('VACUUM');
238f9f13d8cSAndreas Gohr
239f9f13d8cSAndreas Gohr        // a deleted schema should not be used anymore, but let's make sure it's somewhat sane anyway
240f9f13d8cSAndreas Gohr        $this->id = 0;
241f9f13d8cSAndreas Gohr        $this->chksum = '';
242f9f13d8cSAndreas Gohr        $this->columns = array();
243f9f13d8cSAndreas Gohr        $this->maxsort = 0;
244f9f13d8cSAndreas Gohr        $this->ts = 0;
245d5a1a6dcSAndreas Gohr    }
246d5a1a6dcSAndreas Gohr
247d5a1a6dcSAndreas Gohr    /**
2481c502704SAndreas Gohr     * @return string
2491c502704SAndreas Gohr     */
2501c502704SAndreas Gohr    public function getChksum() {
2511c502704SAndreas Gohr        return $this->chksum;
2521c502704SAndreas Gohr    }
2531c502704SAndreas Gohr
2541c502704SAndreas Gohr    /**
2551c502704SAndreas Gohr     * @return int
2561c502704SAndreas Gohr     */
2571c502704SAndreas Gohr    public function getId() {
2581c502704SAndreas Gohr        return $this->id;
2591c502704SAndreas Gohr    }
2601c502704SAndreas Gohr
2611c502704SAndreas Gohr    /**
262587e314dSAndreas Gohr     * @return int returns the timestamp this Schema was created at
263f411d872SAndreas Gohr     */
264f411d872SAndreas Gohr    public function getTimeStamp() {
265f411d872SAndreas Gohr        return $this->ts;
266f411d872SAndreas Gohr    }
267f411d872SAndreas Gohr
268f411d872SAndreas Gohr    /**
26988b7d2aaSAndreas Gohr     * @return bool is this a lookup schema?
27088b7d2aaSAndreas Gohr     */
27188b7d2aaSAndreas Gohr    public function isLookup() {
27288b7d2aaSAndreas Gohr        return $this->islookup;
27388b7d2aaSAndreas Gohr    }
27488b7d2aaSAndreas Gohr
27588b7d2aaSAndreas Gohr    /**
276fa7b96aaSMichael Grosse     * @return string
277fa7b96aaSMichael Grosse     */
278fa7b96aaSMichael Grosse    public function getUser() {
279fa7b96aaSMichael Grosse        return $this->user;
280fa7b96aaSMichael Grosse    }
281fa7b96aaSMichael Grosse
2826ebbbb8eSAndreas Gohr    /**
2836ebbbb8eSAndreas Gohr     * @return string
2846ebbbb8eSAndreas Gohr     */
285e2c90eebSAndreas Gohr    public function getEditors() {
286e2c90eebSAndreas Gohr        return $this->editors;
287e2c90eebSAndreas Gohr    }
288e2c90eebSAndreas Gohr
289fa7b96aaSMichael Grosse    /**
2906ebbbb8eSAndreas Gohr     * Checks if the current user may edit data in this schema
2916ebbbb8eSAndreas Gohr     *
2926ebbbb8eSAndreas Gohr     * @return bool
2936ebbbb8eSAndreas Gohr     */
2946ebbbb8eSAndreas Gohr    public function isEditable() {
2956ebbbb8eSAndreas Gohr        global $USERINFO;
2966ebbbb8eSAndreas Gohr        if($this->editors == '') return true;
2976ebbbb8eSAndreas Gohr        if(blank($_SERVER['REMOTE_USER'])) return false;
2986ebbbb8eSAndreas Gohr        if(auth_isadmin()) return true;
2996ebbbb8eSAndreas Gohr        return auth_isMember($this->editors, $_SERVER['REMOTE_USER'], $USERINFO['grps']);
3006ebbbb8eSAndreas Gohr    }
3016ebbbb8eSAndreas Gohr
3026ebbbb8eSAndreas Gohr    /**
303ce206ec7SAndreas Gohr     * Returns a list of columns in this schema
304ce206ec7SAndreas Gohr     *
305ce206ec7SAndreas Gohr     * @param bool $withDisabled if false, disabled columns will not be returned
306ce206ec7SAndreas Gohr     * @return Column[]
3071c502704SAndreas Gohr     */
308ce206ec7SAndreas Gohr    public function getColumns($withDisabled = true) {
309ce206ec7SAndreas Gohr        if(!$withDisabled) {
310ce206ec7SAndreas Gohr            return array_filter(
311ce206ec7SAndreas Gohr                $this->columns,
312ce206ec7SAndreas Gohr                function (Column $col) {
313ce206ec7SAndreas Gohr                    return $col->isEnabled();
314ce206ec7SAndreas Gohr                }
315ce206ec7SAndreas Gohr            );
316ce206ec7SAndreas Gohr        }
317ce206ec7SAndreas Gohr
3181c502704SAndreas Gohr        return $this->columns;
3191c502704SAndreas Gohr    }
3201c502704SAndreas Gohr
321ae697e1fSAndreas Gohr    /**
3225742aea9SAndreas Gohr     * Find a column in the schema by its label
3235742aea9SAndreas Gohr     *
3245742aea9SAndreas Gohr     * Only enabled columns are returned!
3255742aea9SAndreas Gohr     *
3265742aea9SAndreas Gohr     * @param $name
3275742aea9SAndreas Gohr     * @return bool|Column
3285742aea9SAndreas Gohr     */
3295742aea9SAndreas Gohr    public function findColumn($name) {
3305742aea9SAndreas Gohr        foreach($this->columns as $col) {
3315742aea9SAndreas Gohr            if($col->isEnabled() && utf8_strtolower($col->getLabel()) == utf8_strtolower($name)) {
3325742aea9SAndreas Gohr                return $col;
3335742aea9SAndreas Gohr            }
3345742aea9SAndreas Gohr        }
3355742aea9SAndreas Gohr        return false;
3365742aea9SAndreas Gohr    }
3375742aea9SAndreas Gohr
3385742aea9SAndreas Gohr    /**
339ae697e1fSAndreas Gohr     * @return string
340ae697e1fSAndreas Gohr     */
341ae697e1fSAndreas Gohr    public function getTable() {
342ae697e1fSAndreas Gohr        return $this->table;
343ae697e1fSAndreas Gohr    }
3441c502704SAndreas Gohr
345ae697e1fSAndreas Gohr    /**
346ae697e1fSAndreas Gohr     * @return int the highest sort number used in this schema
347ae697e1fSAndreas Gohr     */
348ae697e1fSAndreas Gohr    public function getMaxsort() {
349ae697e1fSAndreas Gohr        return $this->maxsort;
350ae697e1fSAndreas Gohr    }
3511c502704SAndreas Gohr
352d486d6d7SAndreas Gohr    /**
353d486d6d7SAndreas Gohr     * @return string the JSON representing this schema
354d486d6d7SAndreas Gohr     */
355d486d6d7SAndreas Gohr    public function toJSON() {
356d486d6d7SAndreas Gohr        $data = array(
357d486d6d7SAndreas Gohr            'structversion' => $this->structversion,
358d486d6d7SAndreas Gohr            'schema' => $this->getTable(),
359d486d6d7SAndreas Gohr            'id' => $this->getId(),
36045313413SMichael Grosse            'user' => $this->getUser(),
361d486d6d7SAndreas Gohr            'columns' => array()
362d486d6d7SAndreas Gohr        );
363d486d6d7SAndreas Gohr
364d486d6d7SAndreas Gohr        foreach($this->columns as $column) {
365d486d6d7SAndreas Gohr            $data['columns'][] = array(
366d486d6d7SAndreas Gohr                'colref' => $column->getColref(),
367d486d6d7SAndreas Gohr                'ismulti' => $column->isMulti(),
368d486d6d7SAndreas Gohr                'isenabled' => $column->isEnabled(),
369d486d6d7SAndreas Gohr                'sort' => $column->getSort(),
370d486d6d7SAndreas Gohr                'label' => $column->getLabel(),
371d486d6d7SAndreas Gohr                'class' => $column->getType()->getClass(),
372d486d6d7SAndreas Gohr                'config' => $column->getType()->getConfig(),
373d486d6d7SAndreas Gohr            );
374d486d6d7SAndreas Gohr        }
375d486d6d7SAndreas Gohr
376d486d6d7SAndreas Gohr        return json_encode($data, JSON_PRETTY_PRINT);
377d486d6d7SAndreas Gohr    }
378083afc55SAndreas Gohr}
379