xref: /dokuwiki/inc/Ui/PageDiff.php (revision 48d75c0057e32072269dab43372c65184dcf6649)
1<?php
2
3namespace dokuwiki\Ui;
4
5use dokuwiki\ChangeLog\PageChangeLog;
6use dokuwiki\Form\Form;
7
8/**
9 * DokuWiki PageDiff Interface
10 *
11 * @package dokuwiki\Ui
12 */
13class PageDiff extends Diff
14{
15    /* @var string */
16    protected $text = '';
17
18    /**
19     * PageDiff Ui constructor
20     *
21     * @param string $id  page id
22     */
23    public function __construct($id = null)
24    {
25        global $INFO;
26        $this->id = isset($id) ? $id : $INFO['id'];
27
28        // init preference
29        $this->preference['showIntro'] = true;
30        $this->preference['difftype'] = 'sidebyside'; // diff view type: inline or sidebyside
31
32        $this->setChangeLog();
33    }
34
35    /** @inheritdoc */
36    protected function setChangeLog()
37    {
38        $this->changelog = new PageChangeLog($this->id);
39    }
40
41    /**
42     * Set text to be compared with most current version
43     * exclusively use of the compare($old, $new) method
44     *
45     * @param string $text
46     * @return $this
47     */
48    public function compareWith($text = null)
49    {
50        if (isset($text)) {
51            $this->text = $text;
52            $this->old_rev = '';
53        }
54        return $this;
55    }
56
57    /** @inheritdoc */
58    protected function preProcess()
59    {
60        parent::preProcess();
61        if (!isset($this->old_rev, $this->new_rev)) {
62            // no revision was given, compare previous to current
63            $this->old_rev = $this->changelog->getRevisions(0, 1)[0];
64            $this->new_rev = '';
65
66            global $INFO, $REV;
67            if ($this->id == $INFO['id'])
68               $REV = $this->old_rev; // store revision back in $REV
69        }
70    }
71
72    /**
73     * Show diff
74     * between current page version and provided $text
75     * or between the revisions provided via GET or POST
76     *
77     * @author Andreas Gohr <andi@splitbrain.org>
78     *
79     * @return void
80     */
81    public function show()
82    {
83        global $INFO;
84
85       // determine left and right revision
86        if (!isset($this->old_rev, $this->new_rev)) $this->preProcess();
87        [$l_rev, $r_rev] = [$this->old_rev, $this->new_rev];
88
89       // determine the last revision, which is usually the timestamp of current page,
90       // however which might be the last revision if the page had removed.
91       if ($this->id == $INFO['id']) {
92           $this->last_rev = $INFO['currentrev'] ?? $INFO['meta']['last_change']['date'] ?? 0;
93       } else {
94           $this->last_rev = $this->changelog->getRevisions(-1, 1)[0] // empty array for removed page
95                           ?: $this->changelog->getRevisions(0, 1)[0];
96       }
97
98       // build html diff view components
99        list(
100            $l_minor, $r_minor,
101            $l_head,  $r_head,
102            $l_text,  $r_text,
103            $l_nav,   $r_nav,
104        ) = $this->buildDiffViewComponents($l_rev, $r_rev);
105
106        // create difference engine object
107        $Difference = new \Diff(explode("\n", $l_text), explode("\n", $r_text));
108
109        // display intro
110        if ($this->preference['showIntro']) echo p_locale_xhtml('diff');
111
112        // print form to choose diff view type, and exact url reference to the view
113        if (!$this->text) {
114            $this->showDiffViewSelector();
115        }
116
117        // display diff view table
118        echo '<div class="table">';
119        echo '<table class="diff diff_'.$this->preference['difftype'] .'">';
120
121        //navigation and header
122        switch ($this->preference['difftype']) {
123            case 'inline':
124                if (!$this->text) {
125                    echo '<tr>'
126                        .'<td class="diff-lineheader">-</td>'
127                        .'<td class="diffnav">'. $l_nav .'</td>'
128                        .'</tr>';
129                    echo '<tr>'
130                        .'<th class="diff-lineheader">-</th>'
131                        .'<th '. $l_minor .'>'. $l_head .'</th>'
132                        .'</tr>';
133                }
134                echo '<tr>'
135                    .'<td class="diff-lineheader">+</td>'
136                    .'<td class="diffnav">'. $r_nav .'</td>'
137                    .'</tr>';
138                echo '<tr>'
139                    .'<th class="diff-lineheader">+</th>'
140                    .'<th '. $r_minor .'>'. $r_head .'</th>'
141                    .'</tr>';
142                // create formatter object
143                $DiffFormatter = new \InlineDiffFormatter();
144                break;
145
146            case 'sidebyside':
147            default:
148                if (!$this->text) {
149                    echo '<tr>'
150                        .'<td colspan="2" class="diffnav">'. $l_nav .'</td>'
151                        .'<td colspan="2" class="diffnav">'. $r_nav .'</td>'
152                        .'</tr>';
153                }
154                echo '<tr>'
155                    .'<th colspan="2" '. $l_minor .'>'. $l_head .'</th>'
156                    .'<th colspan="2" '. $r_minor .'>'. $r_head .'</th>'
157                    .'</tr>';
158                // create formatter object
159                $DiffFormatter = new \TableDiffFormatter();
160                break;
161        }
162
163        // output formatted difference
164        echo $this->insertSoftbreaks($DiffFormatter->format($Difference));
165
166        echo '</table>';
167        echo '</div>';
168    }
169
170    /**
171     * Print form to choose diff view type, and exact url reference to the view
172     */
173    protected function showDiffViewSelector()
174    {
175        global $INFO, $lang;
176
177        echo '<div class="diffoptions group">';
178
179        // create the form to select difftype
180        $form = new Form(['action' => wl()]);
181        $form->setHiddenField('id', $this->id);
182        $form->setHiddenField('rev2[0]', $this->old_rev ?: 'current');
183        $form->setHiddenField('rev2[1]', $this->new_rev ?: 'current');
184        $form->setHiddenField('do', 'diff');
185        $options = array(
186                     'sidebyside' => $lang['diff_side'],
187                     'inline' => $lang['diff_inline']
188        );
189        $input = $form->addDropdown('difftype', $options, $lang['diff_type'])
190            ->val($this->preference['difftype'])
191            ->addClass('quickselect');
192        $input->useInput(false); // inhibit prefillInput() during toHTML() process
193        $form->addButton('do[diff]', 'Go')->attr('type','submit');
194        echo $form->toHTML();
195
196        // show exact url reference to the view
197        if ($this->id == $INFO['id']) {
198            echo '<p>';
199            // link to exactly this view FS#2835
200            echo $this->diffViewlink('difflink', $this->old_rev, ($this->new_rev ?: $this->last_rev));
201            echo '</p>';
202        }
203
204        echo '</div>'; // .diffoptions
205    }
206
207    /**
208     * Build html diff view components
209     *
210     * @param int $l_rev  revision timestamp of left side
211     * @param int $r_rev  revision timestamp of right side
212     * @return array
213     *       $l_minor, $r_minor,  // string  class attributes
214     *       $l_head,  $r_head,   // string  html snippet
215     *       $l_text,  $r_text,   // string  raw wiki text
216     *       $l_nav,   $r_nav,    // string  html snippet
217     */
218    protected function buildDiffViewComponents($l_rev, $r_rev)
219    {
220        global $lang;
221
222        if ($this->text) { // compare text to the most current revision
223            $r_minor = '';
224            $l_head = '<a class="wikilink1" href="'. wl($this->id) .'">'
225                . $this->id .' '. dformat((int) @filemtime(wikiFN($this->id))) .'</a> '
226                . $lang['current'];
227            $l_text = rawWiki($this->id, '');
228
229            $l_minor = '';
230            $r_head = $lang['yours'];
231            $r_text = cleanText($this->text);
232
233        } else {
234            // when both revisions are empty then the page was created just now
235            if (!$l_rev && !$r_rev) {
236                $l_text = '';
237            } else {
238                $l_text = rawWiki($this->id, $l_rev);
239            }
240            $r_text = rawWiki($this->id, $r_rev);
241
242            // get header of diff HTML
243            list(
244                $l_head,  $r_head,
245                $l_minor, $r_minor,
246            ) = $this->buildDiffHead($l_rev, $r_rev);
247        }
248        // build navigation
249        $l_nav = '';
250        $r_nav = '';
251        if (!$this->text) {
252            list($l_nav, $r_nav) = $this->buildDiffNavigation($l_rev, $r_rev);
253        }
254
255        return array(
256            $l_minor, $r_minor,
257            $l_head,  $r_head,
258            $l_text,  $r_text,
259            $l_nav,   $r_nav,
260        );
261    }
262
263    /**
264     * Create html for revision navigation
265     *
266     * @param int           $l_rev   left revision timestamp
267     * @param int           $r_rev   right revision timestamp
268     * @return string[] html of left and right navigation elements
269     */
270    protected function buildDiffNavigation($l_rev, $r_rev)
271    {
272        global $INFO;
273
274        // last timestamp is not in changelog, retrieve timestamp from metadata
275        // note: when page is removed, the metadata timestamp is zero
276        if (!$r_rev) {
277            $r_rev = $this->last_rev;
278        }
279
280        //retrieve revisions with additional info
281        list($l_revs, $r_revs) = $this->changelog->getRevisionsAround($l_rev, $r_rev);
282
283        $l_revisions = array();
284        if (!$l_rev) {
285            //no left revision given, add dummy
286            $l_revisions[0] = array('label' => '', 'attrs' => []);
287        }
288        foreach ($l_revs as $rev) {
289            $info = $this->changelog->getRevisionInfo($rev);
290            $l_revisions[$rev] = array(
291                'label' => implode(' ', array(
292                            dformat($info['date']),
293                            editorinfo($info['user'], true),
294                            $info['sum'],
295                           )),
296                'attrs' => ['title' => $rev],
297            );
298            if ($r_rev ? $rev >= $r_rev : false)
299                $l_revisions[$rev]['attrs']['disabled'] = 'disabled';
300        }
301
302        $r_revisions = array();
303        if (!$r_rev) {
304            //no right revision given, add dummy
305            $r_revisions[0] = array('label' => '', 'attrs' => []);
306        }
307        foreach ($r_revs as $rev) {
308            $info = $this->changelog->getRevisionInfo($rev);
309            $r_revisions[$rev] = array(
310                'label' => implode(' ', array(
311                            dformat($info['date']),
312                            editorinfo($info['user'], true),
313                            $info['sum'],
314                           )),
315                'attrs' => ['title' => $rev],
316            );
317            if ($rev <= $l_rev)
318                $r_revisions[$rev]['attrs']['disabled'] = 'disabled';
319        }
320
321        //determine previous/next revisions
322        $l_index = array_search($l_rev, $l_revs);
323        $l_prev = $l_revs[$l_index + 1];
324        $l_next = $l_revs[$l_index - 1];
325        if ($r_rev) {
326            $r_index = array_search($r_rev, $r_revs);
327            $r_prev = $r_revs[$r_index + 1];
328            $r_next = $r_revs[$r_index - 1];
329        } else {
330            //removed page
331            $r_prev = ($l_next) ? $r_revs[0] : null;
332            $r_next = null;
333        }
334
335        /*
336         * Left side:
337         */
338        $l_nav = '';
339        //move back
340        if ($l_prev) {
341            $l_nav .= $this->diffViewlink('diffbothprevrev', $l_prev, $r_prev);
342            $l_nav .= $this->diffViewlink('diffprevrev', $l_prev, $r_rev);
343        }
344        //dropdown
345        $form = new Form(['action' => wl()]);
346        $form->setHiddenField('id', $this->id);
347        $form->setHiddenField('difftype', $this->preference['difftype']);
348        $form->setHiddenField('rev2[1]', $r_rev ?: 'current');
349        $form->setHiddenField('do', 'diff');
350        $input = $form->addDropdown('rev2[0]', $l_revisions)
351            ->val($l_rev ?: 'current')->addClass('quickselect');
352        $input->useInput(false); // inhibit prefillInput() during toHTML() process
353        $form->addButton('do[diff]', 'Go')->attr('type','submit');
354        $l_nav .= $form->toHTML();
355        //move forward
356        if ($l_next && ($l_next < $r_rev || !$r_rev)) {
357            $l_nav .= $this->diffViewlink('diffnextrev', $l_next, $r_rev);
358        }
359
360        /*
361         * Right side:
362         */
363        $r_nav = '';
364        //move back
365        if ($l_rev < $r_prev) {
366            $r_nav .= $this->diffViewlink('diffprevrev', $l_rev, $r_prev);
367        }
368        //dropdown
369        $form = new Form(['action' => wl()]);
370        $form->setHiddenField('id', $this->id);
371        $form->setHiddenField('rev2[0]', $l_rev ?: 'current');
372        $form->setHiddenField('difftype', $this->preference['difftype']);
373        $form->setHiddenField('do', 'diff');
374        $input = $form->addDropdown('rev2[1]', $r_revisions)
375            ->val($r_rev ?: 'current')->addClass('quickselect');
376        $input->useInput(false); // inhibit prefillInput() during toHTML() process
377        $form->addButton('do[diff]', 'Go')->attr('type','submit');
378        $r_nav .= $form->toHTML();
379        //move forward
380        if ($r_next) {
381            if ($this->changelog->isCurrentRevision($r_next)) {
382                //last revision is diff with current page
383                $r_nav .= $this->diffViewlink('difflastrev', $l_rev);
384            } else {
385                $r_nav .= $this->diffViewlink('diffnextrev', $l_rev, $r_next);
386            }
387            $r_nav .= $this->diffViewlink('diffbothnextrev', $l_next, $r_next);
388        }
389        return array($l_nav, $r_nav);
390    }
391
392    /**
393     * Create html link to a diff view defined by two revisions
394     *
395     * @param string $linktype
396     * @param int $lrev oldest revision
397     * @param int $rrev newest revision or null for diff with current revision
398     * @return string html of link to a diff view
399     */
400    protected function diffViewlink($linktype, $lrev, $rrev = null)
401    {
402        global $lang;
403        if ($rrev === null) {
404            $urlparam = array(
405                'do' => 'diff',
406                'rev' => $lrev,
407                'difftype' => $this->preference['difftype'],
408            );
409        } else {
410            $urlparam = array(
411                'do' => 'diff',
412                'rev2[0]' => $lrev,
413                'rev2[1]' => $rrev,
414                'difftype' => $this->preference['difftype'],
415            );
416        }
417        $attr = array(
418            'class' => $linktype,
419            'href'  => wl($this->id, $urlparam, true, '&'),
420            'title' => $lang[$linktype],
421        );
422        return '<a '. buildAttributes($attr) .'><span>'. $lang[$linktype] .'</span></a>';
423    }
424
425
426    /**
427     * Insert soft breaks in diff html
428     *
429     * @param string $diffhtml
430     * @return string
431     */
432    public function insertSoftbreaks($diffhtml)
433    {
434        // search the diff html string for both:
435        // - html tags, so these can be ignored
436        // - long strings of characters without breaking characters
437        return preg_replace_callback('/<[^>]*>|[^<> ]{12,}/', function ($match) {
438            // if match is an html tag, return it intact
439            if ($match[0][0] == '<') return $match[0];
440            // its a long string without a breaking character,
441            // make certain characters into breaking characters by inserting a
442            // word break opportunity (<wbr> tag) in front of them.
443            $regex = <<< REGEX
444(?(?=              # start a conditional expression with a positive look ahead ...
445&\#?\\w{1,6};)     # ... for html entities - we don't want to split them (ok to catch some invalid combinations)
446&\#?\\w{1,6};      # yes pattern - a quicker match for the html entity, since we know we have one
447|
448[?/,&\#;:]         # no pattern - any other group of 'special' characters to insert a breaking character after
449)+                 # end conditional expression
450REGEX;
451            return preg_replace('<'.$regex.'>xu', '\0<wbr>', $match[0]);
452        }, $diffhtml);
453    }
454
455}
456