Completed
Push — master ( 1db5db...8743f5 )
by Michael
06:44
created

functions.php ➔ bookshop_getWysiwygForm()   D

Complexity

Conditions 18
Paths 18

Size

Total Lines 81
Code Lines 59

Duplication

Lines 40
Ratio 49.38 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 18
eloc 59
c 2
b 0
f 0
nc 18
nop 6
dl 40
loc 81
rs 4.9774

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
//  ------------------------------------------------------------------------ //
3
//                      BOOKSHOP - MODULE FOR XOOPS 2                        //
4
//                  Copyright (c) 2007, 2008 Instant Zero                    //
5
//                     <http://www.instant-zero.com/>                        //
6
// ------------------------------------------------------------------------- //
7
//  This program is free software; you can redistribute it and/or modify     //
8
//  it under the terms of the GNU General Public License as published by     //
9
//  the Free Software Foundation; either version 2 of the License, or        //
10
//  (at your option) any later version.                                      //
11
//                                                                           //
12
//  You may not change or alter any portion of this comment or credits       //
13
//  of supporting developers from this source code or any supporting         //
14
//  source code which is considered copyrighted (c) material of the          //
15
//  original comment or credit authors.                                      //
16
//                                                                           //
17
//  This program is distributed in the hope that it will be useful,          //
18
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
19
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
20
//  GNU General Public License for more details.                             //
21
//                                                                           //
22
//  You should have received a copy of the GNU General Public License        //
23
//  along with this program; if not, write to the Free Software              //
24
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
25
//  ------------------------------------------------------------------------ //
26
27
/**
28
 * Returns a module's option
29
 *
30
 * Return's a module's option (for the Bookshop module)
31
 *
32
 * @package       Bookshop
33
 * @author        Instant Zero (http://xoops.instant-zero.com)
34
 * @copyright (c) Instant Zero
35
 *
36
 * @param string $option module option's name
37
 *
38
 * @param string $repmodule
39
 *
40
 * @return bool
41
 */
42
function bookshop_getmoduleoption($option, $repmodule = 'bookshop')
43
{
44
    global $xoopsModuleConfig, $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...
45
    static $tbloptions = array();
46
    if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
47
        return $tbloptions[$option];
48
    }
49
50
    $retval = false;
51
    if (isset($xoopsModuleConfig) && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
52
        if (isset($xoopsModuleConfig[$option])) {
53
            $retval = $xoopsModuleConfig[$option];
54
        }
55
    } else {
56
        $module_handler = xoops_getHandler('module');
57
        $module         =& $module_handler->getByDirname($repmodule);
58
        $config_handler = xoops_getHandler('config');
59
        if ($module) {
60
            $moduleConfig =& $config_handler->getConfigsByCat(0, $module->getVar('mid'));
61
            if (isset($moduleConfig[$option])) {
62
                $retval = $moduleConfig[$option];
63
            }
64
        }
65
    }
66
    $tbloptions[$option] = $retval;
67
68
    return $retval;
69
}
70
71
/**
72
 * Indique si on utilise Xoops 2.2.x
73
 *
74
 * @return boolean vrai si Xoops 2.2.x sinon false
75
 */
76
function bookshop_is_x22()
77
{
78
    $x22 = false;
79
    $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
80
    if (substr($xv, 2, 1) == '2') {
81
        $x22 = true;
82
    }
83
84
    return $x22;
85
}
86
87
/**
88
 * Retreive an editor according to the module's option "form_options"
89
 *
90
 * @param string $caption Titre de la zone d'édition
91
 * @param string $name Nom de la zone d'édition
92
 * @param string $value Contenu initial de la zone d'édition
93
 * @param string $width Largeur de la zone d'édition
94
 * @param string $height Hauteur de la zone d'édition
95
 * @param string $supplemental Paramètres supplémentaires à passer à la zone d'édition
96
 * @return object L'éditeur
0 ignored issues
show
Documentation introduced by
Should the return type not be false|XoopsFormEditor|Xo...oopsFormWysiwygTextArea?

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...
97
 */
98
function bookshop_getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
99
{
100
    $editor                   = false;
101
    $x22                      = bookshop_is_x22();
102
    $editor_configs           = array();
103
    $editor_configs['name']   = $name;
104
    $editor_configs['value']  = $value;
105
    $editor_configs['rows']   = 35;
106
    $editor_configs['cols']   = 60;
107
    $editor_configs['width']  = $width;
108
    $editor_configs['height'] = $height;
109
110
    $editor_option = bookshop_getmoduleoption('bl_form_options');
111
112
    switch (strtolower($editor_option)) {
113 View Code Duplication
        case 'spaw':
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...
114
            if (!$x22) {
115
                if (is_readable(XOOPS_ROOT_PATH . '/class/spaw/formspaw.php')) {
116
                    include_once(XOOPS_ROOT_PATH . '/class/spaw/formspaw.php');
117
                    $editor = new XoopsFormSpaw($caption, $name, $value);
118
                }
119
            } else {
120
                $editor = new XoopsFormEditor($caption, 'spaw', $editor_configs);
121
            }
122
            break;
123
124 View Code Duplication
        case 'fck':
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...
125
            if (!$x22) {
126
                if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
127
                    include_once(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php');
128
                    $editor = new XoopsFormFckeditor($caption, $name, $value);
129
                }
130
            } else {
131
                $editor = new XoopsFormEditor($caption, 'fckeditor', $editor_configs);
132
            }
133
            break;
134
135 View Code Duplication
        case 'htmlarea':
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
            if (!$x22) {
137
                if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
138
                    include_once(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php');
139
                    $editor = new XoopsFormHtmlarea($caption, $name, $value);
140
                }
141
            } else {
142
                $editor = new XoopsFormEditor($caption, 'htmlarea', $editor_configs);
143
            }
144
            break;
145
146
        case 'dhtml':
147
            if (!$x22) {
148
                $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
149
            } else {
150
                $editor = new XoopsFormEditor($caption, 'dhtmltextarea', $editor_configs);
151
            }
152
            break;
153
154
        case 'textarea':
155
            $editor = new XoopsFormTextArea($caption, $name, $value);
156
            break;
157
158
        case 'tinyeditor':
159
            if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
160
                include_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
161
                $editor = new XoopsFormTinyeditorTextArea(array('caption' => $caption, 'name' => $name, 'value' => $value, 'width' => $width, 'height' => $height));
162
            }
163
            break;
164
165 View Code Duplication
        case 'koivi':
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...
166
            if (!$x22) {
167
                if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
168
                    include_once(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php');
169
                    $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, '100%', '250px', '');
170
                }
171
            } else {
172
                $editor = new XoopsFormEditor($caption, 'koivi', $editor_configs);
173
            }
174
            break;
175
    }
176
177
    return $editor;
178
}
179
180
/**
181
 * Create (in a link) a javascript confirmation's box
182
 *
183
 * @package         CP
184
 * @author          Instant Zero http://www.instant-zero.com
185
 * @copyright   (c) Instant Zero http://www.instant-zero.com
186
 *
187
 * @param string $msg	Le message à afficher
188
 * @param boolean $form Est-ce une confirmation pour un formulaire ?
189
 * @return string La "commande" javscript à insérer dans le lien
190
 */
191
function bookshop_JavascriptLinkConfirm($msg, $form = false)
192
{
193
    if (!$form) {
194
        return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $msg) . "')\"";
195
    } else {
196
        return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $msg) . "')\"";
197
    }
198
}
199
200
/**
201
 * Fonction chargée de renvoyer l'adresse IP du visiteur courant
202
 * En essayant de tenir compte des proxy
203
 *
204
 * @return string L'adresse IP (format Ipv4)
205
 */
206
function bookshop_IP()
0 ignored issues
show
Coding Style introduced by
bookshop_IP 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...
207
{
208
    $proxy_ip = '';
209
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
210
        $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
211
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
212
        $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
213
    } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
214
        $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
215
    } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
216
        $proxy_ip = $_SERVER['HTTP_FORWARDED'];
217
    } elseif (!empty($_SERVER['HTTP_VIA'])) {
218
        $proxy_ip = $_SERVER['HTTP_VIA'];
219
    } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
220
        $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
221
    } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
222
        $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
223
    }
224
    $regs = array();
225
    if (!empty($proxy_ip) && $is_ip = preg_match('/^([0-9]{1,3}\.){3,3}[0-9]{1,3}/', $proxy_ip, $regs) && count($regs) > 0) {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $is_ip = (preg_match('/^...s) && count($regs) > 0), Probably Intended Meaning: ($is_ip = preg_match('/^...s)) && count($regs) > 0
Loading history...
226
        $the_IP = $regs[0];
227
    } else {
228
        $the_IP = $_SERVER['REMOTE_ADDR'];
229
    }
230
231
    return $the_IP;
232
}
233
234
/**
235
 * Set the page's title, meta description and meta keywords
236
 * Datas are supposed to be sanitized
237
 *
238
 * @param string $page_title       Page's Title
239
 * @param string $meta_description Page's meta description
240
 * @param string $meta_keywords    Page's meta keywords
241
 * @return void
242
 */
243
function bookshop_set_metas($page_title = '', $meta_description = '', $meta_keywords = '')
244
{
245
    global $xoTheme, $xoTheme, $xoopsTpl;
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...
246
    $xoopsTpl->assign('xoops_pagetitle', $page_title);
247
    if (isset($xoTheme) && is_object($xoTheme)) {
248
        if (!empty($meta_keywords)) {
249
            $xoTheme->addMeta('meta', 'keywords', $meta_keywords);
250
        }
251
        if (!empty($meta_description)) {
252
            $xoTheme->addMeta('meta', 'description', $meta_description);
253
        }
254
    } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) {    // Compatibility for old Xoops versions
255
        if (!empty($meta_keywords)) {
256
            $xoopsTpl->assign('xoops_meta_keywords', $meta_keywords);
257
        }
258
        if (!empty($meta_description)) {
259
            $xoopsTpl->assign('xoops_meta_description', $meta_description);
260
        }
261
    }
262
}
263
264
/**
265
 * Envoi d'un email à partir d'un template à un groupe de personnes
266
 *
267
 * @param string $tpl_name	Nom du template à utiliser
268
 * @param array  $recipients Liste des destinataires
269
 * @param string $subject    Sujet du mail
270
 * @param array $variables	Variables à passer au template
271
 * @return boolean Le résultat de l'envoi du mail
272
 */
273
function bookshop_send_email_from_tpl($tpl_name, $recipients, $subject, $variables)
274
{
275
    global $xoopsConfig;
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...
276
    include_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
277
    if (!is_array($recipients)) {
278
        if (trim($recipients) == '') {
279
            return false;
280
        }
281
    } else {
282
        if (count($recipients) == 0) {
283
            return false;
284
        }
285
    }
286
    if (function_exists('xoops_getMailer')) {
287
        $xoopsMailer =& xoops_getMailer();
288
    } else {
289
        $xoopsMailer =& getMailer();
290
    }
291
292
    $xoopsMailer->useMail();
293
    $xoopsMailer->setTemplateDir(XOOPS_ROOT_PATH . '/modules/bookshop/language/' . $xoopsConfig['language'] . '/mail_template');
294
    $xoopsMailer->setTemplate($tpl_name);
295
    $xoopsMailer->setToEmails($recipients);
296
    // Change !
297
    //$xoopsMailer->setFromEmail('[email protected]');
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
298
    //$xoopsMailer->setFromName('PhotoSports');
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
299
    $xoopsMailer->setSubject($subject);
300
    foreach ($variables as $key => $value) {
301
        $xoopsMailer->assign($key, $value);
302
    }
303
    $res = $xoopsMailer->send();
304
    unset($xoopsMailer);
305
306
    $fp = @fopen(XOOPS_UPLOAD_PATH . '/logmail_bookshop.txt', 'a');
307
    if ($fp) {
308
        fwrite($fp, str_repeat('-', 120) . "\n");
309
        fwrite($fp, date('d/m/Y H:i:s') . "\n");
310
        fwrite($fp, 'Nom du template : ' . $tpl_name . "\n");
311
        fwrite($fp, 'Sujet du mail : ' . $subject . "\n");
312
        if (is_array($recipients)) {
313
            fwrite($fp, 'Destinaire(s) du mail : ' . implode(',', $recipients) . "\n");
314
        } else {
315
            fwrite($fp, 'Destinaire(s) du mail : ' . $recipients . "\n");
316
        }
317
        fwrite($fp, 'Variables transmises : ' . implode(',', $variables) . "\n");
318
        fclose($fp);
319
    }
320
321
    return $res;
322
}
323
324
/**
325
 * Remove module's cache
326
 *
327
 * @return void
328
 */
329
function bookshop_updateCache()
330
{
331
    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...
332
    $folder  = $xoopsModule->getVar('dirname');
333
    $tpllist = array();
0 ignored issues
show
Unused Code introduced by
$tpllist 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...
334
    include_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
335
    include_once XOOPS_ROOT_PATH . '/class/template.php';
336
    $tplfile_handler = xoops_getHandler('tplfile');
337
    $tpllist         = $tplfile_handler->find(null, null, null, $folder);
338
    xoops_template_clear_module_cache($xoopsModule->getVar('mid'));            // Clear module's blocks cache
339
340
    // Remove cache for each page.
341
    foreach ($tpllist as $onetemplate) {
342
        if ($onetemplate->getVar('tpl_type') === 'module') {
343
            // Note, I've been testing all the other methods (like the one of Smarty) and none of them run, that's why I have used this code
344
            $files_del = array();
0 ignored issues
show
Unused Code introduced by
$files_del 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...
345
            $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
346
            if (count($files_del) > 0 && is_array($files_del)) {
347
                foreach ($files_del as $one_file) {
348
                    if (is_file($one_file)) {
349
                        unlink($one_file);
350
                    }
351
                }
352
            }
353
        }
354
    }
355
}
356
357
/**
358
 * Create an infotip
359
 *
360
 * @param string $text Le texte dont on veut créer une bulle d'aide
361
 * @return string La bulle d'aide
362
 */
363
function bookshop_make_infotips($text)
364
{
365
    $infotips = bookshop_getmoduleoption('infotips');
366
    if ($infotips > 0) {
367
        $myts = MyTextSanitizer::getInstance();
368
369
        return $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
370
    }
371
}
372
373
/**
374
 * Redirect user with a message
375
 *
376
 * @param string $message message to display
377
 * @param string $url     The place where to go
378
 * @param        integer  timeout Time to wait before to redirect
379
 */
380
function bookshop_redirect($message = '', $url = 'index.php', $time = 2)
381
{
382
    redirect_header($url, $time, $message);
383
    exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function bookshop_redirect() 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...
384
}
385
386
/**
387
 * Renvoie l'objet du module ...
388
 *
389
 * @return object L'objet XoopsModule pour Bookshop
390
 */
391
function bookshop_get_module()
392
{
393
    static $mymodule;
394
    if (!isset($mymodule)) {
395
        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...
396
        if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == BOOKSHOP_DIRNAME) {
397
            $mymodule =& $xoopsModule;
398
        } else {
399
            $hModule  = xoops_getHandler('module');
400
            $mymodule = $hModule->getByDirname(BOOKSHOP_DIRNAME);
401
        }
402
    }
403
404
    return $mymodule;
405
}
406
407
/**
408
 * Renvoie le nom du module (tel que défini dans le gestionnaire de modules de Xoops)
409
 *
410
 * @return string Le nom du module
411
 */
412
function bookshop_get_module_name()
413
{
414
    static $module_name;
415
    if (!isset($module_name)) {
416
        $mymodule    = bookshop_get_module();
417
        $module_name = $mymodule->getVar('name');
418
    }
419
420
    return $module_name;
421
}
422
423
/**
424
 * Création d'une titre pour être utilisé par l'url rewriting
425
 *
426
 * @param string $content Le contenu a utiliser pour créer l'url
427
 * @param integer $urw Limite basse en dessous de laquelle chaque "mot" n'est pas utilisé
428
 * @return string Le texte qui peut être utilisé pour l'URL
429
 */
430
function bookshop_makeSEOurl($content, $urw = 1)
431
{
432
	$s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛÜŸÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
433
    $r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
434
    $content = strtr($content, $s, $r);
435
    $content = strip_tags($content);
436
    $content = strtolower($content);
437
    $content = htmlentities($content);
438
    $content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
439
    $content = html_entity_decode($content);
440
    $content = preg_replace('/quot/i', ' ', $content);
441
    $content = preg_replace("/'/i", ' ', $content);
442
    $content = preg_replace('/-/i', ' ', $content);
443
    $content = preg_replace('/[[:punct:]]/i', '', $content);
444
445
    // Selon option mais attention au fichier .htaccess !
446
    //$content = eregi_replace('[[:digit:]]','', $content);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
447
    $content = preg_replace('/[^a-z|A-Z|0-9]/', '-', $content);    // moi
448
449
    $words    = explode(' ', $content);
450
    $keywords = '';
451
    foreach ($words as $word) {
452
        if (strlen($word) >= $urw) {
453
            $keywords .= '-' . trim($word);
454
        }
455
    }
456
    if (!$keywords) {
457
        $keywords = '-';
458
    }
459
    // Supprime les tirets en double
460
    $keywords = str_replace('--', '-', $keywords);
461
	// Supprime un éventuel tiret à la fin de la chaine
462
    if (substr($keywords, strlen($keywords) - 1, 1) == '-') {
463
        $keywords = substr($keywords, 0, strlen($keywords) - 1);
464
    }
465
466
    return $keywords;
467
}
468
469
/**
470
 * Mise en place de l'appel à la feuille de style du module dans le template
471
 *
472
 * @return void
473
 */
474
function bookshop_setCSS()
475
{
476
    global $xoopsTpl;
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...
477
    $url = BOOKSHOP_URL . 'assets/css/bookshop.css';
478
    $xoopsTpl->assign('xoops_module_header', "<link rel=\"stylesheet\" type=\"text/css\" href=\"$url\" />");
479
}
480
481
/**
482
 * Création d'un titre pour les balises href des liens html
483
 *
484
 * @param string $title La chaine que l'on souhaite utiliser comme titre
485
 * @return string La chaine formatée pour être utilisée dans l'attribut title d'une balise anchor
486
 */
487
function bookshop_makeHrefTitle($title)
488
{
489
    $s = "\"'";
490
    $r = '  ';
491
492
    return strtr($title, $s, $r);
493
}
494
495
/**
496
 * Formate une monaie en fonction des préférences du module
497
 *
498
 * @param float $ttc Le montant à formater
499
 * @return string Le montant formaté
500
 */
501
function bookshop_formatMoney($ttc)
502
{
503
    $retval = sprintf('%0.' . bookshop_getmoduleoption('decimals_count') . 'f', $ttc);
504
505
    return $retval;
506
}
507
508
/**
509
 * Calcul du TTC � partir du HT et de la TVA
510
 *
511
 * @param float   $ht   Le montant HT dont on veut calculer le TTC
512
 * @param float $vat Le montant de la TVA
513
 * @param boolean $edit Est-ce que le montant est pour être visualisé, auquel cas on le formate
514
 *
515
 * @return float|string
516
 */
517
function bookshop_getTTC($ht, $vat, $edit = false)
518
{
519
    $ttc = $ht * (1 + ($vat / 100));
520
    if (!$edit) {
521
        return bookshop_formatMoney($ttc);
522
    } else {
523
        return $ttc;
524
    }
525
}
526
527
/**
528
 * Calcul de la réduction
529
 *
530
 * @param float $price Le montant dont on veut calculer la réduction
531
 * @param integer $dicount Le montant de la rédution, par exemple 10 pour 10%
0 ignored issues
show
Documentation introduced by
There is no parameter named $dicount. Did you maybe mean $discount?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
532
 * @return float Le montant de la réduction
533
 */
534
function bookshop_getDiscountedPrice($price, $discount)
535
{
536
    return $price - ($price * ($discount / 100));
537
}
538
539
/**
540
 * Renvoie le montant de la tva
541
 *
542
 * @param float $ht Le montant HT
543
 * @param float $vat Le montant de la TVA (par exemple 19.6)
544
 * @return float Le montant de la TVA
545
 */
546
function bookshop_getVAT($ht, $vat)
547
{
548
    return ($ht * $vat) / 100;
549
}
550
551
/**
552
 * Renvoie le HT d'un livre à partir de son TTC
553
 *
554
 * @param float $ttc  Le montant ttc
555
 * @param float ^vat Le montant de la TVA
556
 * @return string Le montant HT formaté avec les paramètres de monnaie
557
 */
558
function bookshop_getHT($ttc, $vat)
559
{
560
    $ht = $ttc / (1 + ($vat / 100));
561
562
    return bookshop_formatMoney($ht);
563
}
564
565
/**
566
 * Création des meta keywords à partir d'un contenu
567
 *
568
 * @param string $content Contenu dont il faut extraire les mots clés
569
 * @return void
570
 */
571
function bookshop_createmeta_keywords($content)
0 ignored issues
show
Coding Style introduced by
bookshop_createmeta_keywords uses the super-global variable $_SESSION 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...
572
{
573
    $keywordscount = bookshop_getmoduleoption('metagen_maxwords');
574
    $keywordsorder = bookshop_getmoduleoption('metagen_order');
575
576
    $tmp = array();
577
    // Search for the "Minimum keyword length"
578
    if (isset($_SESSION['bookshop_keywords_limit'])) {
579
        $limit = $_SESSION['bookshop_keywords_limit'];
580
    } else {
581
        $config_handler                      = xoops_getHandler('config');
582
        $xoopsConfigSearch                   =& $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
583
        $limit                               = $xoopsConfigSearch['keyword_min'];
584
        $_SESSION['bookshop_keywords_limit'] = $limit;
585
    }
586
    $myts            = MyTextSanitizer::getInstance();
587
    $content         = str_replace('<br>', ' ', $content);
588
    $content         = $myts->undoHtmlSpecialChars($content);
589
    $content         = strip_tags($content);
590
    $content         = strtolower($content);
591
    $search_pattern  = array('&nbsp;', "\t", "\r\n", "\r", "\n", ',', '.', "'", ';', ':', ')', '(', '"', '?', '!', '{', '}', '[', ']', '<', '>', '/', '+', '-', '_', '\\', '*');
592
    $replace_pattern = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
593
    $content         = str_replace($search_pattern, $replace_pattern, $content);
594
    $keywords        = explode(' ', $content);
595
    switch ($keywordsorder) {
596
        case 0:    // Ordre d'apparition dans le texte
597
            $keywords = array_unique($keywords);
598
            break;
599
		case 1:	// Ordre de fréquence des mots
600
            $keywords = array_count_values($keywords);
601
            asort($keywords);
602
            $keywords = array_keys($keywords);
603
            break;
604
		case 2:	// Ordre inverse de la fréquence des mots
605
            $keywords = array_count_values($keywords);
606
            arsort($keywords);
607
            $keywords = array_keys($keywords);
608
            break;
609
    }
610
    // Remove black listed words
611
    if (xoops_trim(bookshop_getmoduleoption('metagen_blacklist')) != '') {
612
        $metagen_blacklist = str_replace("\r", '', bookshop_getmoduleoption('metagen_blacklist'));
613
        $metablack         = explode("\n", $metagen_blacklist);
614
        array_walk($metablack, 'trim');
615
        $keywords = array_diff($keywords, $metablack);
616
    }
617
618
    foreach ($keywords as $keyword) {
619
        if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
620
            $tmp[] = $keyword;
621
        }
622
    }
623
    $tmp = array_slice($tmp, 0, $keywordscount);
624
    if (count($tmp) > 0) {
625
        return implode(',', $tmp);
626
    } else {
627
        if (!isset($config_handler) || !is_object($config_handler)) {
628
            $config_handler = xoops_getHandler('config');
629
        }
630
        $xoopsConfigMetaFooter =& $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
631
        if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
632
            return $xoopsConfigMetaFooter['meta_keywords'];
633
        } else {
634
            return '';
635
        }
636
    }
637
}
638
639
/**
640
 * Renvoie la liste des utilisateurs d'un groupe
641
 *
642
 * @param int $group_id	Groupe recherché
643
 * @return array tableau d'objets XoopsUser
644
 */
645
function bookshop_getUsersFromGroup($group_id)
646
{
647
    $tbl_users      = array();
0 ignored issues
show
Unused Code introduced by
$tbl_users 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...
648
    $member_handler = xoops_getHandler('member');
649
    $tbl_users      = $member_handler->getUsersByGroup($group_id, true);
650
651
    return $tbl_users;
652
}
653
654
/**
655
 * Renvoie la liste des adresses email d'un groupe
656
 *
657
 * @param int $group_id	Le numéro du groupe
658
 * @return array La liste des emails
659
 */
660
function bookshop_getEmailsFromGroup($group_id)
661
{
662
    $ret       = array();
663
    $tbl_users = bookshop_getUsersFromGroup($group_id);
664
    foreach ($tbl_users as $user) {
665
        $ret[] = $user->getVar('email');
666
    }
667
668
    return $ret;
669
}
670
671
/**
672
 * Inutilisé, sert normalement pour l'IPN
673
 * @param $datastream
674
 * @param $url
675
 * @return string
676
 */
677
function bookshop_post_it($datastream, $url)
678
{
679
    $url     = preg_replace('@^http://@i', '', $url);
680
    $host    = substr($url, 0, strpos($url, '/'));
681
    $uri     = strstr($url, '/');
682
    $reqbody = '';
683
    foreach ($datastream as $key => $val) {
684
        if (!empty($reqbody)) {
685
            $reqbody .= '&';
686
        }
687
        $reqbody .= $key . '=' . urlencode($val);
688
    }
689
    $contentlength = strlen($reqbody);
690
    $reqheader     = "POST $uri HTTP/1.1\r\n" . "Host: $host\n" . "Content-Type: application/x-www-form-urlencoded\r\n" . "Content-Length: $contentlength\r\n\r\n" . "$reqbody\r\n";
691
692
    return $reqheader;
693
}
694
695
/**
696
 * Verify that the current user is a member of the Admin group
697
 *
698
 * @return booleean Admin or not
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

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...
699
 */
700
function bookshop_isAdmin()
701
{
702
    global $xoopsUser, $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...
703
    if (is_object($xoopsUser)) {
704
        if (in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups())) {
705
            return true;
706
        } else {
707
            if (isset($xoopsModule)) {
708
                if ($xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
709
                    return true;
710
                } else {
711
                    return false;
712
                }
713
            } else {
714
                return false;
715
            }
716
        }
717
    } else {
718
        return false;
719
    }
720
}
721
722
/**
723
 * Indique si l'utilisateur courant fait partie d'une groupe donné (avec gestion de cache)
724
 *
725
 * @param int $group
726
 * @param integer $groupe Groupe recherché
0 ignored issues
show
Documentation introduced by
There is no parameter named $groupe. Did you maybe mean $group?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
727
 * @return boolean vrai si l'utilisateur fait partie du groupe, faux sinon
728
 */
729
function bookshop_isMemberOfGroup($group = 0)
730
{
731
    global $xoopsUser;
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...
732
    static $tblBuffer = array();
733
    $retval = false;
0 ignored issues
show
Unused Code introduced by
$retval 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...
734
    if (is_object($xoopsUser)) {
735
        $uid = $xoopsUser->getVar('uid');
736
    } else {
737
        $uid = 0;
738
    }
739
    if (is_array($tblBuffer) && array_key_exists($group, $tblBuffer)) {
740
        $retval = $tblBuffer[$group];
741
    } else {
742
        $member_handler    = xoops_getHandler('member');
743
        $tblGroups         = $member_handler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
744
        $retval            = in_array($group, $tblGroups);
745
        $tblBuffer[$group] = $retval;
746
    }
747
748
    return $retval;
749
}
750
751
/**
752
 * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
753
 *
754
 * @return boolean Yes = we need to add them, false = no
755
 */
756
function bookshop_needsAsterisk()
757
{
758
    if (bookshop_is_x22()) {
759
        return false;
760
    }
761
    if (strpos(strtolower(XOOPS_VERSION), 'legacy') === false) {
762
        $xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
763
        if ((int)substr($xv, 4, 2) >= 17) {
764
            return false;
765
        }
766
    }
767
768
    return true;
769
}
770
771
/**
772
 * Mark the mandatory fields of a form with a star
773
 *
774
 * @param object $sform The form to modify
775
 * @internal param string $caracter The character to use to mark fields
776
 * @return object The modified form
777
 */
778
function bookshop_formMarkRequiredFields(&$sform)
779
{
780
    if (bookshop_needsAsterisk()) {
781
        $tblRequired = array();
782
        foreach ($sform->getRequired() as $item) {
783
            $tblRequired[] = $item->_name;
784
        }
785
        $tblElements = array();
786
        $tblElements = &$sform->getElements();
787
        $cnt         = count($tblElements);
788
        for ($i = 0; $i < $cnt; ++$i) {
789
            if (is_object($tblElements[$i]) && in_array($tblElements[$i]->_name, $tblRequired)) {
790
                $tblElements[$i]->_caption .= ' *';
791
            }
792
        }
793
    }
794
795
    return $sform;
796
}
797