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