Failed Conditions
Pull Request — master (#3361)
by
unknown
02:55
created

MediaDiff   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 313
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
dl 0
loc 313
rs 8.4
c 0
b 0
f 0
wmc 50
lcom 1
cbo 8

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A setChangeLog() 0 4 1
A preProcess() 0 10 3
F show() 0 78 20
A showDiffViewSelector() 0 20 3
A showImageDiff() 0 29 4
C showFileDiff() 0 78 11
B revisionTitle() 0 26 7

How to fix   Complexity   

Complex Class

Complex classes like MediaDiff often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MediaDiff, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace dokuwiki\Ui;
4
5
use dokuwiki\ChangeLog\MediaChangeLog;
6
use dokuwiki\Extension\Event;
7
use dokuwiki\Form\Form;
8
9
/**
10
 * DokuWiki MediaDiff Interface
11
 *
12
 * @package dokuwiki\Ui
13
 */
14
class MediaDiff extends Diff
15
{
16
    /**
17
     * MediaDiff Ui constructor
18
     *
19
     * @param string $id  media id
20
     */
21
    public function __construct($id)
22
    {
23
        $this->id = $id;
24
        $this->item = 'media';
25
26
        // init preference
27
        $this->preference['fromAjax'] = false; // see doluwiki\Ajax::callMediadiff()
28
        $this->preference['showIntro'] = false;
29
        $this->preference['difftype'] = 'both';  // media diff view type: both, opacity or portions
30
31
        $this->setChangeLog();
32
    }
33
34
    /** @inheritdoc */
35
    protected function setChangeLog()
36
    {
37
        $this->changelog = new MediaChangeLog($this->id);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \dokuwiki\ChangeLog\MediaChangeLog($this->id) of type object<dokuwiki\ChangeLog\MediaChangeLog> is incompatible with the declared type object<dokuwiki\Ui\ChangeLog> of property $changelog.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
38
    }
39
40
    /** @inheritdoc */
41
    protected function preProcess()
42
    {
43
        parent::preProcess();
44
        if (!isset($this->oldRev, $this->newRev)) {
45
            // no revision was given, compare previous to current
46
            $revs = $this->changelog->getRevisions(0, 1);
47
            $this->oldRev = file_exists(mediaFN($this->id, $revs[0])) ? $revs[0] : '';
48
            $this->newRev = '';
49
        }
50
    }
51
52
    /**
53
     * Shows difference between two revisions of media
54
     *
55
     * @author Kate Arzamastseva <[email protected]>
56
     */
57
    public function show()
58
    {
59
        global $conf;
60
61
        $ns = getNS($this->id);
62
        $auth = auth_quickaclcheck("$ns:*");
63
64
        if ($auth < AUTH_READ || !$this->id || !$conf['mediarevisions']) return '';
65
66
       // determine left and right revision
67
        if (!isset($this->oldRev, $this->newRev)) $this->preProcess();
68
        [$oldRev, $newRev] = [$this->oldRev, $this->newRev];
0 ignored issues
show
Bug introduced by
The variable $oldRev seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Bug introduced by
The variable $newRev seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
69
70
        // prepare event data
71
        // NOTE: MEDIA_DIFF event does not found in DokuWiki Event List?
72
        $data = array();
73
        $data[0] = $this->id;
74
        $data[1] = $oldRev;
0 ignored issues
show
Bug introduced by
The variable $oldRev seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
75
        $data[2] = $newRev;
0 ignored issues
show
Bug introduced by
The variable $newRev seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
76
        $data[3] = $ns;
77
        $data[4] = $auth; // permission level
78
        $data[5] = $this->preference['fromAjax'];
79
80
        // trigger event
81
        Event::createAndTrigger('MEDIA_DIFF', $data, null, false);
82
83
        if (is_array($data) && count($data) === 6) {
84
            $this->id = $data[0];
85
            $oldRev = $data[1];
86
            $newRev = $data[2];
87
            $ns     = $data[3];
0 ignored issues
show
Unused Code introduced by
$ns is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
88
            $auth   = $data[4];
89
            $this->preference['fromAjax'] = $data[5];
90
        } else {
91
            return '';
92
        }
93
94
        $oldRevMeta = new \JpegMeta(mediaFN($this->id, $oldRev));
95
        $newRevMeta = new \JpegMeta(mediaFN($this->id, $newRev));
96
97
        $is_img = preg_match('/\.(jpe?g|gif|png)$/', $this->id);
98
        if ($is_img) {
99
            // get image width and height for the mediamanager preview panel
100
            $oldRevSize = media_image_preview_size($this->id, $oldRev, $oldRevMeta);
101
            $newRevSize = media_image_preview_size($this->id, $newRev, $newRevMeta);
102
            // re-check image, ensure minimum image width for showImageDiff()
103
            $is_img = ($oldRevSize && $newRevSize && ($oldRevSize[0] >= 30 || $newRevSize[0] >= 30));
104
        }
105
106
        // determine requested diff view type
107
        if (!$is_img) {
108
            $this->preference['difftype'] = 'both';
109
        }
110
111
        // display intro
112
        if ($this->preference['showIntro']) echo p_locale_xhtml('diff');
113
114
        // print form to choose diff view type
115
        if ($is_img && !$this->preference['fromAjax']) {
116
            $this->showDiffViewSelector();
117
            echo '<div id="mediamanager__diff" >';
118
        }
119
120
        switch ($this->preference['difftype']) {
121
            case 'opacity':
122
            case 'portions':
123
                $this->showImageDiff($oldRev, $newRev, $oldRevSize, $newRevSize, $difftype);
0 ignored issues
show
Bug introduced by
The variable $oldRevSize does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $newRevSize does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $difftype does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Security Bug introduced by
It seems like $oldRevSize defined by media_image_preview_size..., $oldRev, $oldRevMeta) on line 100 can also be of type false; however, dokuwiki\Ui\MediaDiff::showImageDiff() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
Security Bug introduced by
It seems like $newRevSize defined by media_image_preview_size..., $newRev, $newRevMeta) on line 101 can also be of type false; however, dokuwiki\Ui\MediaDiff::showImageDiff() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
124
                break;
125
            case 'both':
126
            default:
127
                $this->showFileDiff($oldRev, $newRev, $oldRevMeta, $newRevMeta, $auth);
0 ignored issues
show
Documentation introduced by
$oldRevMeta is of type object<JpegMeta>, but the function expects a object<dokuwiki\Ui\JpegMeta>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$newRevMeta is of type object<JpegMeta>, but the function expects a object<dokuwiki\Ui\JpegMeta>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
128
                break;
129
        }
130
131
        if ($is_img && !$this->preference['fromAjax']) {
132
            echo '</div>';
133
        }
134
    }
135
136
    /**
137
     * Print form to choose diff view type
138
     * the dropdown is to be added through JavaScript, see lib/scripts/media.js
139
     */
140
    protected function showDiffViewSelector()
141
    {
142
        echo '<div class="diffoptions group">';
143
144
        $form = new Form([
145
            'id' => 'mediamanager__form_diffview',
146
            'action' => media_managerURL([], '&'),
147
            'method' => 'get',
148
            'class' => 'diffView',
149
        ]);
150
        $form->addTagOpen('div')->addClass('no');
151
        $form->setHiddenField('sectok', null);
152
        $form->setHiddenField('mediado', 'diff');
153
        $form->setHiddenField('rev2[0]', $this->oldRev ?: 'current');
154
        $form->setHiddenField('rev2[1]', $this->newRev ?: 'current');
155
        $form->addTagClose('div');
156
        echo $form->toHTML();
157
158
        echo '</div>'; // .diffoptions
159
    }
160
161
    /**
162
     * Prints two images side by side
163
     * and slider
164
     *
165
     * @author Kate Arzamastseva <[email protected]>
166
     *
167
     * @param string|int $oldRev revision timestamp, or empty string
168
     * @param string|int $newRev revision timestamp, or empty string
169
     * @param array  $oldRevSize  array with width and height
170
     * @param array  $newRevSize  array with width and height
171
     * @param string $type    diff view type: opacity or portions
172
     */
173
    protected function showImageDiff($oldRev, $newRev, $oldRevSize, $newRevSize, $type = null)
174
    {
175
        if (!isset($type)) {
176
            $type = $this->preference['difftype'];
177
        }
178
179
        // adjust image width, right side (newer) has priority
180
        if ($oldRevSize != $newRevSize) {
181
            if ($newRevSize[0] > $oldRevSize[0]) {
182
                $oldRevSize = $newRevSize;
183
            }
184
        }
185
186
        $oldRevSrc = ml($this->id, ['rev' => $oldRev, 'h' => $oldRevSize[1], 'w' => $oldRevSize[0]]);
187
        $newRevSrc = ml($this->id, ['rev' => $newRev, 'h' => $oldRevSize[1], 'w' => $oldRevSize[0]]);
188
189
        // slider
190
        echo '<div class="slider" style="max-width: '.($oldRevSize[0]-20).'px;" ></div>';
191
192
        // two images in divs
193
        echo '<div class="imageDiff '.$type.'">';
194
        echo '<div class="image1" style="max-width: '.$oldRevSize[0].'px;">';
195
        echo '<img src="'.$oldRevSrc.'" alt="" />';
196
        echo '</div>';
197
        echo '<div class="image2" style="max-width: '.$oldRevSize[0].'px;">';
198
        echo '<img src="'.$newRevSrc.'" alt="" />';
199
        echo '</div>';
200
        echo '</div>';
201
    }
202
203
    /**
204
     * Shows difference between two revisions of media file
205
     *
206
     * @author Kate Arzamastseva <[email protected]>
207
     *
208
     * @param string|int $oldRev revision timestamp, or empty string
209
     * @param string|int $newRev revision timestamp, or empty string
210
     * @param JpegMeta $oldRevMeta
211
     * @param JpegMeta $newRevMeta
212
     * @param int $auth permission level
213
     */
214
    protected function showFileDiff($oldRev, $newRev, $oldRevMeta, $newRevMeta, $auth)
215
    {
216
        global $lang;
217
218
        // revison info of older file (left side)
219
        $oldRevInfo = $this->getExtendedRevisionInfo($oldRev);
220
        // revison info of newer file (right side)
221
        $newRevInfo = $this->getExtendedRevisionInfo($newRev);
222
223
        // display diff view table
224
        echo '<div class="table">';
225
        echo '<table>';
226
        echo '<tr>';
227
        echo '<th>'. $this->revisionTitle($oldRevInfo) .'</th>';
228
        echo '<th>'. $this->revisionTitle($newRevInfo) .'</th>';
229
        echo '</tr>';
230
231
        echo '<tr class="image">';
232
        echo '<td>';
233
        media_preview($this->id, $auth, $oldRev, $oldRevMeta); // $auth not used in media_preview()?
234
        echo '</td>';
235
236
        echo '<td>';
237
        media_preview($this->id, $auth, $newRev, $newRevMeta);
238
        echo '</td>';
239
        echo '</tr>';
240
241
        echo '<tr class="actions">';
242
        echo '<td>';
243
        media_preview_buttons($this->id, $auth, $oldRev); // $auth used in media_preview_buttons()
244
        echo '</td>';
245
246
        echo '<td>';
247
        media_preview_buttons($this->id, $auth, $newRev);
248
        echo '</td>';
249
        echo '</tr>';
250
251
        $l_tags = media_file_tags($oldRevMeta);
252
        $r_tags = media_file_tags($newRevMeta);
253
        // FIXME r_tags-only stuff
254
        foreach ($l_tags as $key => $l_tag) {
255
            if ($l_tag['value'] != $r_tags[$key]['value']) {
256
                $r_tags[$key]['highlighted'] = true;
257
                $l_tags[$key]['highlighted'] = true;
258
            } elseif (!$l_tag['value'] || !$r_tags[$key]['value']) {
259
                unset($r_tags[$key]);
260
                unset($l_tags[$key]);
261
            }
262
        }
263
264
        echo '<tr>';
265
        foreach (array($l_tags, $r_tags) as $tags) {
266
            echo '<td>';
267
268
            echo '<dl class="img_tags">';
269
            foreach ($tags as $tag) {
270
                $value = cleanText($tag['value']);
271
                if (!$value) $value = '-';
272
                echo '<dt>'.$lang[$tag['tag'][1]].'</dt>';
273
                echo '<dd>';
274
                if ($tag['highlighted']) echo '<strong>';
275
                if ($tag['tag'][2] == 'date') {
276
                    echo dformat($value);
277
                } else {
278
                    echo hsc($value);
279
                }
280
                if ($tag['highlighted']) echo '</strong>';
281
                echo '</dd>';
282
            }
283
            echo '</dl>';
284
285
            echo '</td>';
286
        }
287
        echo '</tr>';
288
289
        echo '</table>';
290
        echo '</div>';
291
    }
292
293
    /**
294
     * Revision Title for MediaDiff table headline
295
     *
296
     * @param array $info  Revision info structure of a media file
297
     * @return string
298
     */
299
    protected function revisionTitle(array $info)
300
    {
301
        global $lang, $INFO;
302
303
        if (isset($info['date'])) {
304
            $rev = $info['date'];
305
            $title = '<bdi><a class="wikilink1" href="'.ml($this->id, ['rev' => $rev]).'">'
306
                   . dformat($rev).'</a></bdi>';
307
        } else {
308
            $rev = false;
309
            $title = '&mdash;';
310
        }
311
        if (isset($info['current']) || ($rev && $rev == $INFO['currentrev'])) {
312
            $title .= '&nbsp;('.$lang['current'].')';
313
        }
314
315
        // append separator
316
        $title .= ($this->preference['difftype'] === 'inline') ? ' ' : '<br />';
317
318
        // supplement
319
        if (isset($info['date'])) {
320
            $objRevInfo = (new MediaRevisions($this->id))->getObjRevInfo($info);
321
            $title .= $objRevInfo->editSummary().' '.$objRevInfo->editor();
322
        }
323
        return $title;
324
    }
325
326
}
327