xref: /plugin/struct/meta/CSVPageImporter.php (revision 17dbef8af8e73f5c6a6bdbfcb629a48d85005bd7)
1<?php
2
3namespace dokuwiki\plugin\struct\meta;
4use dokuwiki\plugin\struct\types\Page;
5
6class CSVPageImporter extends CSVImporter {
7
8    protected $importedPids = array();
9
10    /** @var bool  */
11    protected $createPage = [];
12
13    /**
14     * Chceck if schema is page schema
15     *
16     * @throws StructException
17     * @param string $table
18     * @param string $file
19     */
20    public function __construct($table, $file) {
21        parent::__construct($table, $file);
22
23        if($this->schema->isLookup()) throw new StructException($table.' is not a page schema');
24    }
25
26    /**
27     * Import page schema only when the pid header is present.
28     */
29    protected function readHeaders() {
30
31        //add pid to struct
32        $pageType = new Page(null, 'pid');
33        $this->columns[] = new Column(0, $pageType, 0, true, $this->schema->getTable());
34
35        parent::readHeaders();
36
37        if(!in_array('pid', $this->header)) throw new StructException('There is no "pid" header in the CSV. Schema not imported.');
38    }
39
40    /**
41     * Creates the insert string for the single value table
42     *
43     * @return string
44     */
45    protected function getSQLforAllValues() {
46        $colnames = array();
47        foreach($this->columns as $i => $col) {
48            $colnames[] = 'col' . $col->getColref();
49        }
50        //replace first column with pid
51        $colnames[0] = 'pid';
52        //insert rev at the end
53        $colnames[] = 'rev';
54
55        $placeholds = join(', ', array_fill(0, count($colnames), '?'));
56        $colnames = join(', ', $colnames);
57        $table = $this->schema->getTable();
58
59        return "INSERT INTO data_$table ($colnames, latest) VALUES ($placeholds, 1)";
60    }
61
62    /**
63     * Add the revision.
64     *
65     * @param string[] $values
66     * @param          $line
67     * @param string   $single
68     * @param string   $multi
69     */
70    protected function saveLine($values, $line, $single, $multi) {
71        //create new page revision
72        $pid = $values[0];
73        if ($this->createPage[$pid]) {
74            $this->createPage($pid, $line);
75        }
76        $helper = plugin_load('helper', 'struct');
77        $revision = $helper->createPageRevision($pid, 'CSV data imported');
78        p_get_metadata($pid); // reparse the metadata of the page top update the titles/rev/lasteditor table
79
80        // make sure this schema is assigned
81        /** @noinspection PhpUndefinedVariableInspection */
82        Assignments::getInstance()->assignPageSchema(
83            $pid,
84            $this->schema->getTable()
85        );
86
87        //add page revision to values
88        $values[] = $revision;
89
90        parent::saveLine($values, $line, $single, $multi);
91    }
92
93    /**
94     * Create a page from a namespace template and replace column-label-placeholders
95     *
96     * This is intended to use the same placeholders as bureaucracy in their most basic version
97     * (i.e. without default values, formatting, etc. )
98     *
99     * @param string $pid
100     * @param array  $line
101     */
102    protected function createPage($pid, $line)
103    {
104        $text = pageTemplate($pid);
105        if (trim($text) === '') {
106            $pageParts = explode(':', $pid);
107            $pagename = end($pageParts);
108            $text = "====== $pagename ======\n";
109        }
110        $keys = array_map(function (Column $col) {return $col->getFullQualifiedLabel();} , $this->columns);
111        $keysAt = array_map(function ($key) { return "@@$key@@";}, $keys);
112        $keysHash = array_map(function ($key) { return "##$key##";}, $keys);
113        $flatValues = array_map(
114            function($value) {
115                if (is_array($value)) {
116                    return implode(', ', $value);
117                }
118                return $value;
119            }, $line);
120        $text = str_replace($keysAt, $flatValues, $text);
121        /** @noinspection CascadeStringReplacementInspection */
122        $text = str_replace($keysHash, $flatValues, $text);
123        saveWikiText($pid, $text, 'Created by struct csv import');
124    }
125
126    /**
127     * In the paga schemas primary key is a touple of (pid, rev)
128     *
129     * @param string[] $values
130     * @param string   $single
131     * @return array(pid, rev)
132     */
133    protected function insertIntoSingle($values, $single) {
134        $pid = $values[0];
135        $rev = $values[count($values) - 1];
136
137        //update latest
138        $table = $this->schema->getTable();
139        $this->sqlite->query("UPDATE data_$table SET latest = 0 WHERE latest = 1 AND pid = ?", array($pid));
140
141        //insert into table
142        parent::insertIntoSingle($values, $single);
143
144        //primary key is touple of (pid, rev)
145        return array($pid, $rev);
146    }
147
148    /**
149     * Add pid and rev to insert query parameters
150     *
151     * @param string $multi
152     * @param string $pk
153     * @param string $column
154     * @param string $row
155     * @param string $value
156     */
157    protected function insertIntoMulti($multi, $pk, $column, $row, $value) {
158        list($pid, $rev) = $pk;
159
160        //update latest
161        $table = $this->schema->getTable();
162        $this->sqlite->query("UPDATE multi_$table SET latest = 0 WHERE latest = 1 AND pid = ?", array($pid));
163
164        $this->sqlite->query($multi, array($pid, $rev, $column->getColref(), $row + 1, $value));
165    }
166
167    /**
168     * In page schemas we use REPLACE instead of INSERT to prevent ambiguity
169     *
170     * @return string
171     */
172    protected function getSQLforMultiValue() {
173        $table = $this->schema->getTable();
174        /** @noinspection SqlResolve */
175        return "INSERT INTO multi_$table (pid, rev, colref, row, value, latest) VALUES (?,?,?,?,?,1)";
176    }
177
178    /**
179     * Check if page id realy exists
180     *
181     * @param Column $col
182     * @param mixed  $rawvalue
183     * @return bool
184     */
185    protected function validateValue(Column $col, &$rawvalue) {
186        //check if page id exists and schema is bounded to the page
187        if($col->getLabel() == 'pid') {
188            $pid = cleanID($rawvalue);
189            if (isset($this->importedPids[$pid])) {
190                $this->errors[] = 'Page "'.$pid.'" already imported. Skipping the row.';
191                return false;
192            }
193            if(page_exists($pid)) {
194                $this->importedPids[$pid] = true;
195                return true;
196            }
197            global $INPUT;
198            if ($INPUT->bool('createPage')) {
199                $this->createPage[$pid] = true;
200                return true;
201            }
202            $this->errors[] = 'Page "'.$pid.'" does not exists. Skipping the row.';
203            return false;
204        }
205
206        return parent::validateValue($col, $rawvalue);
207    }
208}
209