xref: /plugin/struct/meta/Schema.php (revision a91bbca21dc4af3c5dbb4590565758c378e3861d)
1083afc55SAndreas Gohr<?php
2083afc55SAndreas Gohr
3ba766201SAndreas Gohrnamespace dokuwiki\plugin\struct\meta;
4d486d6d7SAndreas Gohr
5ba766201SAndreas Gohruse dokuwiki\plugin\struct\types\AbstractBaseType;
6*a91bbca2SAndreas Gohruse dokuwiki\Utf8\PhpString;
7083afc55SAndreas Gohr
87182938bSAndreas Gohr/**
97182938bSAndreas Gohr * Class Schema
107182938bSAndreas Gohr *
117182938bSAndreas Gohr * Represents the schema of a single data table and all its properties. It defines what can be stored in
127182938bSAndreas Gohr * the represented data table and how those contents are formatted.
137182938bSAndreas Gohr *
147182938bSAndreas Gohr * It can be initialized with a timestamp to access the schema as it looked at that particular point in time.
157182938bSAndreas Gohr *
16ba766201SAndreas Gohr * @package dokuwiki\plugin\struct\meta
177182938bSAndreas Gohr */
18d6d97f60SAnna Dabrowskaclass Schema
19d6d97f60SAnna Dabrowska{
20f800af69SMichael Große    use TranslationUtilities;
21f800af69SMichael Große
22083afc55SAndreas Gohr    /** @var \helper_plugin_sqlite|null */
23083afc55SAndreas Gohr    protected $sqlite;
24083afc55SAndreas Gohr
25083afc55SAndreas Gohr    /** @var int The ID of this schema */
26083afc55SAndreas Gohr    protected $id = 0;
27083afc55SAndreas Gohr
28fa7b96aaSMichael Grosse    /** @var string the user who last edited this schema */
29fa7b96aaSMichael Grosse    protected $user = '';
30fa7b96aaSMichael Grosse
31083afc55SAndreas Gohr    /** @var string name of the associated table */
32083afc55SAndreas Gohr    protected $table = '';
33083afc55SAndreas Gohr
341c502704SAndreas Gohr    /** @var Column[] all the colums */
35083afc55SAndreas Gohr    protected $columns = array();
36083afc55SAndreas Gohr
37083afc55SAndreas Gohr    /** @var int */
38083afc55SAndreas Gohr    protected $maxsort = 0;
39083afc55SAndreas Gohr
40250c83c2SAndreas Gohr    /** @var int */
41250c83c2SAndreas Gohr    protected $ts = 0;
42250c83c2SAndreas Gohr
43d486d6d7SAndreas Gohr    /** @var string struct version info */
44d486d6d7SAndreas Gohr    protected $structversion = '?';
45d486d6d7SAndreas Gohr
46127d6bacSMichael Große    /** @var array config array with label translations */
47127d6bacSMichael Große    protected $config = array();
48e2c90eebSAndreas Gohr
49083afc55SAndreas Gohr    /**
50083afc55SAndreas Gohr     * Schema constructor
517182938bSAndreas Gohr     *
52083afc55SAndreas Gohr     * @param string $table The table this schema is for
53083afc55SAndreas Gohr     * @param int $ts The timestamp for when this schema was valid, 0 for current
54083afc55SAndreas Gohr     */
55d6d97f60SAnna Dabrowska    public function __construct($table, $ts = 0)
56d6d97f60SAnna Dabrowska    {
57127d6bacSMichael Große        $baseconfig = array('allowed editors' => '');
58127d6bacSMichael Große
59083afc55SAndreas Gohr        /** @var \helper_plugin_struct_db $helper */
60083afc55SAndreas Gohr        $helper = plugin_load('helper', 'struct_db');
61d486d6d7SAndreas Gohr        $info = $helper->getInfo();
62d486d6d7SAndreas Gohr        $this->structversion = $info['date'];
63083afc55SAndreas Gohr        $this->sqlite = $helper->getDB();
64083afc55SAndreas Gohr        $table = self::cleanTableName($table);
65083afc55SAndreas Gohr        $this->table = $table;
66250c83c2SAndreas Gohr        $this->ts = $ts;
67083afc55SAndreas Gohr
68083afc55SAndreas Gohr        // load info about the schema itself
69083afc55SAndreas Gohr        if ($ts) {
70083afc55SAndreas Gohr            $sql = "SELECT *
71083afc55SAndreas Gohr                      FROM schemas
72083afc55SAndreas Gohr                     WHERE tbl = ?
73083afc55SAndreas Gohr                       AND ts <= ?
74083afc55SAndreas Gohr                  ORDER BY ts DESC
75083afc55SAndreas Gohr                     LIMIT 1";
76083afc55SAndreas Gohr            $opt = array($table, $ts);
77083afc55SAndreas Gohr        } else {
78083afc55SAndreas Gohr            $sql = "SELECT *
79083afc55SAndreas Gohr                      FROM schemas
80083afc55SAndreas Gohr                     WHERE tbl = ?
81083afc55SAndreas Gohr                  ORDER BY ts DESC
82083afc55SAndreas Gohr                     LIMIT 1";
83083afc55SAndreas Gohr            $opt = array($table);
84083afc55SAndreas Gohr        }
85083afc55SAndreas Gohr        $res = $this->sqlite->query($sql, $opt);
86127d6bacSMichael Große        $config = array();
87083afc55SAndreas Gohr        if ($this->sqlite->res2count($res)) {
884e2abec0SMichael Große            $schema = $this->sqlite->res2arr($res);
894e2abec0SMichael Große            $result = array_shift($schema);
90083afc55SAndreas Gohr            $this->id = $result['id'];
91fa7b96aaSMichael Grosse            $this->user = $result['user'];
92587e314dSAndreas Gohr            $this->ts = $result['ts'];
93127d6bacSMichael Große            $config = json_decode($result['config'], true);
94083afc55SAndreas Gohr        }
95083afc55SAndreas Gohr        $this->sqlite->res_close($res);
96127d6bacSMichael Große        $this->config = array_merge($baseconfig, $config);
97f800af69SMichael Große        $this->initTransConfig(array('label'));
98083afc55SAndreas Gohr        if (!$this->id) return;
99083afc55SAndreas Gohr
100083afc55SAndreas Gohr        // load existing columns
101083afc55SAndreas Gohr        $sql = "SELECT SC.*, T.*
102083afc55SAndreas Gohr                  FROM schema_cols SC,
103083afc55SAndreas Gohr                       types T
1041c502704SAndreas Gohr                 WHERE SC.sid = ?
1051c502704SAndreas Gohr                   AND SC.tid = T.id
106083afc55SAndreas Gohr              ORDER BY SC.sort";
1071c502704SAndreas Gohr        $res = $this->sqlite->query($sql, $this->id);
108083afc55SAndreas Gohr        $rows = $this->sqlite->res2arr($res);
109083afc55SAndreas Gohr        $this->sqlite->res_close($res);
110083afc55SAndreas Gohr
111636c8abaSAndreas Gohr        $typeclasses = Column::allTypes();
112083afc55SAndreas Gohr        foreach ($rows as $row) {
113328db41bSAndreas Gohr            if ($row['class'] == 'Integer') {
114328db41bSAndreas Gohr                $row['class'] = 'Decimal';
115328db41bSAndreas Gohr            }
116328db41bSAndreas Gohr
117636c8abaSAndreas Gohr            $class = $typeclasses[$row['class']];
11898eaa57dSAndreas Gohr            if (!class_exists($class)) {
11998eaa57dSAndreas Gohr                // This usually never happens, except during development
12098eaa57dSAndreas Gohr                msg('Unknown type "' . hsc($row['class']) . '" falling back to Text', -1);
121ba766201SAndreas Gohr                $class = 'dokuwiki\\plugin\\struct\\types\\Text';
12298eaa57dSAndreas Gohr            }
12398eaa57dSAndreas Gohr
124083afc55SAndreas Gohr            $config = json_decode($row['config'], true);
125bbf3d6aaSAndreas Gohr            /** @var AbstractBaseType $type */
126bbf3d6aaSAndreas Gohr            $type = new $class($config, $row['label'], $row['ismulti'], $row['tid']);
127bbf3d6aaSAndreas Gohr            $column = new Column(
1281c502704SAndreas Gohr                $row['sort'],
129bbf3d6aaSAndreas Gohr                $type,
1301c502704SAndreas Gohr                $row['colref'],
13163d51bbfSAndreas Gohr                $row['enabled'],
13263d51bbfSAndreas Gohr                $table
1331c502704SAndreas Gohr            );
134bbf3d6aaSAndreas Gohr            $type->setContext($column);
1351c502704SAndreas Gohr
1367629557eSAndreas Gohr            $this->columns[] = $column;
137083afc55SAndreas Gohr            if ($row['sort'] > $this->maxsort) $this->maxsort = $row['sort'];
138083afc55SAndreas Gohr        }
139083afc55SAndreas Gohr    }
140083afc55SAndreas Gohr
141083afc55SAndreas Gohr    /**
14267641668SAndreas Gohr     * @return string identifer for debugging purposes
14367641668SAndreas Gohr     */
144748e747fSAnna Dabrowska    public function __toString()
145d6d97f60SAnna Dabrowska    {
1465b808f9fSAnna Dabrowska        return __CLASS__ . ' ' . $this->table . ' (' . $this->id . ') ';
14767641668SAndreas Gohr    }
14867641668SAndreas Gohr
14967641668SAndreas Gohr    /**
150083afc55SAndreas Gohr     * Cleans any unwanted stuff from table names
151083afc55SAndreas Gohr     *
152083afc55SAndreas Gohr     * @param string $table
153083afc55SAndreas Gohr     * @return string
154083afc55SAndreas Gohr     */
155d6d97f60SAnna Dabrowska    public static function cleanTableName($table)
156d6d97f60SAnna Dabrowska    {
1572af472dcSAndreas Gohr        $table = strtolower($table);
158083afc55SAndreas Gohr        $table = preg_replace('/[^a-z0-9_]+/', '', $table);
159083afc55SAndreas Gohr        $table = preg_replace('/^[0-9_]+/', '', $table);
160083afc55SAndreas Gohr        $table = trim($table);
161083afc55SAndreas Gohr        return $table;
162083afc55SAndreas Gohr    }
163083afc55SAndreas Gohr
164127d6bacSMichael Große
165127d6bacSMichael Große    /**
166097f4a53SAndreas Gohr     * Gets a list of all available schemas
167097f4a53SAndreas Gohr     *
1687c080d69SAndreas Gohr     * @return \string[]
169097f4a53SAndreas Gohr     */
1705b808f9fSAnna Dabrowska    public static function getAll()
171d6d97f60SAnna Dabrowska    {
172097f4a53SAndreas Gohr        /** @var \helper_plugin_struct_db $helper */
173097f4a53SAndreas Gohr        $helper = plugin_load('helper', 'struct_db');
1747cbcfbdbSAndreas Gohr        $db = $helper->getDB(false);
175097f4a53SAndreas Gohr        if (!$db) return array();
176097f4a53SAndreas Gohr
1775b808f9fSAnna Dabrowska        $res = $db->query("SELECT DISTINCT tbl FROM schemas ORDER BY tbl");
178097f4a53SAndreas Gohr        $tables = $db->res2arr($res);
179097f4a53SAndreas Gohr        $db->res_close($res);
180097f4a53SAndreas Gohr
181097f4a53SAndreas Gohr        $result = array();
182097f4a53SAndreas Gohr        foreach ($tables as $row) {
183097f4a53SAndreas Gohr            $result[] = $row['tbl'];
184097f4a53SAndreas Gohr        }
185097f4a53SAndreas Gohr        return $result;
186097f4a53SAndreas Gohr    }
187097f4a53SAndreas Gohr
188097f4a53SAndreas Gohr    /**
189d5a1a6dcSAndreas Gohr     * Delete all data associated with this schema
190d5a1a6dcSAndreas Gohr     *
191d5a1a6dcSAndreas Gohr     * This is really all data ever! Be careful!
192d5a1a6dcSAndreas Gohr     */
193d6d97f60SAnna Dabrowska    public function delete()
194d6d97f60SAnna Dabrowska    {
195d5a1a6dcSAndreas Gohr        if (!$this->id) throw new StructException('can not delete unsaved schema');
196d5a1a6dcSAndreas Gohr
197d5a1a6dcSAndreas Gohr        $this->sqlite->query('BEGIN TRANSACTION');
198d5a1a6dcSAndreas Gohr
199d5a1a6dcSAndreas Gohr        $sql = "DROP TABLE ?";
200d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, 'data_' . $this->table);
201d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, 'multi_' . $this->table);
202d5a1a6dcSAndreas Gohr
203d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schema_assignments WHERE tbl = ?";
204d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
205d5a1a6dcSAndreas Gohr
206d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schema_assignments_patterns WHERE tbl = ?";
207d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
208d5a1a6dcSAndreas Gohr
209d5a1a6dcSAndreas Gohr        $sql = "SELECT T.id
210d5a1a6dcSAndreas Gohr                  FROM types T, schema_cols SC, schemas S
211d5a1a6dcSAndreas Gohr                 WHERE T.id = SC.tid
212d5a1a6dcSAndreas Gohr                   AND SC.sid = S.id
213d5a1a6dcSAndreas Gohr                   AND S.tbl = ?";
214d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM types WHERE id IN ($sql)";
215d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
216d5a1a6dcSAndreas Gohr
217d5a1a6dcSAndreas Gohr        $sql = "SELECT id
218d5a1a6dcSAndreas Gohr                  FROM schemas
219d5a1a6dcSAndreas Gohr                 WHERE tbl = ?";
220d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schema_cols WHERE sid IN ($sql)";
221d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
222d5a1a6dcSAndreas Gohr
223d5a1a6dcSAndreas Gohr        $sql = "DELETE FROM schemas WHERE tbl = ?";
224d5a1a6dcSAndreas Gohr        $this->sqlite->query($sql, $this->table);
225d5a1a6dcSAndreas Gohr
226d5a1a6dcSAndreas Gohr        $this->sqlite->query('COMMIT TRANSACTION');
227d5a1a6dcSAndreas Gohr        $this->sqlite->query('VACUUM');
228f9f13d8cSAndreas Gohr
229f9f13d8cSAndreas Gohr        // a deleted schema should not be used anymore, but let's make sure it's somewhat sane anyway
230f9f13d8cSAndreas Gohr        $this->id = 0;
231f9f13d8cSAndreas Gohr        $this->columns = array();
232f9f13d8cSAndreas Gohr        $this->maxsort = 0;
233f9f13d8cSAndreas Gohr        $this->ts = 0;
234d5a1a6dcSAndreas Gohr    }
235d5a1a6dcSAndreas Gohr
23679c83e06SMichael Große
23779c83e06SMichael Große    /**
23879c83e06SMichael Große     * Clear all data of a schema, but retain the schema itself
23979c83e06SMichael Große     */
240d6d97f60SAnna Dabrowska    public function clear()
241d6d97f60SAnna Dabrowska    {
24279c83e06SMichael Große        if (!$this->id) throw new StructException('can not clear data of unsaved schema');
24379c83e06SMichael Große
24479c83e06SMichael Große        $this->sqlite->query('BEGIN TRANSACTION');
24579c83e06SMichael Große        $sql = 'DELETE FROM ?';
24679c83e06SMichael Große        $this->sqlite->query($sql, 'data_' . $this->table);
24779c83e06SMichael Große        $this->sqlite->query($sql, 'multi_' . $this->table);
24879c83e06SMichael Große        $this->sqlite->query('COMMIT TRANSACTION');
24979c83e06SMichael Große        $this->sqlite->query('VACUUM');
25079c83e06SMichael Große    }
25179c83e06SMichael Große
252d5a1a6dcSAndreas Gohr    /**
2531c502704SAndreas Gohr     * @return int
2541c502704SAndreas Gohr     */
255d6d97f60SAnna Dabrowska    public function getId()
256d6d97f60SAnna Dabrowska    {
2571c502704SAndreas Gohr        return $this->id;
2581c502704SAndreas Gohr    }
2591c502704SAndreas Gohr
2601c502704SAndreas Gohr    /**
261587e314dSAndreas Gohr     * @return int returns the timestamp this Schema was created at
262f411d872SAndreas Gohr     */
263d6d97f60SAnna Dabrowska    public function getTimeStamp()
264d6d97f60SAnna Dabrowska    {
265f411d872SAndreas Gohr        return $this->ts;
266f411d872SAndreas Gohr    }
267f411d872SAndreas Gohr
268f411d872SAndreas Gohr    /**
269fa7b96aaSMichael Grosse     * @return string
270fa7b96aaSMichael Grosse     */
271d6d97f60SAnna Dabrowska    public function getUser()
272d6d97f60SAnna Dabrowska    {
273fa7b96aaSMichael Grosse        return $this->user;
274fa7b96aaSMichael Grosse    }
275fa7b96aaSMichael Grosse
276d6d97f60SAnna Dabrowska    public function getConfig()
277d6d97f60SAnna Dabrowska    {
278127d6bacSMichael Große        return $this->config;
279e2c90eebSAndreas Gohr    }
280e2c90eebSAndreas Gohr
281fa7b96aaSMichael Grosse    /**
282f800af69SMichael Große     * Returns the translated label for this schema
283f800af69SMichael Große     *
284f800af69SMichael Große     * Uses the current language as determined by $conf['lang']. Falls back to english
285f800af69SMichael Große     * and then to the Schema label
286f800af69SMichael Große     *
287f800af69SMichael Große     * @return string
288f800af69SMichael Große     */
289d6d97f60SAnna Dabrowska    public function getTranslatedLabel()
290d6d97f60SAnna Dabrowska    {
291f800af69SMichael Große        return $this->getTranslatedKey('label', $this->table);
292f800af69SMichael Große    }
293f800af69SMichael Große
294f800af69SMichael Große    /**
2956ebbbb8eSAndreas Gohr     * Checks if the current user may edit data in this schema
2966ebbbb8eSAndreas Gohr     *
2976ebbbb8eSAndreas Gohr     * @return bool
2986ebbbb8eSAndreas Gohr     */
299d6d97f60SAnna Dabrowska    public function isEditable()
300d6d97f60SAnna Dabrowska    {
3016ebbbb8eSAndreas Gohr        global $USERINFO;
302ecf2cba2SAndreas Gohr        global $INPUT;
303127d6bacSMichael Große        if ($this->config['allowed editors'] === '') return true;
304ecf2cba2SAndreas Gohr        if ($INPUT->server->str('REMOTE_USER') === '') return false;
3056ebbbb8eSAndreas Gohr        if (auth_isadmin()) return true;
306ecf2cba2SAndreas Gohr        return auth_isMember($this->config['allowed editors'], $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
3076ebbbb8eSAndreas Gohr    }
3086ebbbb8eSAndreas Gohr
3096ebbbb8eSAndreas Gohr    /**
310ce206ec7SAndreas Gohr     * Returns a list of columns in this schema
311ce206ec7SAndreas Gohr     *
312ce206ec7SAndreas Gohr     * @param bool $withDisabled if false, disabled columns will not be returned
313ce206ec7SAndreas Gohr     * @return Column[]
3141c502704SAndreas Gohr     */
315d6d97f60SAnna Dabrowska    public function getColumns($withDisabled = true)
316d6d97f60SAnna Dabrowska    {
317ce206ec7SAndreas Gohr        if (!$withDisabled) {
318ce206ec7SAndreas Gohr            return array_filter(
319ce206ec7SAndreas Gohr                $this->columns,
320ce206ec7SAndreas Gohr                function (Column $col) {
321ce206ec7SAndreas Gohr                    return $col->isEnabled();
322ce206ec7SAndreas Gohr                }
323ce206ec7SAndreas Gohr            );
324ce206ec7SAndreas Gohr        }
325ce206ec7SAndreas Gohr
3261c502704SAndreas Gohr        return $this->columns;
3271c502704SAndreas Gohr    }
3281c502704SAndreas Gohr
329ae697e1fSAndreas Gohr    /**
3305742aea9SAndreas Gohr     * Find a column in the schema by its label
3315742aea9SAndreas Gohr     *
3325742aea9SAndreas Gohr     * Only enabled columns are returned!
3335742aea9SAndreas Gohr     *
3345742aea9SAndreas Gohr     * @param $name
3355742aea9SAndreas Gohr     * @return bool|Column
3365742aea9SAndreas Gohr     */
337d6d97f60SAnna Dabrowska    public function findColumn($name)
338d6d97f60SAnna Dabrowska    {
3395742aea9SAndreas Gohr        foreach ($this->columns as $col) {
340*a91bbca2SAndreas Gohr            if ($col->isEnabled() &&  PhpString::strtolower($col->getLabel()) == PhpString::strtolower($name)) {
3415742aea9SAndreas Gohr                return $col;
3425742aea9SAndreas Gohr            }
3435742aea9SAndreas Gohr        }
3445742aea9SAndreas Gohr        return false;
3455742aea9SAndreas Gohr    }
3465742aea9SAndreas Gohr
3475742aea9SAndreas Gohr    /**
348ae697e1fSAndreas Gohr     * @return string
349ae697e1fSAndreas Gohr     */
350d6d97f60SAnna Dabrowska    public function getTable()
351d6d97f60SAnna Dabrowska    {
352ae697e1fSAndreas Gohr        return $this->table;
353ae697e1fSAndreas Gohr    }
3541c502704SAndreas Gohr
355ae697e1fSAndreas Gohr    /**
356ae697e1fSAndreas Gohr     * @return int the highest sort number used in this schema
357ae697e1fSAndreas Gohr     */
358d6d97f60SAnna Dabrowska    public function getMaxsort()
359d6d97f60SAnna Dabrowska    {
360ae697e1fSAndreas Gohr        return $this->maxsort;
361ae697e1fSAndreas Gohr    }
3621c502704SAndreas Gohr
363d486d6d7SAndreas Gohr    /**
364d486d6d7SAndreas Gohr     * @return string the JSON representing this schema
365d486d6d7SAndreas Gohr     */
366d6d97f60SAnna Dabrowska    public function toJSON()
367d6d97f60SAnna Dabrowska    {
368d486d6d7SAndreas Gohr        $data = array(
369d486d6d7SAndreas Gohr            'structversion' => $this->structversion,
370d486d6d7SAndreas Gohr            'schema' => $this->getTable(),
371d486d6d7SAndreas Gohr            'id' => $this->getId(),
37245313413SMichael Grosse            'user' => $this->getUser(),
373127d6bacSMichael Große            'config' => $this->getConfig(),
374d486d6d7SAndreas Gohr            'columns' => array()
375d486d6d7SAndreas Gohr        );
376d486d6d7SAndreas Gohr
377d486d6d7SAndreas Gohr        foreach ($this->columns as $column) {
378d486d6d7SAndreas Gohr            $data['columns'][] = array(
379d486d6d7SAndreas Gohr                'colref' => $column->getColref(),
380d486d6d7SAndreas Gohr                'ismulti' => $column->isMulti(),
381d486d6d7SAndreas Gohr                'isenabled' => $column->isEnabled(),
382d486d6d7SAndreas Gohr                'sort' => $column->getSort(),
383d486d6d7SAndreas Gohr                'label' => $column->getLabel(),
384d486d6d7SAndreas Gohr                'class' => $column->getType()->getClass(),
385d486d6d7SAndreas Gohr                'config' => $column->getType()->getConfig(),
386d486d6d7SAndreas Gohr            );
387d486d6d7SAndreas Gohr        }
388d486d6d7SAndreas Gohr
389d486d6d7SAndreas Gohr        return json_encode($data, JSON_PRETTY_PRINT);
390d486d6d7SAndreas Gohr    }
391083afc55SAndreas Gohr}
392