xref: /dokuwiki/inc/Ui/PageDiff.php (revision 19b5dd7ee2f494c2bb022e51cb4f97cf782207d6)
1<?php
2
3namespace dokuwiki\Ui;
4
5use dokuwiki\ChangeLog\PageChangeLog;
6use dokuwiki\Form\Form;
7
8/**
9 * DokuWiki PageDiff Interface
10 *
11 * @author Andreas Gohr <andi@splitbrain.org>
12 * @author Satoshi Sahara <sahara.satoshi@gmail.com>
13 * @package dokuwiki\Ui
14 */
15class PageDiff extends Diff
16{
17    /* @var PageChangeLog */
18    protected $changelog;
19
20    /* @var array */
21    protected $oldRevInfo;
22    protected $newRevInfo;
23
24    /* @var string */
25    protected $text;
26
27    /**
28     * PageDiff Ui constructor
29     *
30     * @param string $id  page id
31     */
32    public function __construct($id = null)
33    {
34        global $INFO;
35        if (!isset($id)) $id = $INFO['id'];
36
37        // init preference
38        $this->preference['showIntro'] = true;
39        $this->preference['difftype'] = 'sidebyside'; // diff view type: inline or sidebyside
40
41        parent::__construct($id);
42    }
43
44    /** @inheritdoc */
45    protected function setChangeLog()
46    {
47        $this->changelog = new PageChangeLog($this->id);
48    }
49
50    /**
51     * Set text to be compared with most current version
52     * when it has been externally edited
53     * exclusively use of the compare($old, $new) method
54     *
55     * @param string $text
56     * @return $this
57     */
58    public function compareWith($text = null)
59    {
60        global $lang;
61
62        if (isset($text)) {
63            $this->text = $text;
64            $changelog =& $this->changelog;
65
66            // revision info of older file (left side)
67            $this->oldRevInfo = $changelog->getCurrentRevisionInfo() + [
68                'rev'  => '',
69                'navTitle' => $this->revisionTitle($changelog->getCurrentRevisionInfo()),
70                'text' => rawWiki($this->id, ''),
71            ];
72
73            // revision info of newer file (right side)
74            $this->newRevInfo = [
75                'date' => null,
76              //'ip'   => '127.0.0.1',
77              //'type' => DOKU_CHANGE_TYPE_CREATE,
78                'id'   => $this->id,
79              //'user' => '',
80              //'sum'  => '',
81              //'extra' => '',
82                'sizechange' => strlen($this->text) - io_getSizeFile(wikiFN($this->id, '')),
83                'timestamp' => 'unknown',
84                'rev'  => false,
85                'navTitle' => $lang['yours'],
86                'text' => cleanText($this->text),
87            ];
88        }
89        return $this;
90    }
91
92    /**
93     * Handle requested revision(s) and diff view preferences
94     *
95     * @return void
96     */
97    protected function handle()
98    {
99        global $INPUT;
100
101        // requested rev or rev2
102        if (!isset($this->oldRevInfo, $this->newRevInfo)) {
103            parent::handle();
104        }
105
106        // requested diff view type
107        if ($INPUT->has('difftype')) {
108            $this->preference['difftype'] = $INPUT->str('difftype');
109        } else {
110            // read preference from DokuWiki cookie. PageDiff only
111            $mode = get_doku_pref('difftype', $mode = null);
112            if (isset($mode)) $this->preference['difftype'] = $mode;
113        }
114
115        if (!isset($this->oldRev, $this->newRev)) {
116            // no revision was given, compare previous to current
117            $changelog =& $this->changelog;
118            $this->oldRev = $changelog->getRevisions(0, 1)[0];
119            $this->newRev = $changelog->currentRevision();
120
121            global $INFO, $REV;
122            if ($this->id == $INFO['id'])
123               $REV = $this->oldRev; // store revision back in $REV
124        }
125    }
126
127    /**
128     * Prepare revision info of comparison pair
129     */
130    protected function preProcess()
131    {
132        $changelog =& $this->changelog;
133
134        // revision info of older file (left side)
135        $this->oldRevInfo = $changelog->getRevisionInfo($this->oldRev);
136        // revision info of newer file (right side)
137        $this->newRevInfo = $changelog->getRevisionInfo($this->newRev);
138
139        foreach ([&$this->oldRevInfo, &$this->newRevInfo] as &$revInfo) {
140            // use timestamp and '' properly as $rev for the current file
141            $rev = isset($revInfo['current']) ? '' : $revInfo['date'];
142            $revInfo['rev'] = $rev;
143
144            // headline in the Diff view navigation
145            $revInfo['navTitle'] = $this->revisionTitle($revInfo);
146
147            if ($revInfo['type'] == DOKU_CHANGE_TYPE_DELETE) {
148                //attic stores complete last page version for a deleted page
149                $revInfo['text'] = '';
150            } else {
151                $revInfo['text'] = rawWiki($this->id, $rev);
152            }
153        }
154    }
155
156    /**
157     * Show diff
158     * between current page version and provided $text
159     * or between the revisions provided via GET or POST
160     *
161     * @author Andreas Gohr <andi@splitbrain.org>
162     *
163     * @return void
164     */
165    public function show()
166    {
167        $changelog =& $this->changelog;
168
169        if (!isset($this->oldRevInfo, $this->newRevInfo)) {
170            // retrieve form parameters: rev, rev2, difftype
171            $this->handle();
172            // prepare revision info of comparison pair, except PageConfrict or PageDraft
173            $this->preProcess();
174        }
175
176        // create difference engine object
177        $Difference = new \Diff(
178                explode("\n", $this->oldRevInfo['text']),
179                explode("\n", $this->newRevInfo['text'])
180        );
181
182        // build paired navigation
183        [$navOlderRevisions, $navNewerRevisions] = $this->buildRevisionsNavigation();
184
185        // display intro
186        if ($this->preference['showIntro']) echo p_locale_xhtml('diff');
187
188        // print form to choose diff view type, and exact url reference to the view
189        if ($this->newRevInfo['rev'] !== false) {
190            $this->showDiffViewSelector();
191        }
192
193        // assign minor edit checker to the variable
194        $classEditType = function ($info) {
195            return ($info['type'] === DOKU_CHANGE_TYPE_MINOR_EDIT) ? ' class="minor"' : '';
196        };
197
198        // display diff view table
199        echo '<div class="table">';
200        echo '<table class="diff diff_'.$this->preference['difftype'] .'">';
201
202        //navigation and header
203        switch ($this->preference['difftype']) {
204            case 'inline':
205                if ($this->newRevInfo['rev'] !== false) {
206                    echo '<tr>'
207                        .'<td class="diff-lineheader">-</td>'
208                        .'<td class="diffnav">'. $navOlderRevisions .'</td>'
209                        .'</tr>';
210                    echo '<tr>'
211                        .'<th class="diff-lineheader">-</th>'
212                        .'<th'.$classEditType($this->oldRevInfo).'>'.$this->oldRevInfo['navTitle'].'</th>'
213                        .'</tr>';
214                }
215                echo '<tr>'
216                    .'<td class="diff-lineheader">+</td>'
217                    .'<td class="diffnav">'. $navNewerRevisions .'</td>'
218                    .'</tr>';
219                echo '<tr>'
220                    .'<th class="diff-lineheader">+</th>'
221                    .'<th'.$classEditType($this->newRevInfo).'>'.$this->newRevInfo['navTitle'].'</th>'
222                    .'</tr>';
223                // create formatter object
224                $DiffFormatter = new \InlineDiffFormatter();
225                break;
226
227            case 'sidebyside':
228            default:
229                if ($this->newRevInfo['rev'] !== false) {
230                    echo '<tr>'
231                        .'<td colspan="2" class="diffnav">'. $navOlderRevisions .'</td>'
232                        .'<td colspan="2" class="diffnav">'. $navNewerRevisions .'</td>'
233                        .'</tr>';
234                }
235                echo '<tr>'
236                    .'<th colspan="2"'.$classEditType($this->oldRevInfo).'>'.$this->oldRevInfo['navTitle'].'</th>'
237                    .'<th colspan="2"'.$classEditType($this->newRevInfo).'>'.$this->newRevInfo['navTitle'].'</th>'
238                    .'</tr>';
239                // create formatter object
240                $DiffFormatter = new \TableDiffFormatter();
241                break;
242        }
243
244        // output formatted difference
245        echo $this->insertSoftbreaks($DiffFormatter->format($Difference));
246
247        echo '</table>';
248        echo '</div>';
249    }
250
251    /**
252     * Revision Title for PageDiff table headline
253     *
254     * @param array $info  Revision info structure of a page
255     * @return string
256     */
257    protected function revisionTitle(array $info)
258    {
259        global $lang;
260
261        // use designated title when compare current page source with given text
262        if (array_key_exists('date', $info) && is_null($info['date'])) {
263            return $lang['yours'];
264        }
265
266        if (isset($info['date'])) {
267            $rev = $info['date'];
268            if (($info['timestamp'] ?? '') == 'unknown') {
269                // exteranlly deleted or older file restored
270                $title = '<bdi><a class="wikilink2" href="'.wl($this->id).'">'
271                   . $this->id .' ['. $lang['unknowndate'] .']'.'</a></bdi>';
272            } else {
273                $title = '<bdi><a class="wikilink1" href="'.wl($this->id, ['rev' => $rev]).'">'
274                   . $this->id .' ['. dformat($rev) .']'.'</a></bdi>';
275            }
276        } else {
277            $rev = false;
278            $title = '&mdash;';
279        }
280        if (isset($info['current'])) {
281            $title .= '&nbsp;('.$lang['current'].')';
282        }
283
284        // append separator
285        $title .= ($this->preference['difftype'] === 'inline') ? ' ' : '<br />';
286
287        // supplement
288        if (isset($info['date'])) {
289            $objRevInfo = (new PageRevisions($this->id))->getObjRevInfo($info);
290            $title .= $objRevInfo->editSummary().' '.$objRevInfo->editor();
291        }
292        return $title;
293    }
294
295    /**
296     * Print form to choose diff view type, and exact url reference to the view
297     */
298    protected function showDiffViewSelector()
299    {
300        global $lang;
301
302        // use timestamp for current revision
303        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
304
305        echo '<div class="diffoptions group">';
306
307        // create the form to select difftype
308        $form = new Form(['action' => wl()]);
309        $form->setHiddenField('id', $this->id);
310        $form->setHiddenField('rev2[0]', $oldRev);
311        $form->setHiddenField('rev2[1]', $newRev);
312        $form->setHiddenField('do', 'diff');
313        $options = array(
314                     'sidebyside' => $lang['diff_side'],
315                     'inline' => $lang['diff_inline'],
316        );
317        $input = $form->addDropdown('difftype', $options, $lang['diff_type'])
318            ->val($this->preference['difftype'])
319            ->addClass('quickselect');
320        $input->useInput(false); // inhibit prefillInput() during toHTML() process
321        $form->addButton('do[diff]', 'Go')->attr('type','submit');
322        echo $form->toHTML();
323
324        // show exact url reference to the view when it is meaningful
325        echo '<p>';
326        if ($oldRev && $newRev) {
327            // link to exactly this view FS#2835
328            $viewUrl = $this->diffViewlink('difflink', $oldRev, $newRev);
329        }
330        echo $viewUrl ?? '<br />';
331        echo '</p>';
332
333        echo '</div>'; // .diffoptions
334    }
335
336    /**
337     * Create html for revision navigation
338     *
339     * The navigation consists of older and newer revisions selectors, each
340     * state mutually depends on the selected revision of opposite side.
341     *
342     * @return string[] html of navigation for both older and newer sides
343     */
344    protected function buildRevisionsNavigation()
345    {
346        $changelog =& $this->changelog;
347
348        if ($this->newRevInfo['rev'] === false) {
349            // no revisions selector for PageConflict or PageDraft
350            return array('', '');
351        }
352
353        // use timestamp for current revision
354        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
355
356        // retrieve revisions with additional info
357        [$oldRevs, $newRevs] = $changelog->getRevisionsAround($oldRev, $newRev);
358
359        // build options for dropdown selector
360        $olderRevisions = $this->buildRevisionOptions('older', $oldRevs);
361        $newerRevisions = $this->buildRevisionOptions('newer', $newRevs);
362
363        // determine previous/next revisions
364        $index = array_search($oldRev, $oldRevs);
365        $oldPrevRev = ($index +1 < count($oldRevs)) ? $oldRevs[$index +1] : false;
366        $oldNextRev = ($index > 0)                  ? $oldRevs[$index -1] : false;
367        $index = array_search($newRev, $newRevs);
368        $newPrevRev = ($index +1 < count($newRevs)) ? $newRevs[$index +1] : false;
369        $newNextRev = ($index > 0)                  ? $newRevs[$index -1] : false;
370
371        /*
372         * navigation UI for older revisions / Left side:
373         */
374        $navOlderRevs = '';
375        // move backward both side: ◀◀
376        if ($oldPrevRev && $newPrevRev)
377            $navOlderRevs .= $this->diffViewlink('diffbothprevrev', $oldPrevRev, $newPrevRev);
378        // move backward left side: ◀
379        if ($oldPrevRev)
380            $navOlderRevs .= $this->diffViewlink('diffprevrev', $oldPrevRev, $newRev);
381        // dropdown
382        $navOlderRevs .= $this->buildDropdownSelector('older', $olderRevisions);
383        // move forward left side: ▶
384        if ($oldNextRev && ($oldNextRev < $newRev))
385            $navOlderRevs .= $this->diffViewlink('diffnextrev', $oldNextRev, $newRev);
386
387        /*
388         * navigation UI for newer revisions / Right side:
389         */
390        $navNewerRevs = '';
391        // move backward right side: ◀
392        if ($newPrevRev && ($oldRev < $newPrevRev))
393            $navNewerRevs .= $this->diffViewlink('diffprevrev', $oldRev, $newPrevRev);
394        // dropdown
395        $navNewerRevs .= $this->buildDropdownSelector('newer', $newerRevisions);
396        // move forward right side: ▶
397        if ($newNextRev) {
398            if ($changelog->isCurrentRevision($newNextRev)) {
399                $navNewerRevs .= $this->diffViewlink('difflastrev', $oldRev, $newNextRev);
400            } else {
401                $navNewerRevs .= $this->diffViewlink('diffnextrev', $oldRev, $newNextRev);
402            }
403        }
404        // move forward both side: ▶▶
405        if ($oldNextRev && $newNextRev)
406            $navNewerRevs .= $this->diffViewlink('diffbothnextrev', $oldNextRev, $newNextRev);
407
408        return array($navOlderRevs, $navNewerRevs);
409    }
410
411    /**
412     * prepare options for dropdwon selector
413     *
414     * @params string $side  "older" or "newer"
415     * @params array $revs  list of revsion
416     * @return array
417     */
418    protected function buildRevisionOptions($side, $revs)
419    {
420        global $lang;
421        $changelog =& $this->changelog;
422        $revisions = array();
423
424        // use timestamp for current revision
425        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
426
427        foreach ($revs as $rev) {
428            $info = $changelog->getRevisionInfo($rev);
429            $date = dformat($info['date']);
430            if (($info['timestamp'] ?? '') == 'unknown') {
431                // exteranlly deleted or older file restored
432                $date = preg_replace('/[0-9a-zA-Z]/','_', $date);
433            }
434            $revisions[$rev] = array(
435                'label' => implode(' ', [
436                            $date,
437                            editorinfo($info['user'], true),
438                            $info['sum'],
439                           ]),
440                'attrs' => ['title' => $rev],
441            );
442            if (($side == 'older' && ($newRev && $rev >= $newRev))
443              ||($side == 'newer' && ($rev <= $oldRev))
444            ) {
445                $revisions[$rev]['attrs']['disabled'] = 'disabled';
446            }
447        }
448        return $revisions;
449    }
450
451    /**
452     * build Dropdown form for revisions navigation
453     *
454     * @params string $side  "older" or "newer"
455     * @params array $options  dropdown options
456     * @return string
457     */
458    protected function buildDropdownSelector($side, $options)
459    {
460        $form = new Form(['action' => wl($this->id)]);
461        $form->setHiddenField('id', $this->id);
462        $form->setHiddenField('do', 'diff');
463        $form->setHiddenField('difftype', $this->preference['difftype']);
464
465        // use timestamp for current revision
466        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
467
468        switch ($side) {
469            case 'older': // left side
470                $form->setHiddenField('rev2[1]', $newRev);
471                $input = $form->addDropdown('rev2[0]', $options)
472                    ->val($oldRev)->addClass('quickselect');
473                $input->useInput(false); // inhibit prefillInput() during toHTML() process
474                break;
475            case 'newer': // right side
476                $form->setHiddenField('rev2[0]', $oldRev);
477                $input = $form->addDropdown('rev2[1]', $options)
478                    ->val($newRev)->addClass('quickselect');
479                $input->useInput(false); // inhibit prefillInput() during toHTML() process
480                break;
481        }
482        $form->addButton('do[diff]', 'Go')->attr('type','submit');
483        return $form->toHTML();
484    }
485
486    /**
487     * Create html link to a diff view defined by two revisions
488     *
489     * @param string $linktype
490     * @param int $oldRev older revision
491     * @param int $newRev newer revision or null for diff with current revision
492     * @return string html of link to a diff view
493     */
494    protected function diffViewlink($linktype, $oldRev, $newRev = null)
495    {
496        global $lang;
497        if ($newRev === null) {
498            $urlparam = array(
499                'do' => 'diff',
500                'rev' => $oldRev,
501                'difftype' => $this->preference['difftype'],
502            );
503        } else {
504            $urlparam = array(
505                'do' => 'diff',
506                'rev2[0]' => $oldRev,
507                'rev2[1]' => $newRev,
508                'difftype' => $this->preference['difftype'],
509            );
510        }
511        $attr = array(
512            'class' => $linktype,
513            'href'  => wl($this->id, $urlparam, true, '&'),
514            'title' => $lang[$linktype],
515        );
516        return '<a '. buildAttributes($attr) .'><span>'. $lang[$linktype] .'</span></a>';
517    }
518
519
520    /**
521     * Insert soft breaks in diff html
522     *
523     * @param string $diffhtml
524     * @return string
525     */
526    public function insertSoftbreaks($diffhtml)
527    {
528        // search the diff html string for both:
529        // - html tags, so these can be ignored
530        // - long strings of characters without breaking characters
531        return preg_replace_callback('/<[^>]*>|[^<> ]{12,}/', function ($match) {
532            // if match is an html tag, return it intact
533            if ($match[0][0] == '<') return $match[0];
534            // its a long string without a breaking character,
535            // make certain characters into breaking characters by inserting a
536            // word break opportunity (<wbr> tag) in front of them.
537            $regex = <<< REGEX
538(?(?=              # start a conditional expression with a positive look ahead ...
539&\#?\\w{1,6};)     # ... for html entities - we don't want to split them (ok to catch some invalid combinations)
540&\#?\\w{1,6};      # yes pattern - a quicker match for the html entity, since we know we have one
541|
542[?/,&\#;:]         # no pattern - any other group of 'special' characters to insert a breaking character after
543)+                 # end conditional expression
544REGEX;
545            return preg_replace('<'.$regex.'>xu', '\0<wbr>', $match[0]);
546        }, $diffhtml);
547    }
548
549}
550