xref: /dokuwiki/inc/Ui/PageDiff.php (revision f7711f2b85e327b7a52627930dff9288aa2482cf)
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                'current' => true,
69                'rev'  => '',
70                'navTitle' => $this->revisionTitle($changelog->getCurrentRevisionInfo()),
71                'text' => rawWiki($this->id, ''),
72            ];
73
74            // revision info of newer file (right side)
75            $this->newRevInfo = [
76                'date' => null,
77              //'ip'   => '127.0.0.1',
78              //'type' => DOKU_CHANGE_TYPE_CREATE,
79                'id'   => $this->id,
80              //'user' => '',
81              //'sum'  => '',
82              //'extra' => '',
83                'sizechange' => strlen($this->text) - io_getSizeFile(wikiFN($this->id, '')),
84                'timestamp' => false,
85                'current' => false,
86                'rev'  => false,
87                'navTitle' => $lang['yours'],
88                'text' => cleanText($this->text),
89            ];
90        }
91        return $this;
92    }
93
94    /**
95     * Handle requested revision(s) and diff view preferences
96     *
97     * @return void
98     */
99    protected function handle()
100    {
101        global $INPUT;
102
103        // requested rev or rev2
104        if (!isset($this->oldRevInfo, $this->newRevInfo)) {
105            parent::handle();
106        }
107
108        // requested diff view type
109        if ($INPUT->has('difftype')) {
110            $this->preference['difftype'] = $INPUT->str('difftype');
111        } else {
112            // read preference from DokuWiki cookie. PageDiff only
113            $mode = get_doku_pref('difftype', $mode = null);
114            if (isset($mode)) $this->preference['difftype'] = $mode;
115        }
116
117        if (!$INPUT->has('rev') && !$INPUT->has('rev2')) {
118            global $INFO, $REV;
119            if ($this->id == $INFO['id'])
120                $REV = $this->oldRev; // store revision back in $REV
121        }
122    }
123
124    /**
125     * Prepare revision info of comparison pair
126     */
127    protected function preProcess()
128    {
129        $changelog =& $this->changelog;
130
131        // revision info of older file (left side)
132        $this->oldRevInfo = $changelog->getRevisionInfo($this->oldRev);
133        // revision info of newer file (right side)
134        $this->newRevInfo = $changelog->getRevisionInfo($this->newRev);
135
136        foreach ([&$this->oldRevInfo, &$this->newRevInfo] as &$revInfo) {
137            // use timestamp and '' properly as $rev for the current file
138            $isCurrent = $changelog->isCurrentRevision($revInfo['date']);
139            $revInfo += [
140                'current' => $isCurrent,
141                'rev'     => $isCurrent ? '' : $revInfo['date'],
142            ];
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, $revInfo['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        // revision info may have timestamp key when external edits occurred
267        $info['timestamp'] = $info['timestamp'] ?? true;
268
269        if (isset($info['date'])) {
270            $rev = $info['date'];
271            if ($info['timestamp'] === false) {
272                // exteranlly deleted or older file restored
273                $title = '<bdi><a class="wikilink2" href="'.wl($this->id).'">'
274                   . $this->id .' ['. $lang['unknowndate'] .']'.'</a></bdi>';
275            } else {
276                $title = '<bdi><a class="wikilink1" href="'.wl($this->id, ['rev' => $rev]).'">'
277                   . $this->id .' ['. dformat($rev) .']'.'</a></bdi>';
278            }
279        } else {
280            $rev = false;
281            $title = '&mdash;';
282        }
283        if ($info['current']) {
284            $title .= '&nbsp;('.$lang['current'].')';
285        }
286
287        // append separator
288        $title .= ($this->preference['difftype'] === 'inline') ? ' ' : '<br />';
289
290        // supplement
291        if (isset($info['date'])) {
292            $objRevInfo = (new PageRevisions($this->id))->getObjRevInfo($info);
293            $title .= $objRevInfo->editSummary().' '.$objRevInfo->editor();
294        }
295        return $title;
296    }
297
298    /**
299     * Print form to choose diff view type, and exact url reference to the view
300     */
301    protected function showDiffViewSelector()
302    {
303        global $lang;
304
305        // use timestamp for current revision
306        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
307
308        echo '<div class="diffoptions group">';
309
310        // create the form to select difftype
311        $form = new Form(['action' => wl()]);
312        $form->setHiddenField('id', $this->id);
313        $form->setHiddenField('rev2[0]', $oldRev);
314        $form->setHiddenField('rev2[1]', $newRev);
315        $form->setHiddenField('do', 'diff');
316        $options = array(
317                     'sidebyside' => $lang['diff_side'],
318                     'inline' => $lang['diff_inline'],
319        );
320        $input = $form->addDropdown('difftype', $options, $lang['diff_type'])
321            ->val($this->preference['difftype'])
322            ->addClass('quickselect');
323        $input->useInput(false); // inhibit prefillInput() during toHTML() process
324        $form->addButton('do[diff]', 'Go')->attr('type','submit');
325        echo $form->toHTML();
326
327        // show exact url reference to the view when it is meaningful
328        echo '<p>';
329        if ($oldRev && $newRev) {
330            // link to exactly this view FS#2835
331            $viewUrl = $this->diffViewlink('difflink', $oldRev, $newRev);
332        }
333        echo $viewUrl ?? '<br />';
334        echo '</p>';
335
336        echo '</div>'; // .diffoptions
337    }
338
339    /**
340     * Create html for revision navigation
341     *
342     * The navigation consists of older and newer revisions selectors, each
343     * state mutually depends on the selected revision of opposite side.
344     *
345     * @return string[] html of navigation for both older and newer sides
346     */
347    protected function buildRevisionsNavigation()
348    {
349        $changelog =& $this->changelog;
350
351        if ($this->newRevInfo['rev'] === false) {
352            // no revisions selector for PageConflict or PageDraft
353            return array('', '');
354        }
355
356        // use timestamp for current revision
357        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
358
359        // retrieve revisions with additional info
360        [$oldRevs, $newRevs] = $changelog->getRevisionsAround($oldRev, $newRev);
361
362        // build options for dropdown selector
363        $olderRevisions = $this->buildRevisionOptions('older', $oldRevs);
364        $newerRevisions = $this->buildRevisionOptions('newer', $newRevs);
365
366        // determine previous/next revisions
367        $index = array_search($oldRev, $oldRevs);
368        $oldPrevRev = ($index +1 < count($oldRevs)) ? $oldRevs[$index +1] : false;
369        $oldNextRev = ($index > 0)                  ? $oldRevs[$index -1] : false;
370        $index = array_search($newRev, $newRevs);
371        $newPrevRev = ($index +1 < count($newRevs)) ? $newRevs[$index +1] : false;
372        $newNextRev = ($index > 0)                  ? $newRevs[$index -1] : false;
373
374        /*
375         * navigation UI for older revisions / Left side:
376         */
377        $navOlderRevs = '';
378        // move backward both side: ◀◀
379        if ($oldPrevRev && $newPrevRev)
380            $navOlderRevs .= $this->diffViewlink('diffbothprevrev', $oldPrevRev, $newPrevRev);
381        // move backward left side: ◀
382        if ($oldPrevRev)
383            $navOlderRevs .= $this->diffViewlink('diffprevrev', $oldPrevRev, $newRev);
384        // dropdown
385        $navOlderRevs .= $this->buildDropdownSelector('older', $olderRevisions);
386        // move forward left side: ▶
387        if ($oldNextRev && ($oldNextRev < $newRev))
388            $navOlderRevs .= $this->diffViewlink('diffnextrev', $oldNextRev, $newRev);
389
390        /*
391         * navigation UI for newer revisions / Right side:
392         */
393        $navNewerRevs = '';
394        // move backward right side: ◀
395        if ($newPrevRev && ($oldRev < $newPrevRev))
396            $navNewerRevs .= $this->diffViewlink('diffprevrev', $oldRev, $newPrevRev);
397        // dropdown
398        $navNewerRevs .= $this->buildDropdownSelector('newer', $newerRevisions);
399        // move forward right side: ▶
400        if ($newNextRev) {
401            if ($changelog->isCurrentRevision($newNextRev)) {
402                $navNewerRevs .= $this->diffViewlink('difflastrev', $oldRev, $newNextRev);
403            } else {
404                $navNewerRevs .= $this->diffViewlink('diffnextrev', $oldRev, $newNextRev);
405            }
406        }
407        // move forward both side: ▶▶
408        if ($oldNextRev && $newNextRev)
409            $navNewerRevs .= $this->diffViewlink('diffbothnextrev', $oldNextRev, $newNextRev);
410
411        return array($navOlderRevs, $navNewerRevs);
412    }
413
414    /**
415     * prepare options for dropdwon selector
416     *
417     * @params string $side  "older" or "newer"
418     * @params array $revs  list of revsion
419     * @return array
420     */
421    protected function buildRevisionOptions($side, $revs)
422    {
423        global $lang;
424        $changelog =& $this->changelog;
425        $revisions = array();
426
427        // use timestamp for current revision
428        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
429
430        foreach ($revs as $rev) {
431            $info = $changelog->getRevisionInfo($rev);
432            // revision info may have timestamp key when external edits occurred
433            $info['timestamp'] = $info['timestamp'] ?? true;
434            $date = dformat($info['date']);
435            if ($info['timestamp'] === false) {
436                // exteranlly deleted or older file restored
437                $date = preg_replace('/[0-9a-zA-Z]/','_', $date);
438            }
439            $revisions[$rev] = array(
440                'label' => implode(' ', [
441                            $date,
442                            editorinfo($info['user'], true),
443                            $info['sum'],
444                           ]),
445                'attrs' => ['title' => $rev],
446            );
447            if (($side == 'older' && ($newRev && $rev >= $newRev))
448              ||($side == 'newer' && ($rev <= $oldRev))
449            ) {
450                $revisions[$rev]['attrs']['disabled'] = 'disabled';
451            }
452        }
453        return $revisions;
454    }
455
456    /**
457     * build Dropdown form for revisions navigation
458     *
459     * @params string $side  "older" or "newer"
460     * @params array $options  dropdown options
461     * @return string
462     */
463    protected function buildDropdownSelector($side, $options)
464    {
465        $form = new Form(['action' => wl($this->id)]);
466        $form->setHiddenField('id', $this->id);
467        $form->setHiddenField('do', 'diff');
468        $form->setHiddenField('difftype', $this->preference['difftype']);
469
470        // use timestamp for current revision
471        [$oldRev, $newRev] = [(int)$this->oldRevInfo['date'], (int)$this->newRevInfo['date']];
472
473        switch ($side) {
474            case 'older': // left side
475                $form->setHiddenField('rev2[1]', $newRev);
476                $input = $form->addDropdown('rev2[0]', $options)
477                    ->val($oldRev)->addClass('quickselect');
478                $input->useInput(false); // inhibit prefillInput() during toHTML() process
479                break;
480            case 'newer': // right side
481                $form->setHiddenField('rev2[0]', $oldRev);
482                $input = $form->addDropdown('rev2[1]', $options)
483                    ->val($newRev)->addClass('quickselect');
484                $input->useInput(false); // inhibit prefillInput() during toHTML() process
485                break;
486        }
487        $form->addButton('do[diff]', 'Go')->attr('type','submit');
488        return $form->toHTML();
489    }
490
491    /**
492     * Create html link to a diff view defined by two revisions
493     *
494     * @param string $linktype
495     * @param int $oldRev older revision
496     * @param int $newRev newer revision or null for diff with current revision
497     * @return string html of link to a diff view
498     */
499    protected function diffViewlink($linktype, $oldRev, $newRev = null)
500    {
501        global $lang;
502        if ($newRev === null) {
503            $urlparam = array(
504                'do' => 'diff',
505                'rev' => $oldRev,
506                'difftype' => $this->preference['difftype'],
507            );
508        } else {
509            $urlparam = array(
510                'do' => 'diff',
511                'rev2[0]' => $oldRev,
512                'rev2[1]' => $newRev,
513                'difftype' => $this->preference['difftype'],
514            );
515        }
516        $attr = array(
517            'class' => $linktype,
518            'href'  => wl($this->id, $urlparam, true, '&'),
519            'title' => $lang[$linktype],
520        );
521        return '<a '. buildAttributes($attr) .'><span>'. $lang[$linktype] .'</span></a>';
522    }
523
524
525    /**
526     * Insert soft breaks in diff html
527     *
528     * @param string $diffhtml
529     * @return string
530     */
531    public function insertSoftbreaks($diffhtml)
532    {
533        // search the diff html string for both:
534        // - html tags, so these can be ignored
535        // - long strings of characters without breaking characters
536        return preg_replace_callback('/<[^>]*>|[^<> ]{12,}/', function ($match) {
537            // if match is an html tag, return it intact
538            if ($match[0][0] == '<') return $match[0];
539            // its a long string without a breaking character,
540            // make certain characters into breaking characters by inserting a
541            // word break opportunity (<wbr> tag) in front of them.
542            $regex = <<< REGEX
543(?(?=              # start a conditional expression with a positive look ahead ...
544&\#?\\w{1,6};)     # ... for html entities - we don't want to split them (ok to catch some invalid combinations)
545&\#?\\w{1,6};      # yes pattern - a quicker match for the html entity, since we know we have one
546|
547[?/,&\#;:]         # no pattern - any other group of 'special' characters to insert a breaking character after
548)+                 # end conditional expression
549REGEX;
550            return preg_replace('<'.$regex.'>xu', '\0<wbr>', $match[0]);
551        }, $diffhtml);
552    }
553
554}
555