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