Completed
Push — master ( 2eb568...ada0c5 )
by Michael
06:46 queued 03:03
created

WfdownloadsUtilities::getCurrentUrls()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 15
c 2
b 0
f 0
nc 4
nop 0
dl 0
loc 20
rs 9.4285
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 29 and the first side effect is on line 22.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
/**
12
 * WfdownloadsUtilities Class
13
 *
14
 * @copyright   XOOPS Project (http://xoops.org)
15
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
16
 * @author      XOOPS Development Team
17
 * @package     Wfdownloads
18
 * @since       1.03
19
 *
20
 */
21
22
include_once dirname(__DIR__) . '/include/common.php';
23
24
//namespace Wfdownloads;
25
26
/**
27
 * Class WfdownloadsUtilities
28
 */
29
class WfdownloadsUtilities
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
30
{
31
    /**
32
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
33
     *
34
     * @param string $folder The full path of the directory to check
35
     *
36
     * @return void
37
     */
38
    public static function createFolder($folder)
39
    {
40
        try {
41
            if (!@mkdir($folder) && !is_dir($folder)) {
42
                throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
43
            } else {
44
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
45
            }
46
        } catch (Exception $e) {
47
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
48
        }
49
    }
50
51
    /**
52
     * @param $file
53
     * @param $folder
54
     * @return bool
55
     */
56
    public static function copyFile($file, $folder)
57
    {
58
        return copy($file, $folder);
59
60
        if (is_file($file)) {
0 ignored issues
show
Unused Code introduced by
if (is_file($file)) { ...e { return false; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
Bug introduced by
The variable $file 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...
61
            return copy($file, $folder);
62
        } else {
63
            return false;
64
        }
65
66
        //        try {
67
        //            if (!is_dir($folder)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
68
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
69
        //            } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
70
        //                return copy($file, $folder);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
71
        //            }
72
        //        } catch (Exception $e) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
73
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
74
        //        }
75
        //        return false;
76
    }
77
78
    /**
79
     * @param $src
80
     * @param $dst
81
     */
82
    public static function recurseCopy($src, $dst)
83
    {
84
        $dir = opendir($src);
85
        //    @mkdir($dst);
86
        while (false !== ($file = readdir($dir))) {
87
            if (($file !== '.') && ($file !== '..')) {
88
                if (is_dir($src . '/' . $file)) {
89
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
90
                } else {
91
                    copy($src . '/' . $file, $dst . '/' . $file);
92
                }
93
            }
94
        }
95
        closedir($dir);
96
    }
97
98
    // auto create folders----------------------------------------
99
    //TODO rename this function? And exclude image folder?
100
    public static function createDir()
101
    {
102
        // auto crate folders
103
        //        $thePath = publisherGetUploadDir();
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
104
105 View Code Duplication
        if (publisherGetPathStatus('root', true) < 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
106
            $thePath = publisherGetUploadDir();
107
            $res     = publisherMkdir($thePath);
108
            $msg     = $res ? _AM_PUBLISHER_DIRCREATED : _AM_PUBLISHER_DIRNOTCREATED;
0 ignored issues
show
Unused Code introduced by
$msg 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...
109
        }
110
111 View Code Duplication
        if (publisherGetPathStatus('images', true) < 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
            $thePath = publisherGetImageDir();
113
            $res     = publisherMkdir($thePath);
114
115
            if ($res) {
116
                $source = PUBLISHER_ROOT_PATH . '/assets/images/blank.png';
117
                $dest   = $thePath . 'blank.png';
118
                publisherCopyr($source, $dest);
119
            }
120
            $msg = $res ? _AM_PUBLISHER_DIRCREATED : _AM_PUBLISHER_DIRNOTCREATED;
0 ignored issues
show
Unused Code introduced by
$msg 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...
121
        }
122
123 View Code Duplication
        if (publisherGetPathStatus('images/category', true) < 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
            $thePath = publisherGetImageDir('category');
125
            $res     = publisherMkdir($thePath);
126
127
            if ($res) {
128
                $source = PUBLISHER_ROOT_PATH . '/assets/images/blank.png';
129
                $dest   = $thePath . 'blank.png';
130
                publisherCopyr($source, $dest);
131
            }
132
            $msg = $res ? _AM_PUBLISHER_DIRCREATED : _AM_PUBLISHER_DIRNOTCREATED;
0 ignored issues
show
Unused Code introduced by
$msg 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...
133
        }
134
135 View Code Duplication
        if (publisherGetPathStatus('images/item', true) < 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
136
            $thePath = publisherGetImageDir('item');
137
            $res     = publisherMkdir($thePath);
138
139
            if ($res) {
140
                $source = PUBLISHER_ROOT_PATH . '/assets/images/blank.png';
141
                $dest   = $thePath . 'blank.png';
142
                publisherCopyr($source, $dest);
143
            }
144
            $msg = $res ? _AM_PUBLISHER_DIRCREATED : _AM_PUBLISHER_DIRNOTCREATED;
0 ignored issues
show
Unused Code introduced by
$msg 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...
145
        }
146
147 View Code Duplication
        if (publisherGetPathStatus('content', true) < 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
            $thePath = publisherGetUploadDir(true, 'content');
149
            $res     = publisherMkdir($thePath);
150
            $msg     = $res ? _AM_PUBLISHER_DIRCREATED : _AM_PUBLISHER_DIRNOTCREATED;
0 ignored issues
show
Unused Code introduced by
$msg 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...
151
        }
152
    }
153
154
    public static function buildTableItemTitleRow()
155
    {
156
        echo "<table width='100%' cellspacing='1' cellpadding='3' border='0' class='outer'>";
157
        echo '<tr>';
158
        echo "<th width='40px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_ITEMID . '</strong></td>';
159
        echo "<th width='100px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_ITEMCAT . '</strong></td>';
160
        echo "<th class='bg3' align='center'><strong>" . _AM_PUBLISHER_TITLE . '</strong></td>';
161
        echo "<th width='100px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_CREATED . '</strong></td>';
162
163
        echo "<th width='50px' class='bg3' align='center'><strong>" . _CO_PUBLISHER_WEIGHT . '</strong></td>';
164
        echo "<th width='50px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_HITS . '</strong></td>';
165
        echo "<th width='60px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_RATE . '</strong></td>';
166
        echo "<th width='50px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_VOTES . '</strong></td>';
167
        echo "<th width='60px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_COMMENTS_COUNT . '</strong></td>';
168
169
        echo "<th width='90px' class='bg3' align='center'><strong>" . _CO_PUBLISHER_STATUS . '</strong></td>';
170
        echo "<th width='90px' class='bg3' align='center'><strong>" . _AM_PUBLISHER_ACTION . '</strong></td>';
171
        echo '</tr>';
172
    }
173
174
    /**
175
     * @param     $categoryObj
176
     * @param int $level
177
     */
178
    public static function displayCategory(WfdownloadsCategory $categoryObj, $level = 0)
179
    {
180
        $publisher = WfdownloadsWfdownloads::getInstance();
181
182
        $description = $categoryObj->description();
183
        if (!XOOPS_USE_MULTIBYTES) {
184
            if (strlen($description) >= 100) {
185
                $description = substr($description, 0, 100 - 1) . '...';
0 ignored issues
show
Unused Code introduced by
$description 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...
186
            }
187
        }
188
        $modify = "<a href='category.php?op=mod&amp;categoryid=" . $categoryObj->categoryid() . '&amp;parentid=' . $categoryObj->parentid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/edit.gif' title='" . _AM_PUBLISHER_EDITCOL . "' alt='" . _AM_PUBLISHER_EDITCOL . "' /></a>";
189
        $delete = "<a href='category.php?op=del&amp;categoryid=" . $categoryObj->categoryid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/delete.png' title='" . _AM_PUBLISHER_DELETECOL . "' alt='" . _AM_PUBLISHER_DELETECOL . "' /></a>";
190
191
        $spaces = '';
192
        for ($j = 0; $j < $level; ++$j) {
193
            $spaces .= '&nbsp;&nbsp;&nbsp;';
194
        }
195
196
        echo '<tr>';
197
        echo "<td class='even' align='center'>" . $categoryObj->categoryid() . '</td>';
198
        echo "<td class='even' align='left'>" . $spaces . "<a href='" . PUBLISHER_URL . '/category.php?categoryid=' . $categoryObj->categoryid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/subcat.gif' alt='' />&nbsp;" . $categoryObj->name() . '</a></td>';
199
        echo "<td class='even' align='center'>" . $categoryObj->weight() . '</td>';
200
        echo "<td class='even' align='center'> $modify $delete </td>";
201
        echo '</tr>';
202
        $subCategoriesObj = $publisher->getHandler('category')->getCategories(0, 0, $categoryObj->categoryid());
203
        if (count($subCategoriesObj) > 0) {
204
            ++$level;
205
            foreach ($subCategoriesObj as $key => $thiscat) {
206
                self::displayCategory($thiscat, $level);
207
            }
208
            unset($key, $thiscat);
209
        }
210
        //        unset($categoryObj);
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
211
    }
212
213
    /**
214
     * @param bool $showmenu
215
     * @param int  $categoryId
216
     * @param int  $nbSubCats
217
     * @param null $categoryObj
218
     */
219
    public static function editCategory($showmenu = false, $categoryId = 0, $nbSubCats = 4, $categoryObj = null)
0 ignored issues
show
Unused Code introduced by
The parameter $showmenu is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
220
    {
221
        $publisher = WfdownloadsWfdownloads::getInstance();
222
223
        // if there is a parameter, and the id exists, retrieve data: we're editing a category
224
        if ($categoryId != 0) {
225
            // Creating the category object for the selected category
226
            $categoryObj = $publisher->getHandler('category')->get($categoryId);
227
            if ($categoryObj->notLoaded()) {
228
                redirect_header('category.php', 1, _AM_PUBLISHER_NOCOLTOEDIT);
229
                //            exit();
230
            }
231
        } else {
232
            if (!$categoryObj) {
233
                $categoryObj = $publisher->getHandler('category')->create();
234
            }
235
        }
236
237
        if ($categoryId != 0) {
238
            echo "<br>\n";
239
            publisherOpenCollapsableBar('edittable', 'edittableicon', _AM_PUBLISHER_EDITCOL, _AM_PUBLISHER_CATEGORY_EDIT_INFO);
240
        } else {
241
            publisherOpenCollapsableBar('createtable', 'createtableicon', _AM_PUBLISHER_CATEGORY_CREATE, _AM_PUBLISHER_CATEGORY_CREATE_INFO);
242
        }
243
244
        $sform = $categoryObj->getForm($nbSubCats);
245
        $sform->display();
246
247
        if (!$categoryId) {
248
            publisherCloseCollapsableBar('createtable', 'createtableicon');
249
        } else {
250
            publisherCloseCollapsableBar('edittable', 'edittableicon');
251
        }
252
253
        //Added by fx2024
254
        if ($categoryId) {
255
            $selCat = $categoryId;
256
257
            publisherOpenCollapsableBar('subcatstable', 'subcatsicon', _AM_PUBLISHER_SUBCAT_CAT, _AM_PUBLISHER_SUBCAT_CAT_DSC);
258
            // Get the total number of sub-categories
259
            $categoriesObj = $publisher->getHandler('category')->get($selCat);
260
            $totalsubs     = $publisher->getHandler('category')->getCategoriesCount($selCat);
261
            // creating the categories objects that are published
262
            $subcatsObj    = $publisher->getHandler('category')->getCategories(0, 0, $categoriesObj->categoryid());
263
            $totalSCOnPage = count($subcatsObj);
0 ignored issues
show
Unused Code introduced by
$totalSCOnPage 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...
264
            echo "<table width='100%' cellspacing=1 cellpadding=3 border=0 class = outer>";
265
            echo '<tr>';
266
            echo "<td width='60' class='bg3' align='left'><strong>" . _AM_PUBLISHER_CATID . '</strong></td>';
267
            echo "<td width='20%' class='bg3' align='left'><strong>" . _AM_PUBLISHER_CATCOLNAME . '</strong></td>';
268
            echo "<td class='bg3' align='left'><strong>" . _AM_PUBLISHER_SUBDESCRIPT . '</strong></td>';
269
            echo "<td width='60' class='bg3' align='right'><strong>" . _AM_PUBLISHER_ACTION . '</strong></td>';
270
            echo '</tr>';
271
            if ($totalsubs > 0) {
272
                foreach ($subcatsObj as $subcat) {
273
                    $modify = "<a href='category.php?op=mod&amp;categoryid=" . $subcat->categoryid() . "'><img src='" . XOOPS_URL . '/modules/' . $publisher->getModule()->dirname() . "/assets/images/links/edit.gif' title='" . _AM_PUBLISHER_MODIFY . "' alt='" . _AM_PUBLISHER_MODIFY . "' /></a>";
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $publisher->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
274
                    $delete = "<a href='category.php?op=del&amp;categoryid=" . $subcat->categoryid() . "'><img src='" . XOOPS_URL . '/modules/' . $publisher->getModule()->dirname() . "/assets/images/links/delete.png' title='" . _AM_PUBLISHER_DELETE . "' alt='" . _AM_PUBLISHER_DELETE . "' /></a>";
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $publisher->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
275
                    echo '<tr>';
276
                    echo "<td class='head' align='left'>" . $subcat->categoryid() . '</td>';
277
                    echo "<td class='even' align='left'><a href='" . XOOPS_URL . '/modules/' . $publisher->getModule()->dirname() . '/category.php?categoryid=' . $subcat->categoryid() . '&amp;parentid=' . $subcat->parentid() . "'>" . $subcat->name() . '</a></td>';
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $publisher->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
278
                    echo "<td class='even' align='left'>" . $subcat->description() . '</td>';
279
                    echo "<td class='even' align='right'> {$modify} {$delete} </td>";
280
                    echo '</tr>';
281
                }
282
                //                unset($subcat);
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
283
            } else {
284
                echo '<tr>';
285
                echo "<td class='head' align='center' colspan= '7'>" . _AM_PUBLISHER_NOSUBCAT . '</td>';
286
                echo '</tr>';
287
            }
288
            echo "</table>\n";
289
            echo "<br>\n";
290
            publisherCloseCollapsableBar('subcatstable', 'subcatsicon');
291
292
            publisherOpenCollapsableBar('bottomtable', 'bottomtableicon', _AM_PUBLISHER_CAT_ITEMS, _AM_PUBLISHER_CAT_ITEMS_DSC);
293
            $startitem = XoopsRequest::getInt('startitem');
294
            // Get the total number of published ITEMS
295
            $totalitems = $publisher->getHandler('item')->getItemsCount($selCat, array(WfdownloadsConstants::PUBLISHER_STATUS_PUBLISHED));
296
            // creating the items objects that are published
297
            $itemsObj         = $publisher->getHandler('item')->getAllPublished($publisher->getConfig('idxcat_perpage'), $startitem, $selCat);
298
            $totalitemsOnPage = count($itemsObj);
299
            $allcats          = $publisher->getHandler('category')->getObjects(null, true);
300
            echo "<table width='100%' cellspacing=1 cellpadding=3 border=0 class = outer>";
301
            echo '<tr>';
302
            echo "<td width='40' class='bg3' align='center'><strong>" . _AM_PUBLISHER_ITEMID . '</strong></td>';
303
            echo "<td width='20%' class='bg3' align='left'><strong>" . _AM_PUBLISHER_ITEMCOLNAME . '</strong></td>';
304
            echo "<td class='bg3' align='left'><strong>" . _AM_PUBLISHER_ITEMDESC . '</strong></td>';
305
            echo "<td width='90' class='bg3' align='center'><strong>" . _AM_PUBLISHER_CREATED . '</strong></td>';
306
            echo "<td width='60' class='bg3' align='center'><strong>" . _AM_PUBLISHER_ACTION . '</strong></td>';
307
            echo '</tr>';
308
            if ($totalitems > 0) {
309
                for ($i = 0; $i < $totalitemsOnPage; ++$i) {
310
                    $categoryObj = $allcats[$itemsObj[$i]->categoryid()];
311
                    $modify      = "<a href='item.php?op=mod&amp;itemid=" . $itemsObj[$i]->itemid() . "'><img src='" . XOOPS_URL . '/modules/' . $publisher->getModule()->dirname() . "/assets/images/links/edit.gif' title='" . _AM_PUBLISHER_EDITITEM . "' alt='" . _AM_PUBLISHER_EDITITEM . "' /></a>";
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $publisher->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
312
                    $delete      =
313
                        "<a href='item.php?op=del&amp;itemid=" . $itemsObj[$i]->itemid() . "'><img src='" . XOOPS_URL . '/modules/' . $publisher->getModule()->dirname() . "/assets/images/links/delete.png' title='" . _AM_PUBLISHER_DELETEITEM . "' alt='" . _AM_PUBLISHER_DELETEITEM . "'/></a>";
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $publisher->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
314
                    echo '<tr>';
315
                    echo "<td class='head' align='center'>" . $itemsObj[$i]->itemid() . '</td>';
316
                    echo "<td class='even' align='left'>" . $categoryObj->name() . '</td>';
317
                    echo "<td class='even' align='left'>" . $itemsObj[$i]->getitemLink() . '</td>';
318
                    echo "<td class='even' align='center'>" . $itemsObj[$i]->getDatesub('s') . '</td>';
319
                    echo "<td class='even' align='center'> $modify $delete </td>";
320
                    echo '</tr>';
321
                }
322
            } else {
323
                $itemid = -1;
0 ignored issues
show
Unused Code introduced by
$itemid 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...
324
                echo '<tr>';
325
                echo "<td class='head' align='center' colspan= '7'>" . _AM_PUBLISHER_NOITEMS . '</td>';
326
                echo '</tr>';
327
            }
328
            echo "</table>\n";
329
            echo "<br>\n";
330
            $parentid         = XoopsRequest::getInt('parentid', 0, 'GET');
331
            $pagenavExtraArgs = "op=mod&categoryid=$selCat&parentid=$parentid";
332
            xoops_load('XoopsPageNav');
333
            $pagenav = new XoopsPageNav($totalitems, $publisher->getConfig('idxcat_perpage'), $startitem, 'startitem', $pagenavExtraArgs);
334
            echo '<div style="text-align:right;">' . $pagenav->renderNav() . '</div>';
335
            echo "<input type='button' name='button' onclick=\"location='item.php?op=mod&categoryid=" . $selCat . "'\" value='" . _AM_PUBLISHER_CREATEITEM . "'>&nbsp;&nbsp;";
336
            echo '</div>';
337
        }
338
        //end of fx2024 code
339
    }
340
341
    // ====================== START ===================================
342
343
    /**
344
     *
345
     * Standard functions
346
     *
347
     */
348
349
    /**
350
     * This function transforms a numerical size (like 2048) to a letteral size (like 2MB)
351
     *
352
     * @param integer $bytes     numerical size
353
     * @param integer $precision
354
     *
355
     * @return string letteral size
356
     **/
357 View Code Duplication
    public static function bytesToSize1000($bytes, $precision = 2)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
358
    {
359
        // human readable format -- powers of 1000
360
        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb');
361
362
        return @round($bytes / pow(1000, $i = floor(log($bytes, 1000))), $precision) . ' ' . $unit[(int)$i];
363
    }
364
365
    /**
366
     * @param     $bytes
367
     * @param int $precision
368
     *
369
     * @return string
370
     */
371 View Code Duplication
    public static function bytesToSize1024($bytes, $precision = 2)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
372
    {
373
        // human readable format -- powers of 1024
374
        $unit = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB');
375
376
        return @round($bytes / pow(1024, $i = floor(log($bytes, 1024))), $precision) . ' ' . $unit[(int)$i];
377
    }
378
379
    /**
380
     * This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)
381
     *
382
     * @param string $size letteral size
383
     *
384
     * @return integer numerical size
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
385
     **/
386
    public static function sizeToBytes1024($size)
387
    {
388
        $l   = substr($size, -1);
389
        $ret = substr($size, 0, -1);
390
        switch (strtoupper($l)) {
391
            case 'P':
392
            case 'p':
393
                $ret *= 1024;
394
                break;
395
            case 'T':
396
            case 't':
397
                $ret *= 1024;
398
                break;
399
            case 'G':
400
            case 'g':
401
                $ret *= 1024;
402
                break;
403
            case 'M':
404
            case 'm':
405
                $ret *= 1024;
406
                break;
407
            case 'K':
408
            case 'k':
409
                $ret *= 1024;
410
                break;
411
        }
412
413
        return $ret;
414
    }
415
416
    /**
417
     *
418
     * Filesystem functions
419
     *
420
     */
421
422
    /**
423
     * This function will read the full structure of a directory.
424
     * It's recursive because it doesn't stop with the one directory,
425
     * it just keeps going through all of the directories in the folder you specify.
426
     *
427
     * @param string $path  path to the directory to make
428
     * @param int    $level
429
     *
430
     * @return array
431
     */
432
    public static function getDir($path = '.', $level = 0)
433
    {
434
        $ret    = array();
435
        $ignore = array('cgi-bin', '.', '..');
436
        // Directories to ignore when listing output. Many hosts will deny PHP access to the cgi-bin.
437
        $dirHandler = @opendir($path);
438
        // Open the directory to the handle $dirHandler
439
        while (false !== ($file = readdir($dirHandler))) {
440
            // Loop through the directory
441
            if (!in_array($file, $ignore)) {
442
                // Check that this file is not to be ignored
443
                $spaces = str_repeat('&nbsp;', $level * 4);
444
                // Just to add spacing to the list, to better show the directory tree.
445
                if (is_dir("$path/$file")) {
446
                    // Its a directory, so we need to keep reading down...
447
                    $ret[] = "<strong>{$spaces} {$file}</strong>";
448
                    $ret   = array_merge($ret, self::getDir($path . DIRECTORY_SEPARATOR . $file, $level + 1));
449
                    // Re-call this same function but on a new directory.
450
                    // this is what makes function recursive.
451
                } else {
452
                    $ret[] = "{$spaces} {$file}";
453
                    // Just print out the filename
454
                }
455
            }
456
        }
457
        closedir($dirHandler);
458
        // close the directory handle
459
        return $ret;
460
    }
461
462
    /**
463
     * Create a new directory that contains the file index.html
464
     *
465
     * @param string $dir          path to the directory to make
466
     * @param int    $perm         mode
467
     * @param bool   $create_index if true create index.html
468
     *
469
     * @return bool Returns true on success or false on failure
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
470
     */
471
    public static function makeDir($dir, $perm = 0777, $create_index = true)
472
    {
473
        if (!is_dir($dir)) {
474
            if (!@mkdir($dir, $perm)) {
475
                return false;
476
            } else {
477
                if ($create_index) {
478
                    if (false !== ($fileHandler = @fopen($dir . '/index.html', 'w'))) {
479
                        fwrite($fileHandler, '<script>history.go(-1);</script>');
480
                    }
481
                    @fclose($fileHandler);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
482
                }
483
484
                return true;
485
            }
486
        }
487
488
        return null;
489
    }
490
491
    /**
492
     * @param string $path
493
     *
494
     * @return array
495
     */
496
    public static function getFiles($path = '.')
497
    {
498
        $files = array();
499
        $dir   = opendir($path);
500
        while (false !== ($file = readdir($dir))) {
501
            if (is_file($path . $file)) {
502
                if ($file !== '.' && $file !== '..' && $file !== 'blank.gif' && $file !== 'index.html') {
503
                    $files[] = $file;
504
                }
505
            }
506
        }
507
508
        return $files;
509
    }
510
511
    /**
512
     * Copy a file
513
     *
514
     * @param string $source      is the original directory
515
     * @param string $destination is the destination directory
516
     *
517
     * @return bool Returns true on success or false on failure
518
     *
519
     */
520
    /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
521
    public static function copyFile($source, $destination)
522
    {
523
        // Simple copy for a file
524
        if (is_file($source)) {
525
            return copy($source, $destination);
526
        } else {
527
            return false;
528
        }
529
    }
530
    */
531
532
    /**
533
     * Copy a directory and its contents
534
     *
535
     * @param string $source      is the original directory
536
     * @param string $destination is the destination directory
537
     *
538
     * @return bool Returns true on success or false on failure
539
     *
540
     */
541
    public static function copyDir($source, $destination)
542
    {
543
        if (!$dirHandler = opendir($source)) {
544
            return false;
545
        }
546
        @mkdir($destination);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
547
        while (false !== ($file = readdir($dirHandler))) {
548
            if (($file !== '.') && ($file !== '..')) {
549
                if (is_dir("{$source}/{$file}")) {
550
                    if (!self::copyDir("{$source}/{$file}", "{$destination}/{$file}")) {
551
                        return false;
552
                    }
553
                } else {
554
                    if (!copy("{$source}/{$file}", "{$destination}/{$file}")) {
555
                        return false;
556
                    }
557
                }
558
            }
559
        }
560
        closedir($dirHandler);
561
562
        return true;
563
    }
564
565
    /**
566
     * Delete a file
567
     *
568
     * @param string $path is the file absolute path
569
     *
570
     * @return bool Returns true on success or false on failure
571
     *
572
     */
573
    public static function delFile($path)
574
    {
575
        if (is_file($path)) {
576
            @chmod($path, 0777);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
577
578
            return @unlink($path);
579
        } else {
580
            return false;
581
        }
582
    }
583
584
    /**
585
     * Delete a empty/not empty directory
586
     *
587
     * @param string $dir          path to the directory to delete
588
     * @param bool   $if_not_empty if false it delete directory only if false
589
     *
590
     * @return bool Returns true on success or false on failure
591
     */
592
    public static function delDir($dir, $if_not_empty = true)
593
    {
594
        if (!file_exists($dir)) {
595
            return true;
596
        }
597
        if ($if_not_empty === true) {
598
            if (!is_dir($dir)) {
599
                return unlink($dir);
600
            }
601
            foreach (scandir($dir) as $item) {
602
                if ($item === '.' || $item === '..') {
603
                    continue;
604
                }
605
                if (!self::delDir("{$dir}/{$item}")) {
606
                    return false;
607
                }
608
            }
609
        } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
610
            // NOP
611
        }
612
613
        return rmdir($dir);
614
    }
615
616
    /**
617
     *
618
     * Module functions
619
     *
620
     */
621
622
    /**
623
     * Check if a module exist and return module verision
624
     *
625
     * @param string $dirname
626
     *
627
     * @return boolean, integer   false if module not installed or not active, module version if installed
0 ignored issues
show
Documentation introduced by
The doc-type boolean, could not be parsed: Expected "|" or "end of type", but got "," at position 7. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
628
     *
629
     * @access  public
630
     * @author  luciorota
631
     */
632
    public static function checkModule($dirname)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
633
    {
634
        if (!xoops_isActiveModule($dirname)) {
635
            return false;
636
        }
637
        $moduleHandler = xoops_getHandler('module');
638
        $module        = $moduleHandler->getByDirname($dirname);
639
640
        return $module->getVar('version');
641
    }
642
643
    /**
644
     * Recursively sort categories by level and weight
645
     *
646
     * @param integer $pid
647
     * @param integer $level
648
     *
649
     * @return array array of arrays: 'pid', 'cid', 'level', 'category' as array
650
     *
651
     * @access  public
652
     * @author  luciorota
653
     */
654
    public static function sortCategories($pid = 0, $level = 0)
655
    {
656
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
657
658
        $sorted   = array();
659
        $criteria = new CriteriaCompo();
660
        $criteria->add(new Criteria('pid', $pid));
661
        $criteria->setSort('weight');
662
        $criteria->setOrder('ASC');
663
        $subCategoryObjs = $wfdownloads->getHandler('category')->getObjects($criteria);
664
        if (count($subCategoryObjs) > 0) {
665
            ++$level;
666
            foreach ($subCategoryObjs as $subCategoryObj) {
667
                $pid      = $subCategoryObj->getVar('pid');
668
                $cid      = $subCategoryObj->getVar('cid');
669
                $sorted[] = array('pid' => $pid, 'cid' => $cid, 'level' => $level, 'category' => $subCategoryObj->toArray());
670
                if (false !== ($subSorted = self::sortCategories($cid, $level))) {
671
                    $sorted = array_merge($sorted, $subSorted);
672
                }
673
            }
674
        }
675
676
        return $sorted;
677
    }
678
679
    /**
680
     * Create download by letter choice bar/menu
681
     * updated starting from this idea http://xoops.org/modules/news/article.php?storyid=6497
682
     *
683
     * @return string html
684
     *
685
     * @access  public
686
     * @author  luciorota
687
     */
688
    public static function lettersChoice()
0 ignored issues
show
Coding Style introduced by
lettersChoice uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
689
    {
690
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
691
692
        $criteria = $wfdownloads->getHandler('download')->getActiveCriteria();
693
        $criteria->setGroupby('UPPER(LEFT(title,1))');
694
        $countsByLetters = $wfdownloads->getHandler('download')->getCounts($criteria);
695
        // Fill alphabet array
696
        $alphabet       = wfdownloads_alphabet();
697
        $alphabet_array = array();
698
        foreach ($alphabet as $letter) {
699
            $letter_array = array();
700
            if (isset($countsByLetters[$letter])) {
701
                $letter_array['letter'] = $letter;
702
                $letter_array['count']  = $countsByLetters[$letter];
703
                $letter_array['url']    = XOOPS_URL . "/modules/{$wfdownloads->getModule()->dirname()}/viewcat.php?list={$letter}";
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $wfdownloads->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
704
            } else {
705
                $letter_array['letter'] = $letter;
706
                $letter_array['count']  = 0;
707
                $letter_array['url']    = '';
708
            }
709
            $alphabet_array[$letter] = $letter_array;
710
            unset($letter_array);
711
        }
712
        // Render output
713
        if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) {
714
            include_once $GLOBALS['xoops']->path('/class/theme.php');
715
            $GLOBALS['xoTheme'] = new xos_opal_Theme();
716
        }
717
        require_once $GLOBALS['xoops']->path('class/template.php');
718
        $letterschoiceTpl          = new XoopsTpl();
719
        $letterschoiceTpl->caching = false; // Disable cache
720
        $letterschoiceTpl->assign('alphabet', $alphabet_array);
721
        $html = $letterschoiceTpl->fetch("db:{$wfdownloads->getModule()->dirname()}_co_letterschoice.tpl");
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $wfdownloads->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
722
        unset($letterschoiceTpl);
723
724
        return $html;
725
    }
726
727
    /**
728
     * Checks if a user is admin of Wfdownloads
729
     *
730
     * @return boolean
731
     */
732
    public static function userIsAdmin()
0 ignored issues
show
Coding Style introduced by
userIsAdmin uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
733
    {
734
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
735
736
        static $wfdownloads_isAdmin;
737
        if (isset($wfdownloads_isAdmin)) {
738
            return $wfdownloads_isAdmin;
739
        }
740
        $wfdownloads_isAdmin = (!is_object($GLOBALS['xoopsUser'])) ? false : $GLOBALS['xoopsUser']->isAdmin($wfdownloads->getModule()->getVar('mid'));
0 ignored issues
show
Bug introduced by
The method getVar cannot be called on $wfdownloads->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
741
742
        return $wfdownloads_isAdmin;
743
    }
744
745
    public static function myxoops_cp_header()
746
    {
747
        xoops_cp_header();
748
    }
749
750
    /**
751
     * @param bool $withLink
752
     *
753
     * @return string
754
     */
755
    public static function module_home($withLink = true)
756
    {
757
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
758
759
        $wfdownloadsModuleName = $wfdownloads->getModule()->getVar('name');
0 ignored issues
show
Bug introduced by
The method getVar cannot be called on $wfdownloads->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
760
        if (!$withLink) {
761
            return $wfdownloadsModuleName;
762
        } else {
763
            return '<a href="' . WFDOWNLOADS_URL . '/">{$wfdownloadsModuleName}</a>';
764
        }
765
    }
766
767
    /**
768
     * Detemines if a table exists in the current db
769
     *
770
     * @param string $table the table name (without XOOPS prefix)
771
     *
772
     * @return bool True if table exists, false if not
773
     *
774
     * @access public
775
     * @author xhelp development team
776
     */
777
    public static function tableExists($table)
0 ignored issues
show
Coding Style introduced by
tableExists uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
778
    {
779
        $bRetVal = false;
780
        //Verifies that a MySQL table exists
781
        $GLOBALS['xoopsDB'] = XoopsDatabaseFactory::getDatabaseConnection();
782
        $realName           = $GLOBALS['xoopsDB']->prefix($table);
783
784
        $sql = 'SHOW TABLES FROM ' . XOOPS_DB_NAME;
785
        $ret = $GLOBALS['xoopsDB']->queryF($sql);
786
        while (false !== (list($m_table) = $GLOBALS['xoopsDB']->fetchRow($ret))) {
787
            if ($m_table == $realName) {
788
                $bRetVal = true;
789
                break;
790
            }
791
        }
792
        $GLOBALS['xoopsDB']->freeRecordSet($ret);
793
794
        return $bRetVal;
795
    }
796
797
    /**
798
     * Gets a value from a key in the xhelp_meta table
799
     *
800
     * @param string $key
801
     *
802
     * @return string $value
803
     *
804
     * @access public
805
     * @author xhelp development team
806
     */
807
    public static function getMeta($key)
0 ignored issues
show
Coding Style introduced by
getMeta uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
808
    {
809
        $GLOBALS['xoopsDB'] = XoopsDatabaseFactory::getDatabaseConnection();
810
        $sql                = sprintf('SELECT metavalue FROM %s WHERE metakey=%s', $GLOBALS['xoopsDB']->prefix('wfdownloads_meta'), $GLOBALS['xoopsDB']->quoteString($key));
811
        $ret                = $GLOBALS['xoopsDB']->query($sql);
812
        if (!$ret) {
813
            $value = false;
814
        } else {
815
            list($value) = $GLOBALS['xoopsDB']->fetchRow($ret);
816
        }
817
818
        return $value;
819
    }
820
821
    /**
822
     * Sets a value for a key in the xhelp_meta table
823
     *
824
     * @param string $key
825
     * @param string $value
826
     *
827
     * @return bool true if success, false if failure
828
     *
829
     * @access public
830
     * @author xhelp development team
831
     */
832
    public static function setMeta($key, $value)
0 ignored issues
show
Coding Style introduced by
setMeta uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
833
    {
834
        $GLOBALS['xoopsDB'] = XoopsDatabaseFactory::getDatabaseConnection();
835
        if (false !== ($ret = self::getMeta($key))) {
836
            $sql = sprintf('UPDATE %s SET metavalue = %s WHERE metakey = %s', $GLOBALS['xoopsDB']->prefix('wfdownloads_meta'), $GLOBALS['xoopsDB']->quoteString($value), $GLOBALS['xoopsDB']->quoteString($key));
837
        } else {
838
            $sql = sprintf('INSERT INTO %s (metakey, metavalue) VALUES (%s, %s)', $GLOBALS['xoopsDB']->prefix('wfdownloads_meta'), $GLOBALS['xoopsDB']->quoteString($key), $GLOBALS['xoopsDB']->quoteString($value));
839
        }
840
        $ret = $GLOBALS['xoopsDB']->queryF($sql);
841
        if (!$ret) {
842
            return false;
843
        }
844
845
        return true;
846
    }
847
848
    /**
849
     * @param     $name
850
     * @param     $value
851
     * @param int $time
852
     */
853
    public static function setCookieVar($name, $value, $time = 0)
854
    {
855
        if ($time == 0) {
856
            $time = time() + 3600 * 24 * 365;
857
            //$time = '';
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
858
        }
859
        setcookie($name, $value, $time, '/');
860
    }
861
862
    /**
863
     * @param        $name
864
     * @param string $default
865
     *
866
     * @return string
867
     */
868
    public static function getCookieVar($name, $default = '')
0 ignored issues
show
Coding Style introduced by
getCookieVar uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
869
    {
870
        if (isset($_COOKIE[$name]) && ($_COOKIE[$name] > '')) {
871
            return $_COOKIE[$name];
872
        } else {
873
            return $default;
874
        }
875
    }
876
877
    /**
878
     * @return array
879
     */
880
    public static function getCurrentUrls()
0 ignored issues
show
Coding Style introduced by
getCurrentUrls uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
881
    {
882
        $http        = (strpos(XOOPS_URL, 'https://') === false) ? 'http://' : 'https://';
883
        $phpSelf     = $_SERVER['PHP_SELF'];
884
        $httpHost    = $_SERVER['HTTP_HOST'];
885
        $queryString = $_SERVER['QUERY_STRING'];
886
887
        if ($queryString !== '') {
888
            $queryString = '?' . $queryString;
889
        }
890
        $currentURL          = $http . $httpHost . $phpSelf . $queryString;
891
        $urls                = array();
892
        $urls['http']        = $http;
893
        $urls['httphost']    = $httpHost;
894
        $urls['phpself']     = $phpSelf;
895
        $urls['querystring'] = $queryString;
896
        $urls['full']        = $currentURL;
897
898
        return $urls;
899
    }
900
901
    /**
902
     * @return mixed
903
     */
904
    public static function getCurrentPage()
905
    {
906
        $urls = self::getCurrentUrls();
907
908
        return $urls['full'];
909
    }
910
911
    /**
912
     * @param array $errors
913
     *
914
     * @return string
915
     */
916
    public static function formatErrors($errors = array())
917
    {
918
        $ret = '';
919
        //mb    foreach ($errors as $key => $value) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
920
        foreach ($errors as $value) {
921
            $ret .= "<br> - {$value}";
922
        }
923
924
        return $ret;
925
    }
926
927
    // TODO : The SEO feature is not fully implemented in the module...
928
    /**
929
     * @param        $op
930
     * @param        $id
931
     * @param string $title
932
     *
933
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
934
     */
935
    public static function seo_genUrl($op, $id, $title = '')
936
    {
937
        if (defined('SEO_ENABLED')) {
938
            if (SEO_ENABLED === 'rewrite') {
939
                // generate SEO url using htaccess
940
                return XOOPS_URL . "/wfdownloads.${op}.${id}/" . self::seo_title($title);
941
            } elseif (SEO_ENABLED === 'path-info') {
942
                // generate SEO url using path-info
943
                return XOOPS_URL . "/modules/wfdownloads/seo.php/${op}.${id}/" . self::seo_title($title);
944
            } else {
945
                die('Unknown SEO method.');
0 ignored issues
show
Coding Style Compatibility introduced by
The method seo_genUrl() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
946
            }
947
        } else {
948
            // generate classic url
949
            switch ($op) {
950
                case 'category':
951
                    return XOOPS_URL . "/modules/wfdownloads/${op}.php?categoryid=${id}";
952
                case 'item':
953
                case 'print':
954
                    return XOOPS_URL . "/modules/wfdownloads/${op}.php?itemid=${id}";
955
                default:
956
                    die('Unknown SEO operation.');
0 ignored issues
show
Coding Style Compatibility introduced by
The method seo_genUrl() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
957
            }
958
        }
959
    }
960
961
    /**
962
     * @param  string $title
963
     * @return string
964
     */
965
    public static function seo_title($title = '')
966
    {
967
        $words = preg_split('/[^0-9a-z.]+/', strtolower($title), -1, PREG_SPLIT_NO_EMPTY);
968
        if (count($words) > 0) {
969
            return implode($words, '-') . '.html';
970
        } else {
971
            return '';
972
        }
973
    }
974
975
    /**
976
     * save_Permissions()
977
     *
978
     * @param $groups
979
     * @param $id
980
     * @param $permName
981
     *
982
     * @return bool
983
     */
984
    public static function savePermissions($groups, $id, $permName)
985
    {
986
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
987
988
        $id           = (int)$id;
989
        $result       = true;
990
        $mid          = $wfdownloads->getModule()->mid();
0 ignored issues
show
Bug introduced by
The method mid cannot be called on $wfdownloads->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
991
        $gpermHandler = xoops_getHandler('groupperm');
992
        // First, if the permissions are already there, delete them
993
        $gpermHandler->deleteByModule($mid, $permName, $id);
994
        // Save the new permissions
995
        if (is_array($groups)) {
996
            foreach ($groups as $group_id) {
997
                $gpermHandler->addRight($permName, $id, $group_id, $mid);
998
            }
999
        }
1000
1001
        return $result;
1002
    }
1003
1004
    /**
1005
     * toolbar()
1006
     *
1007
     * @return string
1008
     */
1009
    public static function toolbar()
0 ignored issues
show
Coding Style introduced by
toolbar uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
toolbar uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1010
    {
1011
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1012
1013
        $isSubmissionAllowed = false;
1014
        if (is_object($GLOBALS['xoopsUser']) && ($wfdownloads->getConfig('submissions') == _WFDOWNLOADS_SUBMISSIONS_DOWNLOAD || $wfdownloads->getConfig('submissions') == _WFDOWNLOADS_SUBMISSIONS_BOTH)) {
1015
            $groups = $GLOBALS['xoopsUser']->getGroups();
1016
            if (count(array_intersect($wfdownloads->getConfig('submitarts'), $groups)) > 0) {
1017
                $isSubmissionAllowed = true;
1018
            }
1019
        } elseif (!is_object($GLOBALS['xoopsUser']) && ($wfdownloads->getConfig('anonpost') == _WFDOWNLOADS_ANONPOST_DOWNLOAD || $wfdownloads->getConfig('anonpost') == _WFDOWNLOADS_ANONPOST_BOTH)) {
1020
            $isSubmissionAllowed = true;
1021
        }
1022
        $toolbar = '[ ';
1023
        if ($isSubmissionAllowed === true) {
1024
            $category_suffix = !empty($_GET['cid']) ? '?cid=' . (int)$_GET['cid'] : ''; //Added by Lankford
1025
            $toolbar .= "<a href='submit.php{$category_suffix}'>" . _MD_WFDOWNLOADS_SUBMITDOWNLOAD . '</a> | ';
1026
        }
1027
        $toolbar .= "<a href='newlist.php'>" . _MD_WFDOWNLOADS_LATESTLIST . '</a>';
1028
        $toolbar .= ' | ';
1029
        $toolbar .= "<a href='topten.php?list=hit'>" . _MD_WFDOWNLOADS_POPULARITY . '</a>';
1030
        if ($wfdownloads->getConfig('enable_ratings')) {
1031
            $toolbar .= ' | ';
1032
            $toolbar .= "<a href='topten.php?list=rate'>" . _MD_WFDOWNLOADS_TOPRATED . '</a>';
1033
        }
1034
        $toolbar .= ' ]';
1035
1036
        return $toolbar;
1037
    }
1038
1039
    /**
1040
     * serverStats()
1041
     *
1042
     * @return string
1043
     */
1044
    public static function serverStats()
0 ignored issues
show
Coding Style introduced by
serverStats uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1045
    {
1046
        //mb    $wfdownloads = WfdownloadsWfdownloads::getInstance();
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1047
        $html = '';
1048
        $sql  = 'SELECT metavalue';
1049
        $sql .= ' FROM ' . $GLOBALS['xoopsDB']->prefix('wfdownloads_meta');
1050
        $sql .= " WHERE metakey='version' LIMIT 1";
1051
        $query = $GLOBALS['xoopsDB']->query($sql);
1052
        list($meta) = $GLOBALS['xoopsDB']->fetchRow($query);
1053
        $html .= "<fieldset><legend style='font-weight: bold; color: #900;'>" . _AM_WFDOWNLOADS_DOWN_IMAGEINFO . "</legend>\n";
1054
        $html .= "<div style='padding: 8px;'>\n";
1055
        $html .= '<div>' . _AM_WFDOWNLOADS_DOWN_METAVERSION . $meta . "</div>\n";
1056
        $html .= "<br>\n";
1057
        $html .= "<br>\n";
1058
        $html .= '<div>' . _AM_WFDOWNLOADS_DOWN_SPHPINI . "</div>\n";
1059
        $html .= "<ul>\n";
1060
        //
1061
        $gdlib = function_exists('gd_info') ? "<span style=\"color: green;\">" . _AM_WFDOWNLOADS_DOWN_GDON . '</span>' : "<span style=\"color: red;\">" . _AM_WFDOWNLOADS_DOWN_GDOFF . '</span>';
1062
        $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_GDLIBSTATUS . $gdlib;
1063
        if (function_exists('gd_info')) {
1064
            if (true === $gdlib = gd_info()) {
1065
                $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_GDLIBVERSION . '<b>' . $gdlib['GD Version'] . '</b>';
1066
            }
1067
        }
1068
        //
1069
        //    $safemode = ini_get('safe_mode') ? _AM_WFDOWNLOADS_DOWN_ON . _AM_WFDOWNLOADS_DOWN_SAFEMODEPROBLEMS : _AM_WFDOWNLOADS_DOWN_OFF;
1070
        //    $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_SAFEMODESTATUS . $safemode;
1071
        //
1072
        //    $registerglobals = (!ini_get('register_globals')) ? "<span style=\"color: green;\">" . _AM_WFDOWNLOADS_DOWN_OFF . '</span>' : "<span style=\"color: red;\">" . _AM_WFDOWNLOADS_DOWN_ON . '</span>';
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1073
        //    $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_REGISTERGLOBALS . $registerglobals;
1074
        //
1075
        $downloads = ini_get('file_uploads') ? "<span style=\"color: green;\">" . _AM_WFDOWNLOADS_DOWN_ON . '</span>' : "<span style=\"color: red;\">" . _AM_WFDOWNLOADS_DOWN_OFF . '</span>';
1076
        $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_SERVERUPLOADSTATUS . $downloads;
1077
        //
1078
        $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_MAXUPLOADSIZE . " <b><span style=\"color: blue;\">" . ini_get('upload_max_filesize') . "</span></b>\n";
1079
        $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_MAXPOSTSIZE . " <b><span style=\"color: blue;\">" . ini_get('post_max_size') . "</span></b>\n";
1080
        $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_MEMORYLIMIT . " <b><span style=\"color: blue;\">" . ini_get('memory_limit') . "</span></b>\n";
1081
        $html .= "</ul>\n";
1082
        $html .= "<ul>\n";
1083
        $html .= '<li>' . _AM_WFDOWNLOADS_DOWN_SERVERPATH . ' <b>' . XOOPS_ROOT_PATH . "</b>\n";
1084
        $html .= "</ul>\n";
1085
        $html .= "<br>\n";
1086
        $html .= _AM_WFDOWNLOADS_DOWN_UPLOADPATHDSC . "\n";
1087
        $html .= '</div>';
1088
        $html .= '</fieldset><br>';
1089
1090
        return $html;
1091
    }
1092
1093
    /**
1094
     * displayicons()
1095
     *
1096
     * @param         $time
1097
     * @param int     $status
1098
     * @param integer $counter
1099
     *
1100
     * @return string
1101
     */
1102
    public static function displayIcons($time, $status = _WFDOWNLOADS_STATUS_WAITING, $counter = 0)
1103
    {
1104
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1105
1106
        $new     = '';
1107
        $pop     = '';
1108
        $newdate = (time() - (86400 * $wfdownloads->getConfig('daysnew')));
1109
        $popdate = (time() - (86400 * $wfdownloads->getConfig('daysupdated')));
1110
1111
        if ($wfdownloads->getConfig('displayicons') != _WFDOWNLOADS_DISPLAYICONS_NO) {
1112
            if ($newdate < $time) {
1113
                if ((int)$status > _WFDOWNLOADS_STATUS_APPROVED) {
1114
                    if ($wfdownloads->getConfig('displayicons') == _WFDOWNLOADS_DISPLAYICONS_ICON) {
1115
                        $new = '&nbsp;<img src=' . XOOPS_URL . '/modules/' . WFDOWNLOADS_DIRNAME . "/assets/images/icon/update.gif alt='' align ='absmiddle'/>";
1116
                    }
1117
                    if ($wfdownloads->getConfig('displayicons') == _WFDOWNLOADS_DISPLAYICONS_TEXT) {
1118
                        $new = '<i>' . _WFDOWNLOADS_MD_UPDATED . '</i>';
1119
                    }
1120
                } else {
1121
                    if ($wfdownloads->getConfig('displayicons') == _WFDOWNLOADS_DISPLAYICONS_ICON) {
1122
                        $new = '&nbsp;<img src=' . XOOPS_URL . '/modules/' . WFDOWNLOADS_DIRNAME . "/assets/images/icon/newred.gif alt='' align ='absmiddle'/>";
1123
                    }
1124
                    if ($wfdownloads->getConfig('displayicons') == _WFDOWNLOADS_DISPLAYICONS_TEXT) {
1125
                        $new = '<i>' . _WFDOWNLOADS_MD_NEW . '</i>';
1126
                    }
1127
                }
1128
            }
1129
            if ($popdate < $time) {
1130
                if ($counter >= $wfdownloads->getConfig('popular')) {
1131
                    if ($wfdownloads->getConfig('displayicons') == _WFDOWNLOADS_DISPLAYICONS_ICON) {
1132
                        $pop = '&nbsp;<img src =' . XOOPS_URL . '/modules/' . WFDOWNLOADS_DIRNAME . "/assets/images/icon/pop.gif alt='' align ='absmiddle'/>";
1133
                    }
1134
                    if ($wfdownloads->getConfig('displayicons') == _WFDOWNLOADS_DISPLAYICONS_TEXT) {
1135
                        $pop = '<i>' . _WFDOWNLOADS_MD_POPULAR . '</i>';
1136
                    }
1137
                }
1138
            }
1139
        }
1140
        $icons = "{$new} {$pop}";
1141
1142
        return $icons;
1143
    }
1144
1145
    //if (!function_exists('convertorderbyin')) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1146
    // Reusable Link Sorting Functions
1147
    /**
1148
     * convertorderbyin()
1149
     *
1150
     * @param   $orderby
1151
     *
1152
     * @return string
1153
     */
1154
    public static function convertorderbyin($orderby)
1155
    {
1156
        switch (trim($orderby)) {
1157
            case 'titleA':
1158
                $orderby = 'title ASC';
1159
                break;
1160
            case 'titleD':
1161
                $orderby = 'title DESC';
1162
                break;
1163
            case 'dateA':
1164
                $orderby = 'published ASC';
1165
                break;
1166
            case 'dateD':
1167
                $orderby = 'published DESC';
1168
                break;
1169
            case 'hitsA':
1170
                $orderby = 'hits ASC';
1171
                break;
1172
            case 'hitsD':
1173
                $orderby = 'hits DESC';
1174
                break;
1175
            case 'ratingA':
1176
                $orderby = 'rating ASC';
1177
                break;
1178
            case 'ratingD':
1179
                $orderby = 'rating DESC';
1180
                break;
1181
            case 'sizeD':
1182
                $orderby = 'size DESC';
1183
                break;
1184
            case 'sizeA':
1185
                $orderby = 'size ASC';
1186
                break;
1187
            default:
1188
                $orderby = 'published DESC';
1189
                break;
1190
        }
1191
1192
        return $orderby;
1193
    }
1194
    //}
1195
1196
    //if (!function_exists('convertorderbytrans')) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1197
    /**
1198
     * @param $orderby
1199
     *
1200
     * @return string
1201
     */
1202
    public static function convertorderbytrans($orderby)
1203
    {
1204
        if ($orderby === 'title ASC') {
1205
            $orderbyTrans = _MD_WFDOWNLOADS_TITLEATOZ;
1206
        }
1207
        if ($orderby === 'title DESC') {
1208
            $orderbyTrans = _MD_WFDOWNLOADS_TITLEZTOA;
1209
        }
1210
        if ($orderby === 'published ASC') {
1211
            $orderbyTrans = _MD_WFDOWNLOADS_DATEOLD;
1212
        }
1213
        if ($orderby === 'published DESC') {
1214
            $orderbyTrans = _MD_WFDOWNLOADS_DATENEW;
1215
        }
1216
        if ($orderby === 'hits ASC') {
1217
            $orderbyTrans = _MD_WFDOWNLOADS_POPULARITYLTOM;
1218
        }
1219
        if ($orderby === 'hits DESC') {
1220
            $orderbyTrans = _MD_WFDOWNLOADS_POPULARITYMTOL;
1221
        }
1222
        if ($orderby === 'rating ASC') {
1223
            $orderbyTrans = _MD_WFDOWNLOADS_RATINGLTOH;
1224
        }
1225
        if ($orderby === 'rating DESC') {
1226
            $orderbyTrans = _MD_WFDOWNLOADS_RATINGHTOL;
1227
        }
1228
        if ($orderby === 'size ASC') {
1229
            $orderbyTrans = _MD_WFDOWNLOADS_SIZELTOH;
1230
        }
1231
        if ($orderby === 'size DESC') {
1232
            $orderbyTrans = _MD_WFDOWNLOADS_SIZEHTOL;
1233
        }
1234
1235
        return $orderbyTrans;
0 ignored issues
show
Bug introduced by
The variable $orderbyTrans 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...
1236
    }
1237
    //}
1238
1239
    //if (!function_exists('convertorderbyout')) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1240
    /**
1241
     * @param $orderby
1242
     *
1243
     * @return string
1244
     */
1245
    public static function convertorderbyout($orderby)
1246
    {
1247
        if ($orderby === 'title ASC') {
1248
            $orderby = 'titleA';
1249
        }
1250
        if ($orderby === 'title DESC') {
1251
            $orderby = 'titleD';
1252
        }
1253
        if ($orderby === 'published ASC') {
1254
            $orderby = 'dateA';
1255
        }
1256
        if ($orderby === 'published DESC') {
1257
            $orderby = 'dateD';
1258
        }
1259
        if ($orderby === 'hits ASC') {
1260
            $orderby = 'hitsA';
1261
        }
1262
        if ($orderby === 'hits DESC') {
1263
            $orderby = 'hitsD';
1264
        }
1265
        if ($orderby === 'rating ASC') {
1266
            $orderby = 'ratingA';
1267
        }
1268
        if ($orderby === 'rating DESC') {
1269
            $orderby = 'ratingD';
1270
        }
1271
        if ($orderby === 'size ASC') {
1272
            $orderby = 'sizeA';
1273
        }
1274
        if ($orderby === 'size DESC') {
1275
            $orderby = 'sizeD';
1276
        }
1277
1278
        return $orderby;
1279
    }
1280
    //}
1281
1282
    /**
1283
     * updaterating()
1284
     *
1285
     * @param   $lid
1286
     *
1287
     * @return updates rating data in itemtable for a given item
0 ignored issues
show
Documentation introduced by
Should the return type not be updates|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1288
     **/
1289
    public static function updateRating($lid)
1290
    {
1291
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1292
1293
        $ratingObjs    = $wfdownloads->getHandler('rating')->getObjects(new Criteria('lid', (int)$lid));
1294
        $ratings_count = count($ratingObjs);
1295
        $totalRating   = 0;
1296
        foreach ($ratingObjs as $ratingObj) {
1297
            $totalRating += $ratingObj->getVar('rating');
1298
        }
1299
        $averageRating = $totalRating / $ratings_count;
1300
        $averageRating = number_format($averageRating, 4);
1301
        $downloadObj   = $wfdownloads->getHandler('download')->get($lid);
1302
        $downloadObj->setVar('rating', $averageRating);
1303
        $downloadObj->setVar('votes', $ratings_count);
1304
        $wfdownloads->getHandler('download')->insert($downloadObj);
1305
    }
1306
1307
    /**
1308
     * categoriesCount()
1309
     *
1310
     * @return int
1311
     */
1312
    public static function categoriesCount()
0 ignored issues
show
Coding Style introduced by
categoriesCount uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1313
    {
1314
        $gpermHandler             = xoops_getHandler('groupperm');
1315
        $wfdownloads              = WfdownloadsWfdownloads::getInstance();
1316
        $groups                   = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : array(0 => XOOPS_GROUP_ANONYMOUS);
1317
        $allowedDownCategoriesIds = $gpermHandler->getItemIds('WFDownCatPerm', $groups, $wfdownloads->getModule()->mid());
0 ignored issues
show
Bug introduced by
The method mid cannot be called on $wfdownloads->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1318
1319
        return count($allowedDownCategoriesIds);
1320
    }
1321
1322
    /**
1323
     * getTotalDownloads()
1324
     *
1325
     * @param int|array of integer $cids
1326
     *
1327
     * @return total number of items in items table that are associated with a given table $table id
0 ignored issues
show
Documentation introduced by
Should the return type not be false|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1328
     */
1329
    public static function getTotalDownloads($cids = 0)
1330
    {
1331
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1332
1333
        $criteria = new CriteriaCompo(new Criteria('offline', false));
1334
        $criteria->add(new Criteria('published', 0, '>'));
1335
        $criteria->add(new Criteria('published', time(), '<='));
1336
        $expiredCriteria = new CriteriaCompo(new Criteria('expired', 0));
1337
        $expiredCriteria->add(new Criteria('expired', time(), '>='), 'OR');
1338
        $criteria->add($expiredCriteria);
1339
        if (is_array($cids) && count($cids) > 0) {
1340
            $criteria->add(new Criteria('cid', '(' . implode(',', $cids) . ')', 'IN'));
1341
        } elseif ($cids > 0) {
1342
            $criteria->add(new Criteria('cid', (int)$cids));
1343
        } else {
1344
            return false;
1345
        }
1346
        $criteria->setGroupBy('cid');
1347
        $info['published'] = $wfdownloads->getHandler('download')->getMaxPublishdate($criteria);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1348
        $info['count']     = $wfdownloads->getHandler('download')->getCount($criteria);
1349
1350
        return $info;
1351
    }
1352
1353
    /**
1354
     * @return string
1355
     */
1356
    public static function headerImage()
0 ignored issues
show
Coding Style introduced by
headerImage uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1357
    {
1358
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1359
1360
        $image  = '';
1361
        $result = $GLOBALS['xoopsDB']->query('SELECT indeximage, indexheading FROM ' . $GLOBALS['xoopsDB']->prefix('wfdownloads_indexpage') . ' ');
1362
        list($indexImage, $indexHeading) = $GLOBALS['xoopsDB']->fetchrow($result);
1363
        if (!empty($indeximage)) {
0 ignored issues
show
Bug introduced by
The variable $indeximage does not exist. Did you mean $indexImage?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1364
            $image = self::displayImage($indexImage, 'index.php', $wfdownloads->getConfig('mainimagedir'), $indexHeading);
1365
        }
1366
1367
        return $image;
1368
    }
1369
1370
    /**
1371
     * @param string $image
1372
     * @param string $href
1373
     * @param string $imgSource
1374
     * @param string $altText
1375
     *
1376
     * @return string
1377
     */
1378
    public static function displayImage($image = '', $href = '', $imgSource = '', $altText = '')
0 ignored issues
show
Coding Style introduced by
displayImage uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1379
    {
1380
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1381
1382
        $showImage = '';
1383
1384
        // Check to see if link is given
1385
        if ($href) {
1386
            $showImage = "<a href='{$href}'>";
1387
        }
1388
        // checks to see if the file is valid else displays default blank image
1389
        if (!is_dir(XOOPS_ROOT_PATH . "/{$imgSource}/{$image}") && file_exists(XOOPS_ROOT_PATH . "/{$imgSource}/{$image}")) {
1390
            $showImage .= "<img src='" . XOOPS_URL . "/{$imgSource}/{$image}' border='0' alt='{$altText}' />";
1391
        } else {
1392
            if ($GLOBALS['xoopsUser'] && $GLOBALS['xoopsUser']->isAdmin($wfdownloads->getModule()->mid())) {
0 ignored issues
show
Bug introduced by
The method mid cannot be called on $wfdownloads->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1393
                $showImage .= "<img src='" . XOOPS_URL . '/modules/' . WFDOWNLOADS_DIRNAME . "/assets/images/brokenimg.png' alt='" . _MD_WFDOWNLOADS_ISADMINNOTICE . "' />";
1394
            } else {
1395
                $showImage .= "<img src='" . XOOPS_URL . '/modules/' . WFDOWNLOADS_DIRNAME . "/assets/images/blank.gif' alt='{$altText}' />";
1396
            }
1397
        }
1398
        if ($href) {
1399
            $showImage .= '</a>';
1400
        }
1401
        clearstatcache();
1402
1403
        return $showImage;
1404
    }
1405
1406
    /**
1407
     * createThumb()
1408
     *
1409
     * @param          $imgName
1410
     * @param          $imgPath
1411
     * @param          $imgSavePath
1412
     * @param integer  $width
1413
     * @param integer  $height
1414
     * @param integer  $quality
1415
     * @param bool|int $update
1416
     * @param integer  $aspect
1417
     *
1418
     * @return string
1419
     */
1420
    public static function createThumb($imgName, $imgPath, $imgSavePath, $width = 100, $height = 100, $quality = 100, $update = false, $aspect = 1)
0 ignored issues
show
Unused Code introduced by
The parameter $quality is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $aspect is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1421
    {
1422
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1423
1424
        // Paths
1425
        if ($wfdownloads->getConfig('usethumbs') === false) {
1426
            $imageURL = XOOPS_URL . "/{$imgPath}/{$imgName}";
1427
1428
            return $imageURL;
1429
        }
1430
        $imagePath = XOOPS_ROOT_PATH . "/{$imgPath}/{$imgName}";
1431
        $saveFile  = "{$imgPath}/{$imgSavePath}/{$width}x{$height}_{$imgName}";
1432
        $savePath  = XOOPS_ROOT_PATH . '/' . $saveFile;
1433
        // Return the image if no update and image exists
1434
        if ($update === false && file_exists($savePath)) {
1435
            return XOOPS_URL . '/' . $saveFile;
1436
        }
1437
        // Original image info
1438
        list($origWidth, $origHeight, $type, $attr) = getimagesize($imagePath, $info);
0 ignored issues
show
Unused Code introduced by
The assignment to $attr is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
1439
        switch ($type) {
1440
            case 1:
1441
                # GIF image
1442
                if (function_exists('imagecreatefromgif')) {
1443
                    $img = @imagecreatefromgif($imagePath);
1444
                } else {
1445
                    $img = @imagecreatefrompng($imagePath);
1446
                }
1447
                break;
1448
            case 2:
1449
                # JPEG image
1450
                $img = @imagecreatefromjpeg($imagePath);
1451
                break;
1452
            case 3:
1453
                # PNG image
1454
                $img = @imagecreatefrompng($imagePath);
1455
                break;
1456
            default:
1457
                return $imagePath;
1458
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1459
        }
1460
        if (!empty($img)) {
1461
            // Get original image size and scale ratio
1462
            $scale = $origWidth / $origHeight;
1463
            if ($width / $height > $scale) {
1464
                $width = $height * $scale;
1465
            } else {
1466
                $height = $width / $scale;
1467
            }
1468
            // Create a new temporary image
1469
            if (function_exists('imagecreatetruecolor')) {
1470
                $tempImg = imagecreatetruecolor($width, $height);
1471
            } else {
1472
                $tempImg = imagecreate($width, $height);
1473
            }
1474
            // Copy and resize old image into new image
1475
            imagecopyresampled($tempImg, $img, 0, 0, 0, 0, $width, $height, $origWidth, $origHeight);
1476
            imagedestroy($img);
1477
            flush();
1478
            $img = $tempImg;
1479
        }
1480
        switch ($type) {
1481
            case 1:
1482
            default:
1483
                # GIF image
1484
                if (function_exists('imagegif')) {
1485
                    imagegif($img, $savePath);
1486
                } else {
1487
                    imagepng($img, $savePath);
1488
                }
1489
                break;
1490
            case 2:
0 ignored issues
show
Unused Code introduced by
case 2: # JPEG image..., $quality); break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1491
                # JPEG image
1492
                imagejpeg($img, $savePath, $quality);
1493
                break;
1494
            case 3:
1495
                # PNG image
1496
                imagepng($img, $savePath);
1497
                break;
1498
        }
1499
        imagedestroy($img);
1500
        flush();
1501
1502
        return XOOPS_URL . '/' . $saveFile;
1503
    }
1504
1505
    /**
1506
     * isNewImage()
1507
     *
1508
     * @param integer $published date
1509
     *
1510
     * @return array 'image', 'alttext', 'days'  number of days between $published and now
1511
     **/
1512
    public static function isNewImage($published)
1513
    {
1514
        if ($published <= 0) {
1515
            $indicator['image']   = 'assets/images/icon/download.gif';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1516
            $indicator['alttext'] = _MD_WFDOWNLOADS_NO_FILES;
1517
            $indicator['days']    = null;
1518
        } else {
1519
            $days              = (int)((time() - $published) / 86400); // number of days between $published and now
1520
            $indicator['days'] = $days;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1521
            switch ($days) {
1522
                case 0:
1523
                    // today
1524
                    $indicator['image']   = 'assets/images/icon/download1.gif';
1525
                    $indicator['alttext'] = _MD_WFDOWNLOADS_TODAY;
1526
                    break;
1527
                case 1:
1528
                case 2:
1529
                    // less than 3 days
1530
                    $indicator['image']   = 'assets/images/icon/download2.gif';
1531
                    $indicator['alttext'] = _MD_WFDOWNLOADS_THREE;
1532
                    break;
1533
                case 3:
1534
                case 4:
1535
                case 5:
1536
                case 6:
1537
                    // less than 7 days
1538
                    $indicator['image']   = 'assets/images/icon/download3.gif';
1539
                    $indicator['alttext'] = _MD_WFDOWNLOADS_NEWTHIS;
1540
                    break;
1541
                case 7:
1542
                default:
1543
                    // more than a week
1544
                    $indicator['image']   = 'assets/images/icon/download4.gif';
1545
                    $indicator['alttext'] = _MD_WFDOWNLOADS_NEWLAST;
1546
                    break;
1547
            }
1548
        }
1549
1550
        return $indicator;
1551
    }
1552
1553
    // GetDownloadTime()
1554
    // This function is used to show some different download times
1555
    // BCMATH-Support in PHP needed!
1556
    // (c)02.04.04 by St@neCold, [email protected], http://www.csgui.de
1557
    /**
1558
     * @param int $size
1559
     * @param int $gmodem
1560
     * @param int $gisdn
1561
     * @param int $gdsl
1562
     * @param int $gslan
1563
     * @param int $gflan
1564
     *
1565
     * @return string
1566
     */
1567
    public static function getDownloadTime($size = 0, $gmodem = 1, $gisdn = 1, $gdsl = 1, $gslan = 0, $gflan = 0)
1568
    {
1569
        $aflag  = array();
0 ignored issues
show
Unused Code introduced by
$aflag 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...
1570
        $amtime = array();
0 ignored issues
show
Unused Code introduced by
$amtime 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...
1571
        $artime = array();
1572
        $ahtime = array();
1573
        $asout  = array();
1574
        $aflag  = array($gmodem, $gisdn, $gdsl, $gslan, $gflan);
1575
        $amtime = array($size / 6300 / 60, $size / 7200 / 60, $size / 86400 / 60, $size / 1125000 / 60, $size / 11250000 / 60);
1576
        $amname = array('Modem(56k)', 'ISDN(64k)', 'DSL(768k)', 'LAN(10M)', 'LAN(100M');
1577
        for ($i = 0; $i < 5; ++$i) {
1578
            $artime[$i] = ($amtime[$i] % 60);
1579
        }
1580
        for ($i = 0; $i < 5; ++$i) {
1581
            $ahtime[$i] = sprintf(' %2.0f', $amtime[$i] / 60);
1582
        }
1583
        if ($size <= 0) {
1584
            $dltime = 'N/A';
1585
        } else {
1586
            for ($i = 0; $i < 5; ++$i) {
1587
                if (!$aflag[$i]) {
1588
                    $asout[$i] = '';
1589
                } else {
1590
                    if (($amtime[$i] * 60) < 1) {
1591
                        $asout[$i] = sprintf(' : %4.2fs', $amtime[$i] * 60);
1592
                    } else {
1593
                        if ($amtime[$i] < 1) {
1594
                            $asout[$i] = sprintf(' : %2.0fs', round($amtime[$i] * 60));
1595
                        } else {
1596
                            if ($ahtime[$i] == 0) {
1597
                                $asout[$i] = sprintf(' : %5.1fmin', $amtime[$i]);
1598
                            } else {
1599
                                $asout[$i] = sprintf(' : %2.0fh%2.0fmin', $ahtime[$i], $artime[$i]);
1600
                            }
1601
                        }
1602
                    }
1603
                    $asout[$i] = '<b>' . $amname[$i] . '</b>' . $asout[$i];
1604
                    if ($i < 4) {
1605
                        $asout[$i] .= ' | ';
1606
                    }
1607
                }
1608
            }
1609
            $dltime = '';
1610
            for ($i = 0; $i < 5; ++$i) {
1611
                $dltime .= $asout[$i];
1612
            }
1613
        }
1614
1615
        return $dltime;
1616
    }
1617
1618
    /**
1619
     * @param $haystack
1620
     * @param $needle
1621
     *
1622
     * @return string
1623
     */
1624
    public static function strrrchr($haystack, $needle)
1625
    {
1626
        return substr($haystack, 0, strpos($haystack, $needle) + 1);
1627
    }
1628
1629
    /**
1630
     * @param      $fileName
1631
     * @param bool $isAdmin
1632
     *
1633
     * @return array
1634
     */
1635
    public static function allowedMimetypes($fileName, $isAdmin = true)
1636
    {
1637
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1638
1639
        $ext      = ltrim(strrchr($fileName, '.'), '.');
1640
        $criteria = new CriteriaCompo(new Criteria('mime_ext', strtolower($ext)));
1641
        if ($isAdmin === true) {
1642
            $criteria->add(new Criteria('mime_admin', true));
1643
        } else {
1644
            $criteria->add(new Criteria('mime_user', true));
1645
        }
1646
        if (false !== ($mimetypeObjs = $wfdownloads->getHandler('mimetype')->getObjects($criteria))) {
1647
            $mimetypeObj = $mimetypeObjs[0];
1648
            $ret         = explode(' ', $mimetypeObj->getVar('mime_types'));
1649
        } else {
1650
            $ret = array();
1651
        }
1652
1653
        return $ret;
1654
    }
1655
1656
    /**
1657
     * @param $size_str
1658
     *
1659
     * @return int
1660
     */
1661
    public static function return_bytes($size_str)
1662
    {
1663
        switch (substr($size_str, -1)) {
1664
            case 'M':
1665
            case 'm':
1666
                return (int)$size_str * 1048576;
1667
            case 'K':
1668
            case 'k':
1669
                return (int)$size_str * 1024;
1670
            case 'G':
1671
            case 'g':
1672
                return (int)$size_str * 1073741824;
1673
            default:
1674
                return $size_str;
1675
        }
1676
    }
1677
1678
    /**
1679
     * uploading()
1680
     *
1681
     * @param string  $filename
1682
     * @param string  $uploadDirectory
1683
     * @param array   $allowedMimetypes
1684
     * @param string  $redirectURL
1685
     * @param integer $num
1686
     * @param bool    $redirect
1687
     * @param bool    $isAdmin
1688
     * @param bool    $onlyImages
1689
     *
1690
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
1691
     **/
1692
    public static function uploading($filename, $uploadDirectory = 'uploads', $allowedMimetypes = array(), $redirectURL = 'index.php', $num = 0, $redirect = false, $isAdmin = true, $onlyImages = false)
0 ignored issues
show
Coding Style introduced by
uploading uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
uploading uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1693
    {
1694
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
1695
        $file        = array();
1696
        if (empty($allowedMimetypes)) {
1697
            $allowedMimetypes = self::allowedMimetypes($_FILES['userfile']['name'], $isAdmin);
1698
        }
1699
        if (empty($allowedMimetypes)) {
1700
            $errors = 'MIME type not allowed';
1701
            redirect_header($redirectURL, 4, $errors);
1702
        }
1703
        $uploadDirectory .= '/';
1704
        $file_name = $_FILES['userfile']['name'];
0 ignored issues
show
Unused Code introduced by
$file_name 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...
1705
        //Admin can upload files of any size
1706
        if (self::userIsAdmin()) {
1707
            $maxFileSize = self::return_bytes(ini_get('upload_max_filesize'));
1708
        } else {
1709
            $maxFileSize = $wfdownloads->getConfig('maxfilesize');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $maxFileSize is correct as $wfdownloads->getConfig('maxfilesize') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1710
        }
1711
        $maxImageWidth  = $wfdownloads->getConfig('maximgwidth');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $maxImageWidth is correct as $wfdownloads->getConfig('maximgwidth') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1712
        $maxImageHeight = $wfdownloads->getConfig('maximgheight');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $maxImageHeight is correct as $wfdownloads->getConfig('maximgheight') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1713
        // TODO: use Xoops XoopsMediaUploader class
1714
        if ($onlyImages) {
1715
            include_once XOOPS_ROOT_PATH . '/modules/wfdownloads/class/img_uploader.php';
1716
            //xoops_load('XoopsMediaUploader');
1717
            $uploader = new XoopsMediaImgUploader($uploadDirectory, $allowedMimetypes, $maxFileSize, $maxImageWidth, $maxImageHeight);
1718
        } else {
1719
            include_once XOOPS_ROOT_PATH . '/class/uploader.php';
1720
            //xoops_load('XoopsMediaUploader');
1721
            $uploader = new XoopsMediaUploader($uploadDirectory, $allowedMimetypes, $maxFileSize, $maxImageWidth, $maxImageHeight);
1722
        }
1723
        //    $uploader->noAdminSizeCheck(1);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1724
        if ($uploader->fetchMedia($_POST['xoops_upload_file'][0])) {
1725
            if (!$uploader->upload()) {
1726
                $errors = $uploader->getErrors();
1727
                unlink($uploadDirectory . $uploader->savedFileName);
1728
                redirect_header($redirectURL, 4, $errors);
1729
            } else {
1730
                if ($redirect) {
1731
                    redirect_header($redirectURL, 4, _AM_WFDOWNLOADS_UPLOADFILE);
1732
                } else {
1733
                    if (is_file($uploader->savedDestination)) {
1734
                        //                    $file['url'] = XOOPS_URL . '/' . $uploadDirectory . '/';
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1735
                        $file['filename'] = strtolower($uploader->savedFileName);
1736
                        $file['filetype'] = $_FILES['userfile']['type'];
1737
                        $file['size']     = filesize($uploadDirectory . strtolower($uploader->savedFileName));
1738
                    }
1739
1740
                    return $file;
1741
                }
1742
            }
1743
        } else {
1744
            $errors = $uploader->getErrors();
1745
            unlink($uploadDirectory . $uploader->savedFileName);
1746
            redirect_header($redirectURL, 4, $errors);
1747
        }
1748
1749
        return null;
1750
    }
1751
1752
    /**
1753
     * @param      $filePath
1754
     * @param bool $isBinary
1755
     * @param bool $retBytes
1756
     *
1757
     * @return bool|int|mixed
1758
     */
1759
    public static function download($filePath, $isBinary = true, $retBytes = true)
1760
    {
1761
        // how many bytes per chunk
1762
        //$chunkSize = 1 * (1024 * 1024);
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1763
        $chunkSize    = 8 * (1024 * 1024); //8MB (highest possible fread length)
1764
        $buffer       = '';
0 ignored issues
show
Unused Code introduced by
$buffer 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...
1765
        $bytesCounter = 0;
1766
1767
        if ($isBinary === true) {
1768
            $handler = fopen($filePath, 'rb');
1769
        } else {
1770
            $handler = fopen($filePath, 'r');
1771
        }
1772
        if ($handler === false) {
1773
            return false;
1774
        }
1775
        while (!feof($handler)) {
1776
            $buffer = fread($handler, $chunkSize);
1777
            echo $buffer;
1778
            ob_flush();
1779
            flush();
1780
            if ($retBytes) {
1781
                $bytesCounter += strlen($buffer);
1782
            }
1783
        }
1784
        $status = fclose($handler);
1785
        if ($retBytes && $status) {
1786
            return $bytesCounter; // return num. bytes delivered like readfile() does.
1787
        }
1788
1789
        return $status;
1790
    }
1791
1792
    // IN PROGRESS
1793
    // IN PROGRESS
1794
    // IN PROGRESS
1795
    /**
1796
     * @author     Jack Mason
1797
     * @website    volunteer @ http://www.osipage.com, web access application and bookmarking tool.
1798
     * @copyright  Free script, use anywhere as you like, no attribution required
1799
     * @created    2014
1800
     * The script is capable of downloading really large files in PHP. Files greater than 2GB may fail in 32-bit windows or similar system.
1801
     * All incorrect headers have been removed and no nonsense code remains in this script. Should work well.
1802
     * The best and most recommended way to download files with PHP is using xsendfile, learn
1803
     * more here: https://tn123.org/mod_xsendfile/
1804
     *
1805
     * @param $filePath
1806
     * @param $fileMimetype
1807
     */
1808
    public static function largeDownload($filePath, $fileMimetype)
0 ignored issues
show
Unused Code introduced by
The parameter $fileMimetype is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
largeDownload uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
largeDownload uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1809
    {
1810
        /* You may need these ini settings too */
1811
        set_time_limit(0);
1812
        ini_set('memory_limit', '512M');
1813
        if (!empty($filePath)) {
1814
            $fileInfo            = pathinfo($filePath);
1815
            $fileName            = $fileInfo['basename'];
1816
            $fileExtension       = $fileInfo['extension'];
0 ignored issues
show
Unused Code introduced by
$fileExtension 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...
1817
            $default_contentType = 'application/octet-stream';
1818
            // to find and use specific content type, check out this IANA page : http://www.iana.org/assignments/media-types/media-types.xhtml
1819
            $contentType = $default_contentType;
1820
            if (false !== ($fileMimetype = !'')) {
1821
                $contentType = $fileMimetype;
1822
            }
1823
            if (file_exists($filePath)) {
1824
                $size   = filesize($filePath);
1825
                $offset = 0;
0 ignored issues
show
Unused Code introduced by
$offset 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...
1826
                $length = $size;
0 ignored issues
show
Unused Code introduced by
$length 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...
1827
                //HEADERS FOR PARTIAL DOWNLOAD FACILITY BEGINS
1828
                if (isset($_SERVER['HTTP_RANGE'])) {
1829
                    preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
1830
                    $offset  = (int)$matches[1];
1831
                    $length  = (int)$matches[2] - $offset;
1832
                    $fhandle = fopen($filePath, 'r');
1833
                    fseek($fhandle, $offset); // seek to the requested offset, this is 0 if it's not a partial content request
1834
                    $data = fread($fhandle, $length);
0 ignored issues
show
Unused Code introduced by
$data 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...
1835
                    fclose($fhandle);
1836
                    header('HTTP/1.1 206 Partial Content');
1837
                    header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $size);
1838
                }//HEADERS FOR PARTIAL DOWNLOAD FACILITY BEGINS
1839
                //USUAL HEADERS FOR DOWNLOAD
1840
                header('Content-Disposition: attachment;filename=' . $fileName);
1841
                header('Content-Type: ' . $contentType);
1842
                header('Accept-Ranges: bytes');
1843
                header('Pragma: public');
1844
                header('Expires: -1');
1845
                header('Cache-Control: no-cache');
1846
                header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
1847
                header('Content-Length: ' . filesize($filePath));
1848
                $chunksize = 8 * (1024 * 1024); //8MB (highest possible fread length)
1849
                if ($size > $chunksize) {
1850
                    $handle = fopen($_FILES['file']['tmp_name'], 'rb');
1851
                    $buffer = '';
0 ignored issues
show
Unused Code introduced by
$buffer 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...
1852
                    while (!feof($handle) && (connection_status() === CONNECTION_NORMAL)) {
1853
                        $buffer = fread($handle, $chunksize);
1854
                        print $buffer;
1855
                        ob_flush();
1856
                        flush();
1857
                    }
1858
                    if (connection_status() !== CONNECTION_NORMAL) {
1859
                        //TODO traslation
1860
                        echo 'Connection aborted';
1861
                    }
1862
                    fclose($handle);
1863
                } else {
1864
                    ob_clean();
1865
                    flush();
1866
                    readfile($filePath);
1867
                }
1868
            } else {
1869
                //TODO traslation
1870
                echo 'File does not exist!';
1871
            }
1872
        } else {
1873
            //TODO traslation
1874
            echo 'There is no file to download!';
1875
        }
1876
    }
1877
1878
    /**
1879
     * @param $selectedForumId
1880
     *
1881
     * @return int
1882
     */
1883
    public static function getForum($selectedForumId)
0 ignored issues
show
Coding Style introduced by
getForum uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1884
    {
1885
        $selectedForumId = (int)$selectedForumId;
1886
        echo "<select name='forumid'>";
1887
        echo "<option value='0'>----------------------</option>";
1888
        $result = $GLOBALS['xoopsDB']->query('SELECT forum_name, forum_id FROM ' . $GLOBALS['xoopsDB']->prefix('bb_forums') . ' ORDER BY forum_id');
1889
        while (false !== (list($forumName, $forumId) = $GLOBALS['xoopsDB']->fetchRow($result))) {
1890
            $optionSelected = '';
1891
            if ($forumId == $selectedForumId) {
1892
                $optionSelected = "selected='selected'";
1893
            }
1894
            echo "<option value='{$forumId}' {$optionSelected}>{$forumName}</option>";
1895
        }
1896
        echo '</select></div>';
1897
1898
        return $selectedForumId;
1899
    }
1900
1901
    /**
1902
     * @param $serverURL
1903
     *
1904
     * @return bool
1905
     */
1906
    public static function mirrorOnline($serverURL)
1907
    {
1908
        $fp = @fsockopen($serverURL, 80, $errno, $errstr, 5);
1909
        if (!$fp) {
1910
            $isOnline = false;
1911
        } else {
1912
            $isOnline = true;
1913
            fclose($fp);
1914
        }
1915
1916
        return $isOnline;
1917
    }
1918
1919
    /**
1920
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
1921
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
1922
     * www.cakephp.org
1923
     *
1924
     * @param string  $text         String to truncate.
1925
     * @param integer $length       Length of returned string, including ellipsis.
1926
     * @param string  $ending       Ending to be appended to the trimmed string.
1927
     * @param boolean $exact        If false, $text will not be cut mid-word
1928
     * @param boolean $considerHtml If true, HTML tags would be handled correctly
1929
     *
1930
     * @return string Trimmed string.
1931
     */
1932
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
1933
    {
1934
        if ($considerHtml) {
1935
            // if the plain text is shorter than the maximum length, return the whole text
1936
            if (strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
1937
                return $text;
1938
            }
1939
            // splits all html-tags to scanable lines
1940
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
1941
            $total_length = strlen($ending);
1942
            $open_tags    = array();
1943
            $truncate     = '';
1944
            foreach ($lines as $line_matchings) {
0 ignored issues
show
Bug introduced by
The expression $lines of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1945
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
1946
                if (!empty($line_matchings[1])) {
1947
                    // if it's an "empty element" with or without xhtml-conform closing slash
1948
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
1949
                        // do nothing
1950
                        // if tag is a closing tag
1951
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
1952
                        // delete tag from $open_tags list
1953
                        $pos = array_search($tag_matchings[1], $open_tags);
1954
                        if ($pos !== false) {
1955
                            unset($open_tags[$pos]);
1956
                        }
1957
                        // if tag is an opening tag
1958
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
1959
                        // add tag to the beginning of $open_tags list
1960
                        array_unshift($open_tags, strtolower($tag_matchings[1]));
1961
                    }
1962
                    // add html-tag to $truncate'd text
1963
                    $truncate .= $line_matchings[1];
1964
                }
1965
                // calculate the length of the plain text part of the line; handle entities as one character
1966
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
1967
                if ($total_length + $content_length > $length) {
1968
                    // the number of characters which are left
1969
                    $left            = $length - $total_length;
1970
                    $entities_length = 0;
1971
                    // search for html entities
1972
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
1973
                        // calculate the real length of all entities in the legal range
1974
                        foreach ($entities[0] as $entity) {
1975
                            if ($entity[1] + 1 - $entities_length <= $left) {
1976
                                $left--;
1977
                                $entities_length += strlen($entity[0]);
1978
                            } else {
1979
                                // no more characters left
1980
                                break;
1981
                            }
1982
                        }
1983
                    }
1984
                    $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
1985
                    // maximum lenght is reached, so get off the loop
1986
                    break;
1987
                } else {
1988
                    $truncate .= $line_matchings[2];
1989
                    $total_length += $content_length;
1990
                }
1991
                // if the maximum length is reached, get off the loop
1992
                if ($total_length >= $length) {
1993
                    break;
1994
                }
1995
            }
1996
        } else {
1997
            if (strlen($text) <= $length) {
1998
                return $text;
1999
            } else {
2000
                $truncate = substr($text, 0, $length - strlen($ending));
2001
            }
2002
        }
2003
        // if the words shouldn't be cut in the middle...
2004
        if (!$exact) {
2005
            // ...search the last occurance of a space...
2006
            $spacepos = strrpos($truncate, ' ');
2007
            if (isset($spacepos)) {
2008
                // ...and cut the text in this position
2009
                $truncate = substr($truncate, 0, $spacepos);
2010
            }
2011
        }
2012
        // add the defined ending to the text
2013
        $truncate .= $ending;
2014
        if ($considerHtml) {
2015
            // close all unclosed html-tags
2016
            foreach ($open_tags as $tag) {
0 ignored issues
show
Bug introduced by
The variable $open_tags 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...
2017
                $truncate .= '</' . $tag . '>';
2018
            }
2019
        }
2020
2021
        return $truncate;
2022
    }
2023
2024
    // Swish-e support EXPERIMENTAL
2025
    /**
2026
     * php4swish-e 1.1, a web search interface for the swish-e search engine.
2027
     * swish-e is a popular open-source search engine that runs on many platforms.
2028
     * More information on swish-e is available at swish-e.org.
2029
     * This code has been thoroughly tested and is ready for production
2030
     * on any UNIX or Linux server that has the swish-e search engine installed.
2031
     * You are free to modify this code as you see fit.
2032
     * You must specify the path of swish-e ($swish) and
2033
     * the location of the search index file ($swisheIndexFilePath).
2034
     * You will also need to change the default index file served if it is not index.php.
2035
     * If you want the meta description information to display completely,
2036
     * be sure the <meta description... information is on *one* line for each web page.
2037
     * If you wish to allow external search forms to call this script, be sure to set the
2038
     * form's action attribute to whatever you name this file.
2039
     * Suggestions for enhancements are welcome.
2040
     */
2041
    public static function swishe_check()
2042
    {
2043
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
2044
2045
        // Get the location of the document repository (the index files are located in the root)
2046
        $swisheDocPath = $wfdownloads->getConfig('uploaddir');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $swisheDocPath is correct as $wfdownloads->getConfig('uploaddir') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2047
        // Get the location of the SWISH-E executable
2048
        $swisheExePath = $wfdownloads->getConfig('swishe_exe_path');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $swisheExePath is correct as $wfdownloads->getConfig('swishe_exe_path') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2049
        // check if _binfilter.sh exists
2050
        if (!is_file("{$swisheDocPath}/_binfilter.sh")) {
2051
            return false;
2052
        }
2053
        // check if swish-e.conf exists
2054
        if (!is_file("{$swisheDocPath}/swish-e.conf")) {
2055
            return false;
2056
        }
2057
        // check if swish-e.exe exists
2058
        if (!is_file("{$swisheExePath}/swish-e.exe")) {
2059
            return false;
2060
        }
2061
2062
        return true;
2063
    }
2064
2065
    public static function swishe_config()
2066
    {
2067
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
2068
2069
        // Get the location of the document repository (the index files are located in the root)
2070
        $swisheDocPath = $wfdownloads->getConfig('uploaddir');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $swisheDocPath is correct as $wfdownloads->getConfig('uploaddir') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2071
        // Create _binfilter.sh
2072
        $file = "{$swisheDocPath}/_binfilter.sh";
2073
        $fp   = fopen($file, 'w') || die("<BR><BR>Unable to open $file");
0 ignored issues
show
Coding Style Compatibility introduced by
The method swishe_config() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2074
        fwrite($fp, "strings \"\$1\" - 2>/dev/null\n");
2075
        fclose($fp);
2076
        chmod($file, 0755);
2077
        unset($fp);
2078
        // Create swish-e.conf
2079
        $file = "{$swisheDocPath}/swish-e.conf";
2080
        $fp   = fopen($file, 'w') || die("<BR><BR>Unable to open {$file}");
0 ignored issues
show
Coding Style Compatibility introduced by
The method swishe_config() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2081
        // IndexDir [directories or files|URL|external program]
2082
        // IndexDir defines the source of the documents for Swish-e. Swish-e currently supports three file access methods: File system, HTTP (also called spidering), and prog for reading files from an external program.
2083
        fwrite($fp, "IndexDir {$swisheDocPath}/\n");
2084
        // IndexFile *path*
2085
        // Index file specifies the location of the generated index file. If not specified, Swish-e will create the file index.swish-e in the current directory.
2086
        fwrite($fp, "IndexFile {$swisheDocPath}/index.swish-e\n");
2087
        // TruncateDocSize *number of characters*
2088
        // TruncateDocSize limits the size of a document while indexing documents and/or using filters. This config directive truncates the numbers of read bytes of a document to the specified size. This means: if a document is larger, read only the specified numbers of bytes of the document.
2089
        //fwrite($fp, "TruncateDocSize 100000\n");
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2090
        // IndexReport [0|1|2|3]
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2091
        // This is how detailed you want reporting while indexing. You can specify numbers 0 to 3. 0 is totally silent, 3 is the most verbose. The default is 1.
2092
        fwrite($fp, "IndexReport 1\n");
2093
        // IndexContents [TXT|HTML|XML|TXT2|HTML2|XML2|TXT*|HTML*|XML*] *file extensions*
2094
        // The IndexContents directive assigns one of Swish-e's document parsers to a document, based on the its extension. Swish-e currently knows how to parse TXT, HTML, and XML documents.
2095
        fwrite($fp, "IndexContents TXT* .dat\n");
2096
        // FileFilter *suffix* "filter-prog" ["filter-options"]
2097
        // This maps file suffix (extension) to a filter program. If filter-prog starts with a directory delimiter (absolute path), Swish-e doesn't use the FilterDir settings, but uses the given filter-prog path directly.
2098
        //fwrite($fp, "FileFilter .dat \"{$swisheDocPath}/_binfilter.sh\" \"'%p'\"\n");
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2099
        // IndexOnly *list of file suffixes*
2100
        // This directive specifies the allowable file suffixes (extensions) while indexing. The default is to index all files specified in IndexDir.
2101
        fwrite($fp, "IndexOnly .dat\n");
2102
        // MinWordLimit *integer*
2103
        // Set the minimum length of an word. Shorter words will not be indexed. The default is 1 (as defined in src/config.h).
2104
        fwrite($fp, "MinWordLimit 3\n");
2105
        fclose($fp);
2106
        chmod($file, 0755);
2107
    }
2108
2109
    /**
2110
     * @param $swisheQueryWords
2111
     *
2112
     * @return array|bool
0 ignored issues
show
Documentation introduced by
Should the return type not be null|array|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
2113
     */
2114
    public static function swishe_search($swisheQueryWords)
2115
    {
2116
        /**
2117
         * @param $str
2118
         * @param $num_chars
2119
         * @return string
2120
         */
2121
        function strright($str, $num_chars)
2122
        {
2123
            $str_length = strlen($str);
2124
2125
            return substr($str, $str_length - $num_chars, $str_length);
2126
        }
2127
2128
        $wfdownloads = WfdownloadsWfdownloads::getInstance();
2129
2130
        $ret = false;
2131
        // IN PROGRESS
2132
        // IN PROGRESS
2133
        // IN PROGRESS
2134
        $swisheQueryWords = stripslashes($swisheQueryWords);
2135
        if (strlen($swisheQueryWords) > 2) {
2136
            //print "<BR>SEARCH!";
2137
            // Get the first word in $swisheQueryWords and use it for the $summary_query.
2138
            // IN PROGRESS
2139
            // IN PROGRESS
2140
            // IN PROGRESS
2141
            $summary_query   = str_replace("\"", ' ', $swisheQueryWords);
2142
            $summary_query   = trim($summary_query);
2143
            $summary_query_e = explode(' ', $summary_query);
2144
            $summary_query   = trim($summary_query_e[0]);
2145
            $summary_query   = rtrim($summary_query, '*');
0 ignored issues
show
Unused Code introduced by
$summary_query 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...
2146
2147
            //print "<BR>SQ:  ".$summary_query;
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2148
2149
            // Get the location of the document repository (the index files are located in the root)
2150
            $swisheDocPath        = $wfdownloads->getConfig('uploaddir');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $swisheDocPath is correct as $wfdownloads->getConfig('uploaddir') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2151
            $swisheDocPath_strlen = strlen($wfdownloads->getConfig('swishe_doc_path'));
2152
2153
            // Get the location of the SWISH-E executable
2154
            $swisheExePath = $wfdownloads->getConfig('swishe_exe_path');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $swisheExePath is correct as $wfdownloads->getConfig('swishe_exe_path') (which targets WfdownloadsWfdownloads::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2155
2156
            // Get search query
2157
            $swisheQueryWords    = escapeshellcmd($swisheQueryWords); // escape potentially malicious shell commands
2158
            $swisheQueryWords    = stripslashes($swisheQueryWords); // remove backslashes from search query
2159
            $swisheQueryWords    = preg_replace('#("|\')#', '', $swisheQueryWords); // remove quotes from search query
2160
            $swisheCommand       = "{$swisheExePath}/swish-e"; // path of swish-e command
2161
            $swisheIndexFilePath = "{$swisheDocPath}/index.swish-e"; // path of swish-e index file
2162
            $swisheSearchParams  = ''; // Additional search parameters
2163
            $swisheSearchParams .= '-H1'; // -H1 : print standard result header (default).
2164
            if ($wfdownloads->getConfig('swishe_search_limit') != 0) {
2165
                $swisheSearchParams .= " -m{$wfdownloads->getConfig('swishe_search_limit')}"; // -m *number* (max results)
2166
            }
2167
2168
            // Opens a pipe to swish-e
2169
            $swishePipeHandler = popen("{$swisheCommand} -w {$swisheQueryWords} -f {$swisheIndexFilePath} {$swisheSearchParams}", 'r');
2170
            if (!$swishePipeHandler) {
2171
                die('The search request generated an error...Please try again.');
0 ignored issues
show
Coding Style Compatibility introduced by
The method swishe_search() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2172
            }
2173
            error_log("{$swisheCommand} -w {$swisheQueryWords} -f {$swisheIndexFilePath} {$swisheSearchParams}");
2174
2175
            $line_cnt = 1;
2176
            // loop through each line of the pipe result (i.e. swish-e output) to find hit number
2177
            while (false !== ($nline = @fgets($swishePipeHandler, 1024))) {
2178
                if ($line_cnt == 4) {
2179
                    $num_line = $nline;
0 ignored issues
show
Unused Code introduced by
$num_line 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...
2180
                    break; // grab the 4th line, which contains the number of hits returned
2181
                }
2182
                ++$line_cnt;
2183
            }
2184
2185
            // strip out all but the number of hits
2186
            //$num_results = preg_replace('/# Number of hits: /', '', $num_line);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2187
2188
            //$table_header_flag = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2189
            //$disp_nff_flag = true;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2190
2191
            $ret = array();
2192
            while (false !== ($line = @fgets($swishePipeHandler, 4096))) {
2193
                // loop through each line of the pipe result (i.e. swish-e output)
2194
                if (preg_match("/^(\d+)\s+(\S+)\s+\"(.*)\"\s+(\d+)/", $line)) {
2195
                    // Skip commented-out lines and the last line
2196
                    $line    = explode('"', $line); // split the string into an array by quotation marks
2197
                    $line[1] = preg_replace('/[[:blank:]]/', '%%', $line[1]); // replace every space with %% for the phrase in quotation marks
2198
                    $line    = implode('"', $line); // collapse the array into a string
2199
                    $line    = preg_replace('/[[:blank:]]/', "\t", $line); // replace every space with a tab
2200
2201
                    list($relevance, $result_url, $result_title, $file_size) = explode("\t", $line); // split the line into an array by tabs; assign variable names to each column
2202
                    $relevance /= 10; // format relevance as a percentage for search results
2203
                    $full_path_and_file = $result_url;
0 ignored issues
show
Unused Code introduced by
$full_path_and_file 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...
2204
                    $result_url         = trim(substr($result_url, $swisheDocPath_strlen - 1, strlen($result_url)));
2205
                    $file_path          = strright($result_url, strlen($result_url) - 2);
2206
                    //                $file_path2 =       substr($result_url, (strlen($result_url) - (strlen($result_url) - 2)),strlen($result_url));
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2207
                    $ret[] = array(
2208
                        'relevance'    => $relevance,
2209
                        'result_url'   => $result_url,
2210
                        'result_title' => $result_title,
2211
                        'file_size'    => $file_size,
2212
                        'file_path'    => $file_path
2213
                    );
2214
                }
2215
            }
2216
            // close the shell pipe
2217
            pclose($swishePipeHandler);
2218
        }
2219
2220
        return $ret;
2221
    }
2222
    // Swish-e support EXPERIMENTAL
2223
2224
    // ===========================================================
2225
2226
}
2227