Completed
Push — master ( 76b4a1...141e43 )
by Michael
06:17 queued 02:44
created

functions.php ➔ xfgb_clear_tmp_files()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 18
rs 8.8571
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 33 and the first side effect is on line 26.

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
// $Id: include/functions.php,v 1.4 2006/01/01 C.Felix AKA the Cat
3
//  ------------------------------------------------------------------------ //
4
//             XF Guestbook                                                  //
5
// ------------------------------------------------------------------------- //
6
//  This program is free software; you can redistribute it and/or modify     //
7
//  it under the terms of the GNU General Public License as published by     //
8
//  the Free Software Foundation; either version 2 of the License, or        //
9
//  (at your option) any later version.                                      //
10
//                                                                           //
11
//  You may not change or alter any portion of this comment or credits       //
12
//  of supporting developers from this source code or any supporting         //
13
//  source code which is considered copyrighted (c) material of the          //
14
//  original comment or credit authors.                                      //
15
//                                                                           //
16
//  This program is distributed in the hope that it will be useful,          //
17
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
18
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
19
//  GNU General Public License for more details.                             //
20
//                                                                           //
21
//  You should have received a copy of the GNU General Public License        //
22
//  along with this program; if not, write to the Free Software              //
23
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
24
//  ------------------------------------------------------------------------ //
25
26
global $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
27
$cacheFolder = XOOPS_UPLOAD_PATH . '/' . $xoopsModule->getVar('dirname');
28
if (!is_dir($cacheFolder)) {
29
    mkdir($cacheFolder, 0777);
30
    file_put_contents($cacheFolder . '/index.html', '');
31
}
32
33
function xfgb_upload()
0 ignored issues
show
Coding Style introduced by
xfgb_upload 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
xfgb_upload 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...
34
{
35
    global $xoopsModule, $xoopsModuleConfig, $preview_name, $msgstop;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
36
    $created = time();
37
    $ext     = preg_replace("/^.+\.([^.]+)$/sU", "\\1", $_FILES['photo']['name']);
0 ignored issues
show
Unused Code introduced by
$ext 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...
38
    include_once(XOOPS_ROOT_PATH . '/class/uploader.php');
39
    $field = $_POST['xoops_upload_file'][0];
40
    if (!empty($field) || $field !== '') {
41
        // Check if file uploaded
42
        if ($_FILES[$field]['tmp_name'] === '' || !is_readable($_FILES[$field]['tmp_name'])) {
43
            $msgstop .= sprintf(_MD_XFGB_FILEERROR, $xoopsModuleConfig['photo_maxsize']);
44
        } else {
45
            $photos_dir              = XOOPS_UPLOAD_PATH . '/' . $xoopsModule->getVar('dirname');
46
            $array_allowed_mimetypes = array('image/gif', 'image/pjpeg', 'image/jpeg', 'image/x-png');
47
            $uploader                =
48
                new XoopsMediaUploader($photos_dir, $array_allowed_mimetypes, $xoopsModuleConfig['photo_maxsize'], $xoopsModuleConfig['photo_maxwidth'], $xoopsModuleConfig['photo_maxheight']);
49
            if ($uploader->fetchMedia($field) && $uploader->upload()) {
50
                if (isset($preview_name)) {
51
                    @unlink("$photos_dir/" . $preview_name);
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...
52
                }
53
                $tmp_name     = $uploader->getSavedFileName();
54
                $ext          = preg_replace("/^.+\.([^.]+)$/sU", "\\1", $tmp_name);
55
                $preview_name = 'tmp_' . $created . '.' . $ext;
56
                rename("$photos_dir/$tmp_name", "$photos_dir/$preview_name");
57
            } else {
58
                $msgstop .= $uploader->getErrors();
59
            }
60
        }
61
    }
62
}
63
64
/**
65
 * @param null $criteria
66
 * @param int  $limit
67
 * @param int  $start
68
 * @return array
69
 */
70 View Code Duplication
function xfgb_getCountry($criteria = null, $limit = 0, $start = 0)
0 ignored issues
show
Best Practice introduced by
The function xfgb_getCountry() has been defined more than once; this definition is ignored, only the first definition in admin/country_manager.php (L201-217) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
Duplication introduced by
This function 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...
71
{
72
    global $xoopsDB, $action;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
73
    $ret = array();
74
    $sql = 'SELECT * FROM ' . $xoopsDB->prefix('xfguestbook_country');
75
    if (isset($criteria) && $criteria !== '') {
76
        $sql .= ' WHERE ' . $criteria;
77
    }
78
    $sql .= ' ORDER BY country_code ASC';
79
    $result = $xoopsDB->query($sql, $limit, $start);
80
    while ($myrow = $xoopsDB->fetchArray($result)) {
81
        array_push($ret, $myrow);
82
    }
83
84
    return $ret;
85
}
86
87
/**
88
 * @param null $criteria
89
 * @param int  $limit
90
 * @param int  $start
91
 * @return array
92
 */
93
function xfgb_getAllCountry($criteria = null, $limit = 0, $start = 0)
94
{
95
    global $xoopsDB, $action, $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
96
    $ret = array();
97
    $sql = 'SELECT country_code, country_name FROM ' . $xoopsDB->prefix('xfguestbook_country');
98
    if (isset($criteria) && $criteria !== '') {
99
        $sql .= ' WHERE ' . $criteria;
100
    }
101
    $sql .= ' ORDER BY country_code ASC';
102
    $result = $xoopsDB->query($sql, $limit, $start);
103
    while ($myrow = $xoopsDB->fetchArray($result)) {
104
        //      $ret[$myrow['country_code']] = $myrow['country_name'];
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...
105
        $ret[$xoopsModuleConfig['flagdir'] . '/' . $myrow['country_code']] = $myrow['country_name'];
106
    }
107
108
    return $ret;
109
}
110
111
/**
112
 * @param $user_id
113
 * @return bool
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...
114
 */
115
function xfgb_get_user_data($user_id)
116
{
117
    global $xoopsUser, $xoopsModuleConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
118
119
    if (!(int)$user_id) {
120
        return false;
121
    }
122
123
    $poster = new XoopsUser($user_id);
124
    if ($poster->isActive()) {
125
        $xoopsUser ? $a_poster['poster'] = "<a href='../../userinfo.php?uid=$user_id'>" . $poster->uname() . '</a>' : $a_poster['poster'] = $poster->uname();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$a_poster was never initialized. Although not strictly required by PHP, it is generally a good practice to add $a_poster = 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...
126
        if ($xoopsModuleConfig['display_avatar']) {
127
            $rank = $poster->rank();
128
            $rank['title'] ? $a_poster['rank'] = $rank['title'] : $a_poster['rank'] = '';
129
            $rank['image'] ? $a_poster['rank_img'] = "<img src='" . XOOPS_URL . '/uploads/' . $rank['image'] . "' alt='' />" : $a_poster['rank_img'] = '';
130
            $poster->user_avatar() ? $a_poster['avatar'] = "<img src='" . XOOPS_URL . '/uploads/' . $poster->user_avatar() . "' alt='' />" : $a_poster['avatar'] = '';
131
        } else {
132
            $a_poster['rank']     = '';
133
            $a_poster['avatar']   = '';
134
            $a_poster['rank_img'] = '';
135
        }
136
137
        return $a_poster;
138
    } else {
139
        return false;
140
    }
141
}
142
143
// Effacement fichiers temporaires
144
/**
145
 * @param        $dir_path
146
 * @param string $prefix
147
 * @return int
148
 */
149
function xfgb_clear_tmp_files($dir_path, $prefix = 'tmp_')
150
{
151
    if (!($dir = @opendir($dir_path))) {
152
        return 0;
153
    }
154
    $ret        = 0;
155
    $prefix_len = strlen($prefix);
156
    while (($file = readdir($dir)) !== false) {
157
        if (strncmp($file, $prefix, $prefix_len) === 0) {
158
            if (@unlink("$dir_path/$file")) {
159
                $ret++;
160
            }
161
        }
162
    }
163
    closedir($dir);
164
165
    return $ret;
166
}
167
168
// IP bannies (modérés automatiquement)
169
/**
170
 * @param null $all
171
 * @return array
172
 */
173
function xfgb_get_badips($all = null)
174
{
175
    global $xoopsDB;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
176
    $ret    = array();
177
    $sql    = 'SELECT * FROM ' . $xoopsDB->prefix('xfguestbook_badips');
178
    $result = $xoopsDB->query($sql);
179
    if ($all) {
180
        while ($myrow = $xoopsDB->fetchArray($result)) {
181
            array_push($ret, $myrow);
182
        }
183
    } else {
184
        while (list($ip_id, $ip_value) = $xoopsDB->fetchRow($result)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $ip_id 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...
185
            $ret[] = $ip_value;
186
        }
187
    }
188
189
    return $ret;
190
}
191
192
/**
193
 * @param $email
194
 * @return bool
195
 */
196
function email_exist($email)
197
{
198
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
199
        return false;
200
    } elseif (!checkdnsrr(array_pop(explode('@', $email)), 'MX')) {
0 ignored issues
show
Bug introduced by
explode('@', $email) cannot be passed to array_pop() as the parameter $array expects a reference.
Loading history...
201
        return false;
202
    } else {
203
        return true;
204
    }
205
}
206