Passed
Push — master ( e643a0...1f75e2 )
by Michael
03:19
created

Utility::isX23()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace XoopsModules\Oledrion;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
*/
14
15
/**
16
 * oledrion
17
 *
18
 * @copyright   {@link https://xoops.org/ XOOPS Project}
19
 * @license     {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
20
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
21
 */
22
23
/**
24
 * A set of useful and common functions
25
 *
26
 * @author        Hervé Thouzard - Instant Zero (http://xoops.instant-zero.com)
27
 * @copyright (c) Instant Zero
28
 *
29
 * Note: You should be able to use it without the need to instanciate it.
30
 */
31
32
use WideImage\WideImage;
0 ignored issues
show
Bug introduced by
The type WideImage\WideImage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type WideImage\WideImage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
33
use Xmf\Request;
0 ignored issues
show
Bug introduced by
The type Xmf\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type Xmf\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
use XoopsModules\Oledrion;
35
36
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
37
38
/**
39
 * Class Oledrion\Utility
40
 */
41
class Utility extends \XoopsObject
0 ignored issues
show
Bug introduced by
The type XoopsObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type XoopsObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
42
{
43
    const MODULE_NAME = 'oledrion';
44
45
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
46
47
    use Common\ServerStats; // getServerStats Trait
48
49
    use Common\FilesManagement; // Files Management Trait
50
51
    //--------------- Custom module methods -----------------------------
52
53
    /**
54
     * Access the only instance of this class
55
     *
56
     * @return Oledrion\Utility
57
     *
58
     * @static
59
     * @staticvar   object
60
     */
61
    public static function getInstance()
62
    {
63
        static $instance;
64
        if (null === $instance) {
65
            $instance = new static();
66
        }
67
68
        return $instance;
69
    }
70
71
    /**
72
     * Returns a module's option (with cache)
73
     *
74
     * @param  string $option    module option's name
75
     * @param  bool   $withCache Do we have to use some cache ?
76
     * @return mixed   option's value
77
     */
78
    public static function getModuleOption($option, $withCache = true)
79
    {
80
        global $xoopsModuleConfig, $xoopsModule;
81
        $repmodule = static::MODULE_NAME;
82
        static $options = [];
83
        if (is_array($options) && array_key_exists($option, $options) && $withCache) {
84
            return $options[$option];
85
        }
86
87
        $retval = null;
88
        if (null !== $xoopsModuleConfig && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
89
            if (isset($xoopsModuleConfig[$option])) {
90
                $retval = $xoopsModuleConfig[$option];
91
            }
92
        } else {
93
            /** @var \XoopsModuleHandler $moduleHandler */
94
            $moduleHandler = xoops_getHandler('module');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

94
            $moduleHandler = /** @scrutinizer ignore-call */ xoops_getHandler('module');
Loading history...
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

94
            $moduleHandler = /** @scrutinizer ignore-call */ xoops_getHandler('module');
Loading history...
95
            $module        = $moduleHandler->getByDirname($repmodule);
96
            $configHandler = xoops_getHandler('config');
97
            if ($module) {
98
                $moduleConfig = $configHandler->getConfigsByCat(0, $module->getVar('mid'));
99
                if (isset($moduleConfig[$option])) {
100
                    $retval = $moduleConfig[$option];
101
                }
102
            }
103
        }
104
        $options[$option] = $retval;
105
106
        return $retval;
107
    }
108
109
    /**
110
     * Is Xoops 2.3.x ?
111
     *
112
     * @return bool
113
     */
114
    public static function isX23()
115
    {
116
        $x23 = false;
117
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
118
        if ((int)mb_substr($xv, 2, 1) >= 3) {
119
            $x23 = true;
120
        }
121
122
        return $x23;
123
    }
124
125
    /**
126
     * Is Xoops 2.0.x ?
127
     *
128
     * @return bool
129
     */
130
    public static function isX20()
131
    {
132
        $x20 = false;
133
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
134
        if ('0' == mb_substr($xv, 2, 1)) {
135
            $x20 = true;
136
        }
137
138
        return $x20;
139
    }
140
141
    /**
142
     * Retreive an editor according to the module's option "form_options"
143
     *
144
     * @param  string $caption Caption to give to the editor
145
     * @param  string $name    Editor's name
146
     * @param  string $value   Editor's value
147
     * @param  string $width   Editor's width
148
     * @param  string $height  Editor's height
149
     * @param  string $supplemental
150
     * @return bool|\XoopsFormEditor The editor to use
151
     */
152
    public static function getWysiwygForm(
153
        $caption,
154
        $name,
155
        $value = '',
156
        $width = '100%',
157
        $height = '400px',
158
        $supplemental = '')
159
    {
160
        /** @var Oledrion\Helper $helper */
161
        $helper                   = Oledrion\Helper::getInstance();
162
        $editor                   = false;
163
        $editor_configs           = [];
164
        $editor_configs['name']   = $name;
165
        $editor_configs['value']  = $value;
166
        $editor_configs['rows']   = 35;
167
        $editor_configs['cols']   = 60;
168
        $editor_configs['width']  = '100%';
169
        $editor_configs['height'] = '400px';
170
171
        $editor_option = mb_strtolower(static::getModuleOption('editorAdmin'));
0 ignored issues
show
Unused Code introduced by
The assignment to $editor_option is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $editor_option is dead and can be removed.
Loading history...
172
        //        $editor = new \XoopsFormEditor($caption, $editor_option, $editor_configs);
173
        //        public function __construct($caption, $name, $configs = null, $nohtml = false, $OnFailure = '')
174
175
        if ($helper->isUserAdmin()) {
176
            $editor = new \XoopsFormEditor($caption, $helper->getConfig('editorAdmin'), $editor_configs, $nohtml = false, $onfailure = 'textarea');
0 ignored issues
show
Bug introduced by
The type XoopsFormEditor was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type XoopsFormEditor was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
177
        } else {
178
            $editor = new \XoopsFormEditor($caption, $helper->getConfig('editorUser'), $editor_configs, $nohtml = false, $onfailure = 'textarea');
179
        }
180
181
        return $editor;
182
    }
183
184
    /**
185
     * Create (in a link) a javascript confirmation's box
186
     *
187
     * @param  string $message Message to display
188
     * @param  bool   $form    Is this a confirmation for a form ?
189
     * @return string  the javascript code to insert in the link (or in the form)
190
     */
191
    public static function javascriptLinkConfirm($message, $form = false)
192
    {
193
        if (!$form) {
194
            return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
195
        }
196
197
        return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
198
    }
199
200
    /**
201
     * Get current user IP
202
     *
203
     * @return string IP address (format Ipv4)
204
     */
205
    public static function IP()
206
    {
207
        $proxy_ip = '';
208
        if (\Xmf\Request::hasVar('HTTP_X_FORWARDED_FOR', 'SERVER')) {
209
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
210
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
211
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
212
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
213
            $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
214
        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
215
            $proxy_ip = $_SERVER['HTTP_FORWARDED'];
216
        } elseif (!empty($_SERVER['HTTP_VIA'])) {
217
            $proxy_ip = $_SERVER['HTTP_VIA'];
218
        } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
219
            $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
220
        } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
221
            $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
222
        }
223
        $regs = [];
224
        //if (!empty($proxy_ip) && $is_ip = ereg('^([0-9]{1,3}\.){3,3}[0-9]{1,3}', $proxy_ip, $regs) && count($regs) > 0) {
225
        if (!empty($proxy_ip) && filter_var($proxy_ip, FILTER_VALIDATE_IP) && count($regs) > 0) {
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 $pageTitle       Page's Title
239
     * @param  string $metaDescription Page's meta description
240
     * @param  string $metaKeywords    Page's meta keywords
241
     */
242
    public static function setMetas($pageTitle = '', $metaDescription = '', $metaKeywords = '')
243
    {
244
        global $xoTheme, $xoTheme, $xoopsTpl;
245
        $xoopsTpl->assign('xoops_pagetitle', $pageTitle);
246
        if (null !== $xoTheme && is_object($xoTheme)) {
247
            if (!empty($metaKeywords)) {
248
                $xoTheme->addMeta('meta', 'keywords', $metaKeywords);
249
            }
250
            if (!empty($metaDescription)) {
251
                $xoTheme->addMeta('meta', 'description', $metaDescription);
252
            }
253
        } elseif (null !== $xoopsTpl && is_object($xoopsTpl)) {
254
            // Compatibility for old Xoops versions
255
            if (!empty($metaKeywords)) {
256
                $xoopsTpl->assign('xoops_meta_keywords', $metaKeywords);
257
            }
258
            if (!empty($metaDescription)) {
259
                $xoopsTpl->assign('xoops_meta_description', $metaDescription);
260
            }
261
        }
262
    }
263
264
    /**
265
     * Send an email from a template to a list of recipients
266
     *
267
     * @param         $tplName
268
     * @param  array  $recipients List of recipients
269
     * @param  string $subject    Email's subject
270
     * @param  array  $variables  Varirables to give to the template
271
     * @return bool   Result of the send
272
     * @internal param string $tpl_name Template's name
273
     */
274
    public static function sendEmailFromTpl($tplName, $recipients, $subject, $variables)
275
    {
276
        global $xoopsConfig;
277
        require_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
278
        if (!is_array($recipients)) {
0 ignored issues
show
introduced by
The condition is_array($recipients) is always true.
Loading history...
introduced by
The condition is_array($recipients) is always true.
Loading history...
279
            if ('' === trim($recipients)) {
280
                return false;
281
            }
282
        } else {
283
            if (0 === count($recipients)) {
284
                return false;
285
            }
286
        }
287
        if (function_exists('xoops_getMailer')) {
288
            $xoopsMailer = xoops_getMailer();
289
        } else {
290
            $xoopsMailer = xoops_getMailer();
291
        }
292
293
        $xoopsMailer->useMail();
294
        $templateDir = XOOPS_ROOT_PATH . '/modules/' . static::MODULE_NAME . '/language/' . $xoopsConfig['language'] . '/mail_template';
295
        if (!is_dir($templateDir)) {
296
            $templateDir = XOOPS_ROOT_PATH . '/modules/' . static::MODULE_NAME . '/language/english/mail_template';
297
        }
298
        $xoopsMailer->setTemplateDir($templateDir);
299
        $xoopsMailer->setTemplate($tplName);
300
        $xoopsMailer->setToEmails($recipients);
301
        // TODO: Change !
302
        // $xoopsMailer->setFromEmail('[email protected]');
303
        //$xoopsMailer->setFromName('MonSite');
304
        $xoopsMailer->setSubject($subject);
305
        foreach ($variables as $key => $value) {
306
            $xoopsMailer->assign($key, $value);
307
        }
308
        $res = $xoopsMailer->send();
309
        unset($xoopsMailer);
310
        // B.R. $filename = XOOPS_UPLOAD_PATH . '/logmail_' . static::MODULE_NAME . '.php';
311
        $filename = OLEDRION_UPLOAD_PATH . '/logmail_' . static::MODULE_NAME . '.php';
312
        if (!file_exists($filename)) {
313
            $fp = @fopen($filename, 'ab');
314
            if ($fp) {
0 ignored issues
show
introduced by
$fp is of type resource|false, thus it always evaluated to false.
Loading history...
introduced by
$fp is of type resource|false, thus it always evaluated to false.
Loading history...
315
                fwrite($fp, "<?php exit(); ?>\n");
316
                fclose($fp);
317
            }
318
        }
319
        $fp = @fopen($filename, 'ab');
320
321
        if ($fp) {
0 ignored issues
show
introduced by
$fp is of type resource|false, thus it always evaluated to false.
Loading history...
introduced by
$fp is of type resource|false, thus it always evaluated to false.
Loading history...
322
            fwrite($fp, str_repeat('-', 120) . "\n");
323
            fwrite($fp, date('d/m/Y H:i:s') . "\n");
324
            fwrite($fp, 'Template name : ' . $tplName . "\n");
325
            fwrite($fp, 'Email subject : ' . $subject . "\n");
326
            if (is_array($recipients)) {
327
                fwrite($fp, 'Recipient(s) : ' . implode(',', $recipients) . "\n");
328
            } else {
329
                fwrite($fp, 'Recipient(s) : ' . $recipients . "\n");
330
            }
331
            fwrite($fp, 'Transmited variables : ' . implode(',', $variables) . "\n");
332
            fclose($fp);
333
        }
334
335
        return $res;
336
    }
337
338
    /**
339
     * Remove module's cache
340
     */
341
    public static function updateCache()
342
    {
343
        global $xoopsModule;
344
        $folder  = $xoopsModule->getVar('dirname');
345
        $tpllist = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $tpllist is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $tpllist is dead and can be removed.
Loading history...
346
        require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
347
        require_once XOOPS_ROOT_PATH . '/class/template.php';
348
        /** @var \XoopsTplfileHandler $tplfileHandler */
349
        $tplfileHandler = xoops_getHandler('tplfile');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

349
        $tplfileHandler = /** @scrutinizer ignore-call */ xoops_getHandler('tplfile');
Loading history...
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

349
        $tplfileHandler = /** @scrutinizer ignore-call */ xoops_getHandler('tplfile');
Loading history...
350
        $tpllist        = $tplfileHandler->find(null, null, null, $folder);
351
        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
0 ignored issues
show
Bug introduced by
The function xoops_template_clear_module_cache was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

351
        /** @scrutinizer ignore-call */ 
352
        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
Loading history...
Bug introduced by
The function xoops_template_clear_module_cache was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

351
        /** @scrutinizer ignore-call */ 
352
        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
Loading history...
352
353
        /** @var \XoopsTplfile $onetemplate */
354
        foreach ($tpllist as $onetemplate) {
355
            // Remove cache for each page.
356
            if ('module' === $onetemplate->getVar('tpl_type')) {
357
                //  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
358
                $files_del = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $files_del is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $files_del is dead and can be removed.
Loading history...
359
                $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_CACHE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_CACHE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
360
                if (is_array($files_del) && count($files_del) > 0) {
361
                    foreach ($files_del as $one_file) {
362
                        if (is_file($one_file)) {
363
                            if (false === @unlink($one_file)) {
364
                                throw new \RuntimeException('The file '.$one_file.' could not be deleted.');
365
                            }
366
                        }
367
                    }
368
                }
369
            }
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 mixed  $time
379
     */
380
    public static function redirect($message = '', $url = 'index.php', $time = 2)
381
    {
382
        redirect_header($url, $time, $message);
0 ignored issues
show
Bug introduced by
The function redirect_header was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

382
        /** @scrutinizer ignore-call */ 
383
        redirect_header($url, $time, $message);
Loading history...
Bug introduced by
The function redirect_header was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

382
        /** @scrutinizer ignore-call */ 
383
        redirect_header($url, $time, $message);
Loading history...
383
    }
384
385
    /**
386
     * Internal function used to get the handler of the current module
387
     *
388
     * @return \XoopsModule The module
389
     */
390
    protected static function _getModule()
391
    {
392
        static $mymodule;
393
        if (null === $mymodule) {
394
            global $xoopsModule;
395
            if (null !== $xoopsModule && is_object($xoopsModule) && OLEDRION_DIRNAME == $xoopsModule->getVar('dirname')) {
396
                $mymodule = $xoopsModule;
397
            } else {
398
                /** @var \XoopsModuleHandler $moduleHandler */
399
                $moduleHandler = xoops_getHandler('module');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

399
                $moduleHandler = /** @scrutinizer ignore-call */ xoops_getHandler('module');
Loading history...
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

399
                $moduleHandler = /** @scrutinizer ignore-call */ xoops_getHandler('module');
Loading history...
400
                $mymodule      = $moduleHandler->getByDirname(OLEDRION_DIRNAME);
401
            }
402
        }
403
404
        return $mymodule;
405
    }
406
407
    /**
408
     * Returns the module's name (as defined by the user in the module manager) with cache
409
     * @return string Module's name
410
     */
411
    public static function getModuleName()
412
    {
413
        static $moduleName;
414
        if (null === $moduleName) {
415
            $mymodule   = static::_getModule();
416
            $moduleName = $mymodule->getVar('name');
417
        }
418
419
        return $moduleName;
420
    }
421
422
    /**
423
     * Create a title for the href tags inside html links
424
     *
425
     * @param  string $title Text to use
426
     * @return string Formated text
427
     */
428
    public static function makeHrefTitle($title)
429
    {
430
        $s = "\"'";
431
        $r = '  ';
432
433
        return strtr($title, $s, $r);
434
    }
435
436
    /**
437
     * Retourne la liste des utilisateurs appartenants à un groupe
438
     *
439
     * @param  int $groupId Searched group
440
     * @return array Array of XoopsUsers
441
     */
442
    public static function getUsersFromGroup($groupId)
443
    {
444
        $users         = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $users is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $users is dead and can be removed.
Loading history...
445
        /** @var \XoopsMemberHandler $memberHandler */
446
        $memberHandler = xoops_getHandler('member');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

446
        $memberHandler = /** @scrutinizer ignore-call */ xoops_getHandler('member');
Loading history...
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

446
        $memberHandler = /** @scrutinizer ignore-call */ xoops_getHandler('member');
Loading history...
447
        $users         = $memberHandler->getUsersByGroup($groupId, true);
448
449
        return $users;
450
    }
451
452
    /**
453
     * Retourne la liste des emails des utilisateurs membres d'un groupe
454
     *
455
     * @param $groupId
456
     * @return array Emails list
457
     * @internal param int $group_id Group's number
458
     */
459
    public static function getEmailsFromGroup($groupId)
460
    {
461
        $ret   = [];
462
        $users = static::getUsersFromGroup($groupId);
463
        foreach ($users as $user) {
464
            $ret[] = $user->getVar('email');
465
        }
466
467
        return $ret;
468
    }
469
470
    /**
471
     * Vérifie que l'utilisateur courant fait partie du groupe des administrateurs
472
     *
473
     * @return bool Admin or not
474
     */
475
    public static function isAdmin()
476
    {
477
        global $xoopsUser, $xoopsModule;
478
        if (is_object($xoopsUser)) {
479
            if (in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups(), true)) {
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_GROUP_ADMIN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_GROUP_ADMIN was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
480
                return true;
481
            }
482
483
            if (null !== $xoopsModule && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
484
                return true;
485
            }
486
        }
487
488
        return false;
489
    }
490
491
    /**
492
     * Returns the current date in the Mysql format
493
     *
494
     * @return string Date in the Mysql format
495
     */
496
    public static function getCurrentSQLDate()
497
    {
498
        return date('Y-m-d'); // 2007-05-02
499
    }
500
501
    /**
502
     * @return bool|string
503
     */
504
    public static function getCurrentSQLDateTime()
505
    {
506
        return date('Y-m-d H:i:s'); // 2007-05-02
507
    }
508
509
    /**
510
     * Convert a Mysql date to the human's format
511
     *
512
     * @param  string $date The date to convert
513
     * @param  string $format
514
     * @return string The date in a human form
515
     */
516
    public static function SQLDateToHuman($date, $format = 'l')
517
    {
518
        if ('0000-00-00' !== $date && '' !== xoops_trim($date)) {
0 ignored issues
show
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

518
        if ('0000-00-00' !== $date && '' !== /** @scrutinizer ignore-call */ xoops_trim($date)) {
Loading history...
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

518
        if ('0000-00-00' !== $date && '' !== /** @scrutinizer ignore-call */ xoops_trim($date)) {
Loading history...
519
            return formatTimestamp(strtotime($date), $format);
0 ignored issues
show
Bug introduced by
The function formatTimestamp was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

519
            return /** @scrutinizer ignore-call */ formatTimestamp(strtotime($date), $format);
Loading history...
Bug introduced by
The function formatTimestamp was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

519
            return /** @scrutinizer ignore-call */ formatTimestamp(strtotime($date), $format);
Loading history...
520
        }
521
522
        return '';
523
    }
524
525
    /**
526
     * Convert a timestamp to a Mysql date
527
     *
528
     * @param int $timestamp The timestamp to use
529
     * @return string  The date in the Mysql format
530
     */
531
    public static function timestampToMysqlDate($timestamp)
532
    {
533
        return date('Y-m-d', (int)$timestamp);
534
    }
535
536
    /**
537
     * Conversion d'un dateTime Mysql en date lisible en français
538
     * @param $dateTime
539
     * @return bool|string
540
     */
541
    public static function sqlDateTimeToFrench($dateTime)
542
    {
543
        return date('d/m/Y H:i:s', strtotime($dateTime));
544
    }
545
546
    /**
547
     * Convert a timestamp to a Mysql datetime form
548
     * @param int $timestamp The timestamp to use
549
     * @return string  The date and time in the Mysql format
550
     */
551
    public static function timestampToMysqlDateTime($timestamp)
552
    {
553
        return date('Y-m-d H:i:s', $timestamp);
554
    }
555
556
    /**
557
     * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
558
     *
559
     * @return bool Yes = we need to add them, false = no
560
     */
561
    public static function needsAsterisk()
562
    {
563
        if (static::isX23()) {
564
            return false;
565
        }
566
        if (false !== mb_stripos(XOOPS_VERSION, 'impresscms')) {
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_VERSION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
567
            return false;
568
        }
569
        if (false === mb_stripos(XOOPS_VERSION, 'legacy')) {
570
            $xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
0 ignored issues
show
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

570
            $xv = /** @scrutinizer ignore-call */ xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
Loading history...
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

570
            $xv = /** @scrutinizer ignore-call */ xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
Loading history...
571
            if ((int)mb_substr($xv, 4, 2) >= 17) {
572
                return false;
573
            }
574
        }
575
576
        return true;
577
    }
578
579
    /**
580
     * Mark the mandatory fields of a form with a star
581
     *
582
     * @param  \XoopsForm $sform The form to modify
0 ignored issues
show
Bug introduced by
The type XoopsForm was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type XoopsForm was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
583
     * @return \XoopsForm The modified form
584
     * @internal param string $character The character to use to mark fields
585
     */
586
    public static function &formMarkRequiredFields(&$sform)
587
    {
588
        if (static::needsAsterisk()) {
589
            $required = [];
590
            foreach ($sform->getRequired() as $item) {
591
                $required[] = $item->_name;
592
            }
593
            $elements = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $elements is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $elements is dead and can be removed.
Loading history...
594
            $elements = $sform->getElements();
595
            $cnt      = count($elements);
0 ignored issues
show
Unused Code introduced by
The assignment to $cnt is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $cnt is dead and can be removed.
Loading history...
596
            foreach ($elements as $i => $iValue) {
597
                if (is_object($elements[$i]) && in_array($iValue->_name, $required, true)) {
598
                    $iValue->_caption .= ' *';
599
                }
600
            }
601
        }
602
603
        return $sform;
604
    }
605
606
    /**
607
     * Create an html heading (from h1 to h6)
608
     *
609
     * @param  string $title The text to use
610
     * @param int     $level Level to return
611
     * @return string  The heading
612
     */
613
    public static function htitle($title = '', $level = 1)
614
    {
615
        printf('<h%01d>%s</h%01d>', $level, $title, $level);
616
    }
617
618
    /**
619
     * Create a unique upload filename
620
     *
621
     * @param  string $folder   The folder where the file will be saved
622
     * @param  string $fileName Original filename (coming from the user)
623
     * @param  bool   $trimName Do we need to create a "short" unique name ?
624
     * @return string  The unique filename to use (with its extension)
625
     */
626
    public static function createUploadName($folder, $fileName, $trimName = false)
627
    {
628
        $uid           = '';
629
        $workingfolder = $folder;
630
        if ('/' !== xoops_substr($workingfolder, mb_strlen($workingfolder) - 1, 1)) {
0 ignored issues
show
Bug introduced by
The function xoops_substr was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

630
        if ('/' !== /** @scrutinizer ignore-call */ xoops_substr($workingfolder, mb_strlen($workingfolder) - 1, 1)) {
Loading history...
Bug introduced by
The function xoops_substr was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

630
        if ('/' !== /** @scrutinizer ignore-call */ xoops_substr($workingfolder, mb_strlen($workingfolder) - 1, 1)) {
Loading history...
631
            $workingfolder .= '/';
632
        }
633
        $ext  = basename($fileName);
634
        $ext  = explode('.', $ext);
635
        $ext  = '.' . $ext[count($ext) - 1];
636
        $true = true;
637
        while ($true) {
638
            $ipbits = explode('.', $_SERVER['REMOTE_ADDR']);
639
            list($usec, $sec) = explode(' ', microtime());
640
            $usec *= 65536;
641
            $sec  = ((int)$sec) & 0xFFFF;
642
643
            if ($trimName) {
644
                $uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
645
            } else {
646
                $uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
647
            }
648
            if (!file_exists($workingfolder . $uid . $ext)) {
649
                $true = false;
650
            }
651
        }
652
653
        return $uid . $ext;
654
    }
655
656
    /**
657
     * Replace html entities with their ASCII equivalent
658
     *
659
     * @param  string $chaine The string undecode
660
     * @return string The undecoded string
661
     */
662
    public static function unhtml($chaine)
663
    {
664
        $search = $replace = [];
665
        $chaine = html_entity_decode($chaine);
666
667
        for ($i = 0; $i <= 255; ++$i) {
668
            $search[]  = '&#' . $i . ';';
669
            $replace[] = chr($i);
670
        }
671
        $replace[] = '...';
672
        $search[]  = '…';
673
        $replace[] = "'";
674
        $search[]  = '‘';
675
        $replace[] = "'";
676
        $search[]  = '’';
677
        $replace[] = '-';
678
        $search[]  = '&bull;'; // $replace[] = '•';
679
        $replace[] = '—';
680
        $search[]  = '&mdash;';
681
        $replace[] = '-';
682
        $search[]  = '&ndash;';
683
        $replace[] = '-';
684
        $search[]  = '&shy;';
685
        $replace[] = '"';
686
        $search[]  = '&quot;';
687
        $replace[] = '&';
688
        $search[]  = '&amp;';
689
        $replace[] = 'ˆ';
690
        $search[]  = '&circ;';
691
        $replace[] = '¡';
692
        $search[]  = '&iexcl;';
693
        $replace[] = '¦';
694
        $search[]  = '&brvbar;';
695
        $replace[] = '¨';
696
        $search[]  = '&uml;';
697
        $replace[] = '¯';
698
        $search[]  = '&macr;';
699
        $replace[] = '´';
700
        $search[]  = '&acute;';
701
        $replace[] = '¸';
702
        $search[]  = '&cedil;';
703
        $replace[] = '¿';
704
        $search[]  = '&iquest;';
705
        $replace[] = '˜';
706
        $search[]  = '&tilde;';
707
        $replace[] = "'";
708
        $search[]  = '&lsquo;'; // $replace[]='‘';
709
        $replace[] = "'";
710
        $search[]  = '&rsquo;'; // $replace[]='’';
711
        $replace[] = '‚';
712
        $search[]  = '&sbquo;';
713
        $replace[] = "'";
714
        $search[]  = '&ldquo;'; // $replace[]='“';
715
        $replace[] = "'";
716
        $search[]  = '&rdquo;'; // $replace[]='”';
717
        $replace[] = '„';
718
        $search[]  = '&bdquo;';
719
        $replace[] = '‹';
720
        $search[]  = '&lsaquo;';
721
        $replace[] = '›';
722
        $search[]  = '&rsaquo;';
723
        $replace[] = '<';
724
        $search[]  = '&lt;';
725
        $replace[] = '>';
726
        $search[]  = '&gt;';
727
        $replace[] = '±';
728
        $search[]  = '&plusmn;';
729
        $replace[] = '«';
730
        $search[]  = '&laquo;';
731
        $replace[] = '»';
732
        $search[]  = '&raquo;';
733
        $replace[] = '×';
734
        $search[]  = '&times;';
735
        $replace[] = '÷';
736
        $search[]  = '&divide;';
737
        $replace[] = '¢';
738
        $search[]  = '&cent;';
739
        $replace[] = '£';
740
        $search[]  = '&pound;';
741
        $replace[] = '¤';
742
        $search[]  = '&curren;';
743
        $replace[] = '¥';
744
        $search[]  = '&yen;';
745
        $replace[] = '§';
746
        $search[]  = '&sect;';
747
        $replace[] = '©';
748
        $search[]  = '&copy;';
749
        $replace[] = '¬';
750
        $search[]  = '&not;';
751
        $replace[] = '®';
752
        $search[]  = '&reg;';
753
        $replace[] = '°';
754
        $search[]  = '&deg;';
755
        $replace[] = 'µ';
756
        $search[]  = '&micro;';
757
        $replace[] = '¶';
758
        $search[]  = '&para;';
759
        $replace[] = '·';
760
        $search[]  = '&middot;';
761
        $replace[] = '†';
762
        $search[]  = '&dagger;';
763
        $replace[] = '‡';
764
        $search[]  = '&Dagger;';
765
        $replace[] = '‰';
766
        $search[]  = '&permil;';
767
        $replace[] = 'Euro';
768
        $search[]  = '&euro;'; // $replace[]='€'
769
        $replace[] = '¼';
770
        $search[]  = '&frac14;';
771
        $replace[] = '½';
772
        $search[]  = '&frac12;';
773
        $replace[] = '¾';
774
        $search[]  = '&frac34;';
775
        $replace[] = '¹';
776
        $search[]  = '&sup1;';
777
        $replace[] = '²';
778
        $search[]  = '&sup2;';
779
        $replace[] = '³';
780
        $search[]  = '&sup3;';
781
        $replace[] = 'á';
782
        $search[]  = '&aacute;';
783
        $replace[] = 'Á';
784
        $search[]  = '&Aacute;';
785
        $replace[] = 'â';
786
        $search[]  = '&acirc;';
787
        $replace[] = 'Â';
788
        $search[]  = '&Acirc;';
789
        $replace[] = 'à';
790
        $search[]  = '&agrave;';
791
        $replace[] = 'À';
792
        $search[]  = '&Agrave;';
793
        $replace[] = 'å';
794
        $search[]  = '&aring;';
795
        $replace[] = 'Å';
796
        $search[]  = '&Aring;';
797
        $replace[] = 'ã';
798
        $search[]  = '&atilde;';
799
        $replace[] = 'Ã';
800
        $search[]  = '&Atilde;';
801
        $replace[] = 'ä';
802
        $search[]  = '&auml;';
803
        $replace[] = 'Ä';
804
        $search[]  = '&Auml;';
805
        $replace[] = 'ª';
806
        $search[]  = '&ordf;';
807
        $replace[] = 'æ';
808
        $search[]  = '&aelig;';
809
        $replace[] = 'Æ';
810
        $search[]  = '&AElig;';
811
        $replace[] = 'ç';
812
        $search[]  = '&ccedil;';
813
        $replace[] = 'Ç';
814
        $search[]  = '&Ccedil;';
815
        $replace[] = 'ð';
816
        $search[]  = '&eth;';
817
        $replace[] = 'Ð';
818
        $search[]  = '&ETH;';
819
        $replace[] = 'é';
820
        $search[]  = '&eacute;';
821
        $replace[] = 'É';
822
        $search[]  = '&Eacute;';
823
        $replace[] = 'ê';
824
        $search[]  = '&ecirc;';
825
        $replace[] = 'Ê';
826
        $search[]  = '&Ecirc;';
827
        $replace[] = 'è';
828
        $search[]  = '&egrave;';
829
        $replace[] = 'È';
830
        $search[]  = '&Egrave;';
831
        $replace[] = 'ë';
832
        $search[]  = '&euml;';
833
        $replace[] = 'Ë';
834
        $search[]  = '&Euml;';
835
        $replace[] = 'ƒ';
836
        $search[]  = '&fnof;';
837
        $replace[] = 'í';
838
        $search[]  = '&iacute;';
839
        $replace[] = 'Í';
840
        $search[]  = '&Iacute;';
841
        $replace[] = 'î';
842
        $search[]  = '&icirc;';
843
        $replace[] = 'Î';
844
        $search[]  = '&Icirc;';
845
        $replace[] = 'ì';
846
        $search[]  = '&igrave;';
847
        $replace[] = 'Ì';
848
        $search[]  = '&Igrave;';
849
        $replace[] = 'ï';
850
        $search[]  = '&iuml;';
851
        $replace[] = 'Ï';
852
        $search[]  = '&Iuml;';
853
        $replace[] = 'ñ';
854
        $search[]  = '&ntilde;';
855
        $replace[] = 'Ñ';
856
        $search[]  = '&Ntilde;';
857
        $replace[] = 'ó';
858
        $search[]  = '&oacute;';
859
        $replace[] = 'Ó';
860
        $search[]  = '&Oacute;';
861
        $replace[] = 'ô';
862
        $search[]  = '&ocirc;';
863
        $replace[] = 'Ô';
864
        $search[]  = '&Ocirc;';
865
        $replace[] = 'ò';
866
        $search[]  = '&ograve;';
867
        $replace[] = 'Ò';
868
        $search[]  = '&Ograve;';
869
        $replace[] = 'º';
870
        $search[]  = '&ordm;';
871
        $replace[] = 'ø';
872
        $search[]  = '&oslash;';
873
        $replace[] = 'Ø';
874
        $search[]  = '&Oslash;';
875
        $replace[] = 'õ';
876
        $search[]  = '&otilde;';
877
        $replace[] = 'Õ';
878
        $search[]  = '&Otilde;';
879
        $replace[] = 'ö';
880
        $search[]  = '&ouml;';
881
        $replace[] = 'Ö';
882
        $search[]  = '&Ouml;';
883
        $replace[] = 'œ';
884
        $search[]  = '&oelig;';
885
        $replace[] = 'Œ';
886
        $search[]  = '&OElig;';
887
        $replace[] = 'š';
888
        $search[]  = '&scaron;';
889
        $replace[] = 'Š';
890
        $search[]  = '&Scaron;';
891
        $replace[] = 'ß';
892
        $search[]  = '&szlig;';
893
        $replace[] = 'þ';
894
        $search[]  = '&thorn;';
895
        $replace[] = 'Þ';
896
        $search[]  = '&THORN;';
897
        $replace[] = 'ú';
898
        $search[]  = '&uacute;';
899
        $replace[] = 'Ú';
900
        $search[]  = '&Uacute;';
901
        $replace[] = 'û';
902
        $search[]  = '&ucirc;';
903
        $replace[] = 'Û';
904
        $search[]  = '&Ucirc;';
905
        $replace[] = 'ù';
906
        $search[]  = '&ugrave;';
907
        $replace[] = 'Ù';
908
        $search[]  = '&Ugrave;';
909
        $replace[] = 'ü';
910
        $search[]  = '&uuml;';
911
        $replace[] = 'Ü';
912
        $search[]  = '&Uuml;';
913
        $replace[] = 'ý';
914
        $search[]  = '&yacute;';
915
        $replace[] = 'Ý';
916
        $search[]  = '&Yacute;';
917
        $replace[] = 'ÿ';
918
        $search[]  = '&yuml;';
919
        $replace[] = 'Ÿ';
920
        $search[]  = '&Yuml;';
921
        $chaine    = str_replace($search, $replace, $chaine);
922
923
        return $chaine;
924
    }
925
926
    /**
927
     * Création d'une titre pour être utilisé par l'url rewriting
928
     *
929
     * @param  string $content  Le texte à utiliser pour créer l'url
930
     * @param int     $urw      La limite basse pour créer les mots
931
     * @return string  Le texte à utiliser pour l'url
932
     *                          Note, some parts are from Solo's code
933
     */
934
    public static function makeSeoUrl($content, $urw = 1)
935
    {
936
        $s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛܟÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
937
        $r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
938
        $content = static::unhtml($content); // First, remove html entities
939
        $content = strtr($content, $s, $r);
940
        $content = strip_tags($content);
941
        $content = mb_strtolower($content);
942
        $content = htmlentities($content, ENT_QUOTES | ENT_HTML5); // TODO: Vérifier
943
        $content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
944
        $content = html_entity_decode($content);
945
        $content = str_ireplace('quot', ' ', $content);
946
        $content = preg_replace("/'/i", ' ', $content);
947
        $content = preg_replace('/-/i', ' ', $content);
948
        $content = preg_replace('/[[:punct:]]/i', '', $content);
949
950
        // Selon option mais attention au fichier .htaccess !
951
        // $content = eregi_replace('[[:digit:]]','', $content);
952
        $content = preg_replace('/[^a-z|A-Z|0-9]/', '-', $content);
953
954
        $words    = explode(' ', $content);
955
        $keywords = '';
956
        foreach ($words as $word) {
957
            if (mb_strlen($word) >= $urw) {
958
                $keywords .= '-' . trim($word);
959
            }
960
        }
961
        if (!$keywords) {
962
            $keywords = '-';
963
        }
964
        // Supprime les tirets en double
965
        $keywords = str_replace('---', '-', $keywords);
966
        $keywords = str_replace('--', '-', $keywords);
967
        // Supprime un éventuel tiret à la fin de la chaine
968
        if ('-' == mb_substr($keywords, mb_strlen($keywords) - 1, 1)) {
969
            $keywords = mb_substr($keywords, 0, -1);
970
        }
971
972
        return $keywords;
973
    }
974
975
    /**
976
     * Create the meta keywords based on the content
977
     *
978
     * @param  string $content Content from which we have to create metakeywords
979
     * @return string The list of meta keywords
980
     */
981
    public static function createMetaKeywords($content)
982
    {
983
        $keywordscount = static::getModuleOption('metagen_maxwords');
984
        $keywordsorder = static::getModuleOption('metagen_order');
985
986
        $tmp = [];
987
        // Search for the "Minimum keyword length"
988
        if (\Xmf\Request::hasVar('oledrion_keywords_limit', 'SESSION')) {
989
            $limit = $_SESSION['oledrion_keywords_limit'];
990
        } else {
991
            $configHandler                       = xoops_getHandler('config');
992
            $xoopsConfigSearch                   = $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

992
            $xoopsConfigSearch                   = /** @scrutinizer ignore-call */ $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
Loading history...
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

992
            $xoopsConfigSearch                   = /** @scrutinizer ignore-call */ $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
Loading history...
993
            $limit                               = $xoopsConfigSearch['keyword_min'];
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_CONF_SEARCH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_CONF_SEARCH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
994
            $_SESSION['oledrion_keywords_limit'] = $limit;
995
        }
996
        $myts            = \MyTextSanitizer::getInstance();
997
        $content         = str_replace('<br>', ' ', $content);
0 ignored issues
show
Bug introduced by
The type MyTextSanitizer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type MyTextSanitizer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
998
        $content         = $myts->undoHtmlSpecialChars($content);
999
        $content         = strip_tags($content);
1000
        $content         = mb_strtolower($content);
1001
        $search_pattern  = [
1002
            '&nbsp;',
1003
            "\t",
1004
            "\r\n",
1005
            "\r",
1006
            "\n",
1007
            ',',
1008
            '.',
1009
            "'",
1010
            ';',
1011
            ':',
1012
            ')',
1013
            '(',
1014
            '"',
1015
            '?',
1016
            '!',
1017
            '{',
1018
            '}',
1019
            '[',
1020
            ']',
1021
            '<',
1022
            '>',
1023
            '/',
1024
            '+',
1025
            '-',
1026
            '_',
1027
            '\\',
1028
            '*',
1029
        ];
1030
        $replace_pattern = [
1031
            ' ',
1032
            ' ',
1033
            ' ',
1034
            ' ',
1035
            ' ',
1036
            ' ',
1037
            ' ',
1038
            ' ',
1039
            '',
1040
            '',
1041
            '',
1042
            '',
1043
            '',
1044
            '',
1045
            '',
1046
            '',
1047
            '',
1048
            '',
1049
            '',
1050
            '',
1051
            '',
1052
            '',
1053
            '',
1054
            '',
1055
            '',
1056
            '',
1057
            '',
1058
        ];
1059
        $content         = str_replace($search_pattern, $replace_pattern, $content);
1060
        $keywords        = explode(' ', $content);
1061
        switch ($keywordsorder) {
1062
            case 0: // Ordre d'apparition dans le texte
1063
1064
                $keywords = array_unique($keywords);
1065
1066
                break;
1067
            case 1: // Ordre de fréquence des mots
1068
1069
                $keywords = array_count_values($keywords);
1070
                asort($keywords);
1071
                $keywords = array_keys($keywords);
1072
1073
                break;
1074
            case 2: // Ordre inverse de la fréquence des mots
1075
1076
                $keywords = array_count_values($keywords);
1077
                arsort($keywords);
1078
                $keywords = array_keys($keywords);
1079
1080
                break;
1081
        }
1082
        // Remove black listed words
1083
        if ('' !== xoops_trim(static::getModuleOption('metagen_blacklist'))) {
1084
            $metagen_blacklist = str_replace("\r", '', static::getModuleOption('metagen_blacklist'));
0 ignored issues
show
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1084
            $metage/** @scrutinizer ignore-call */ n_blacklist = str_replace("\r", '', static::getModuleOption('metagen_blacklist'));
Loading history...
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1084
            $metage/** @scrutinizer ignore-call */ n_blacklist = str_replace("\r", '', static::getModuleOption('metagen_blacklist'));
Loading history...
1085
            $metablack         = explode("\n", $metagen_blacklist);
1086
            array_walk($metablack, 'trim');
1087
            $keywords = array_diff($keywords, $metablack);
1088
        }
1089
1090
        foreach ($keywords as $keyword) {
1091
            if (!is_numeric($keyword) && mb_strlen($keyword) >= $limit) {
1092
                $tmp[] = $keyword;
1093
            }
1094
        }
1095
        $tmp = array_slice($tmp, 0, $keywordscount);
1096
        if (count($tmp) > 0) {
1097
            return implode(',', $tmp);
1098
        }
1099
1100
        if (null === $configHandler || !is_object($configHandler)) {
1101
            $configHandler = xoops_getHandler('config');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $configHandler does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $configHandler does not seem to be defined for all execution paths leading up to this point.
Loading history...
1102
        }
1103
        $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
1104
        if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_CONF_METAFOOTER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_CONF_METAFOOTER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1105
            return $xoopsConfigMetaFooter['meta_keywords'];
1106
        }
1107
1108
        return '';
1109
    }
1110
1111
    /**
1112
     * Fonction chargée de gérer l'upload
1113
     *
1114
     * @param int       $indice L'indice du fichier à télécharger
1115
     * @param  string   $dstpath
1116
     * @param  null     $mimeTypes
1117
     * @param  null|int $uploadMaxSize
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $mimeTypes is correct as it would always require null to be passed?
Loading history...
Documentation Bug introduced by
Are you sure the doc-type for parameter $mimeTypes is correct as it would always require null to be passed?
Loading history...
1118
     * @param  null|int $maxWidth
1119
     * @param  null|int $maxHeight
1120
     * @return mixed   True si l'upload s'est bien déroulé sinon le message d'erreur correspondant
1121
     */
1122
    public static function uploadFile(
1123
        $indice,
1124
        $dstpath = XOOPS_UPLOAD_PATH,
1125
        $mimeTypes = null,
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_UPLOAD_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_UPLOAD_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1126
        $uploadMaxSize = null,
1127
        $maxWidth = null,
1128
        $maxHeight = null)
1129
    {
1130
        //        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1131
        global $destname;
1132
        if (\Xmf\Request::hasVar('xoops_upload_file', 'POST')) {
1133
            require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1134
            $fldname = '';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1135
            $fldname = $_FILES[$_POST['xoops_upload_file'][$indice]];
0 ignored issues
show
Unused Code introduced by
The assignment to $fldname is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $fldname is dead and can be removed.
Loading history...
1136
            $fldname = get_magic_quotes_gpc() ? stripslashes($fldname['name']) : $fldname['name'];
1137
            if (xoops_trim('' !== $fldname)) {
1138
                $destname = static::createUploadName($dstpath, $fldname, true);
0 ignored issues
show
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1138
                /** @scrutinizer ignore-call */ 
1139
                $destname = static::createUploadName($dstpath, $fldname, true);
Loading history...
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1138
                /** @scrutinizer ignore-call */ 
1139
                $destname = static::createUploadName($dstpath, $fldname, true);
Loading history...
1139
                if (null === $mimeTypes) {
1140
                    $permittedtypes = explode("\n", str_replace("\r", '', static::getModuleOption('mimetypes')));
1141
                    array_walk($permittedtypes, 'trim');
1142
                } else {
1143
                    $permittedtypes = $mimeTypes;
1144
                }
1145
                $uploadSize = $uploadMaxSize;
1146
                if (null === $uploadMaxSize) {
1147
                    $uploadSize = static::getModuleOption('maxuploadsize');
1148
                }
1149
                $uploader = new \XoopsMediaUploader($dstpath, $permittedtypes, $uploadSize, $maxWidth, $maxHeight);
1150
                //$uploader->allowUnknownTypes = true;
0 ignored issues
show
Bug introduced by
The type XoopsMediaUploader was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Bug introduced by
The type XoopsMediaUploader was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1151
                $uploader->setTargetFileName($destname);
1152
                if ($uploader->fetchMedia($_POST['xoops_upload_file'][$indice])) {
1153
                    if ($uploader->upload()) {
1154
                        return true;
1155
                    }
1156
1157
                    return _ERRORS . ' ' . htmlentities($uploader->getErrors(), ENT_QUOTES | ENT_HTML5);
1158
                }
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\_ERRORS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant XoopsModules\Oledrion\_ERRORS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1159
1160
                return htmlentities($uploader->getErrors(), ENT_QUOTES | ENT_HTML5);
1161
            }
1162
1163
            return false;
1164
        }
1165
1166
        return false;
1167
    }
1168
1169
    /**
1170
     * Resize a Picture to some given dimensions (using the wideImage library)
1171
     *
1172
     * @param  string $src_path      Picture's source
1173
     * @param  string $dst_path      Picture's destination
1174
     * @param int     $param_width   Maximum picture's width
1175
     * @param int     $param_height  Maximum picture's height
1176
     * @param  bool   $keep_original Do we have to keep the original picture ?
1177
     * @param  string $fit           Resize mode (see the wideImage library for more information)
1178
     * @return bool
1179
     */
1180
    public static function resizePicture(
1181
        $src_path,
1182
        $dst_path,
1183
        $param_width,
1184
        $param_height,
1185
        $keep_original = false,
1186
        $fit = 'inside')
1187
    {
1188
        //        require_once OLEDRION_PATH . 'class/wideimage/WideImage.inc.php';
1189
        $resize = true;
1190
        if (OLEDRION_DONT_RESIZE_IF_SMALLER) {
1191
            if (false === @getimagesize($src_path)) {
1192
                $message = 'The picture ' . $src_path . ' could not be found and resized.';
1193
//                throw new \RuntimeException($message);
1194
                self::redirect($message);
1195
1196
                return false;
1197
            } else {
1198
                $pictureDimensions = getimagesize($src_path);
1199
                if (is_array($pictureDimensions)) {
1200
                    $width  = $pictureDimensions[0];
1201
                    $height = $pictureDimensions[1];
1202
                    if ($width < $param_width && $height < $param_height) {
1203
                        $resize = false;
1204
                    }
1205
                }
1206
            }
1207
        }
1208
1209
        $img = WideImage::load($src_path);
1210
        if ($resize) {
1211
            $result = $img->resize($param_width, $param_height, $fit);
1212
            $result->saveToFile($dst_path);
1213
        } else {
1214
            if (false === @copy($src_path, $dst_path)) {
1215
                throw new \RuntimeException('The file '.$src_path.' could not be copied.');
1216
            }
1217
        }
1218
1219
        if (!$keep_original) {
1220
            if (false === @unlink($src_path)) {
1221
                throw new \RuntimeException('The file '.$src_path.' could not be deleted.');
1222
            }
1223
        }
1224
1225
        return true;
1226
    }
1227
1228
    /**
1229
     * Triggering a Xoops alert after an event
1230
     *
1231
     * @param int   $category The category ID of the event
1232
     * @param int   $itemId   The ID of the element (too general to be precisely described)
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1232
     * @param int   $itemId   Th/** @scrutinizer ignore-call */ e ID of the element (too general to be precisely described)
Loading history...
1233
     * @param mixed $event    The event that is triggered
1234
     * @param mixed $tags     Variables to pass to the template
1235
     */
1236
    public static function notify($category, $itemId, $event, $tags)
1237
    {
1238
        /** @var \XoopsNotificationHandler $notificationHandler */
1239
        $notificationHandler  = xoops_getHandler('notification');
1240
        $tags['X_MODULE_URL'] = OLEDRION_URL;
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1240
        $tags['X_MODULE_URL'] = /** @scrutinizer ignore-call */ OLEDRION_URL;
Loading history...
1241
        $notificationHandler->triggerEvent($category, $itemId, $event, $tags);
1242
    }
1243
1244
    /**
1245
     * Ajoute des jours à une date et retourne la nouvelle date au format Date de Mysql
1246
     *
1247
     * @param  int $duration
1248
     * @param int  $startingDate Date de départ (timestamp)
1249
     * @return bool|string
1250
     * @internal param int $durations Durée en jours
1251
     */
1252
    public static function addDaysToDate($duration = 1, $startingDate = 0)
1253
    {
1254
        if (0 == $startingDate) {
1255
            $startingDate = time();
1256
        }
1257
        $endingDate = $startingDate + ($duration * 86400);
1258
1259
        return date('Y-m-d', $endingDate);
1260
    }
1261
1262
    /**
1263
     * Returns a breadcrumb based on the parameters passed and starting (automatically) from the root of the module     *
1264
     * @param array  $path  The complete path (except root) of the breadcrumb as key = url value = title
1265
     * @param string $raquo The default separator to use
1266
     * @return string the breadcrumb
0 ignored issues
show
introduced by
The condition is_array($path) is always true.
Loading history...
1267
     */
1268
    public static function breadcrumb($path, $raquo = ' &raquo; ')
1269
    {
1270
        $breadcrumb        = '';
1271
        $workingBreadcrumb = [];
1272
        if (is_array($path)) {
1273
            $moduleName          = static::getModuleName();
0 ignored issues
show
introduced by
The condition is_array($path) is always true.
Loading history...
1274
            $workingBreadcrumb[] = "<a href='" . OLEDRION_URL . "' title='" . static::makeHrefTitle($moduleName) . "'>" . $moduleName . '</a>';
1275
            foreach ($path as $url => $title) {
1276
                $workingBreadcrumb[] = "<a href='" . $url . "'>" . $title . '</a>';
1277
            }
1278
            $cnt = count($workingBreadcrumb);
1279
            foreach ($workingBreadcrumb as $i => $iValue) {
1280
                if ($i == $cnt - 1) {
1281
                    $workingBreadcrumb[$i] = strip_tags($workingBreadcrumb[$i]);
1282
                }
1283
            }
1284
            $breadcrumb = implode($raquo, $workingBreadcrumb);
1285
        }
1286
1287
        return $breadcrumb;
1288
    }
1289
1290
    /**
1291
     * @param $string
1292
     * @return string
1293
     */
1294
    public static function close_tags($string)
1295
    {
1296
        // match opened tags
1297
        if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
1298
            $start_tags = $start_tags[1];
1299
1300
            // match closed tags
1301
            if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
1302
                $complete_tags = [];
1303
                $end_tags      = $end_tags[1];
1304
1305
                foreach ($start_tags as $key => $val) {
1306
                    $posb = array_search($val, $end_tags, true);
1307
                    if (is_int($posb)) {
1308
                        unset($end_tags[$posb]);
1309
                    } else {
1310
                        $complete_tags[] = $val;
1311
                    }
1312
                }
1313
            } else {
1314
                $complete_tags = $start_tags;
1315
            }
1316
1317
            $complete_tags = array_reverse($complete_tags);
1318
            for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
1319
                $string .= '</' . $complete_tags[$i] . '>';
1320
            }
1321
        }
1322
1323
        return $string;
1324
    }
1325
1326
    /**
1327
     * @param               $string
1328
     * @param  int          $length
1329
     * @param  string       $etc
1330
     * @param  bool         $break_words
1331
     * @return mixed|string
1332
     */
1333
    public static function truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
1334
    {
1335
        if (0 == $length) {
1336
            return '';
1337
        }
1338
1339
        if (mb_strlen($string) > $length) {
1340
            $length -= mb_strlen($etc);
1341
            if (!$break_words) {
1342
                $string = preg_replace('/\s+?(\S+)?$/', '', mb_substr($string, 0, $length + 1));
1343
                $string = preg_replace('/<[^>]*$/', '', $string);
1344
                $string = static::close_tags($string);
1345
            }
1346
1347
            return $string . $etc;
1348
        }
1349
1350
        return $string;
1351
    }
1352
1353
    /**
1354
     * Create an infotip
1355
     * @param $text
1356
     * @return string
1357
     */
1358
    public static function makeInfotips($text)
0 ignored issues
show
Bug introduced by
The function xoops_substr was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1358
    public static function makeInfotips($tex/** @scrutinizer ignore-call */ t)
Loading history...
1359
    {
1360
        $ret      = '';
1361
        $infotips = static::getModuleOption('infotips');
1362
        if ($infotips > 0) {
1363
            $myts = \MyTextSanitizer::getInstance();
1364
            $ret  = $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
1365
        }
0 ignored issues
show
Bug introduced by
The function xoops_substr was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1365
        }/** @scrutinizer ignore-call */ 
Loading history...
1366
1367
        return $ret;
1368
    }
1369
1370
    /**
1371
     * Mise en place de l'appel à la feuille de style du module dans le template
1372
     * @param string $url
1373
     */
1374
    public static function setCSS($url = '')
1375
    {
1376
        global $xoopsTpl, $xoTheme;
1377
        if ('' == $url) {
1378
            $url = OLEDRION_URL . 'assets/css/oledrion.css';
1379
        }
1380
1381
        if (!is_object($xoTheme)) {
1382
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$url\">");
1383
        } else {
1384
            $xoTheme->addStylesheet($url);
1385
        }
1386
    }
1387
1388
    /**
1389
     * Mise en place de l'appel à la feuille de style du module dans le template
1390
     * @param string $language
1391
     */
1392
    public static function setLocalCSS($language = 'english')
1393
    {
1394
        global $xoopsTpl, $xoTheme;
1395
1396
        $localcss = OLEDRION_URL . 'language/' . $language . '/style.css';
1397
1398
        if (!is_object($xoTheme)) {
1399
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$localcss\">");
1400
        } else {
1401
            $xoTheme->addStylesheet($localcss);
1402
        }
1403
    }
1404
1405
    /**
1406
     * Calcul du TTC à partir du HT et de la TVA
1407
     *
1408
     * @param int     $ht     Montant HT
1409
     * @param int     $vat    Taux de TVA
1410
     * @param  bool   $edit   Si faux alors le montant est formaté pour affichage sinon il reste tel quel
1411
     * @param  string $format Format d'affichage du résultat (long ou court)
1412
     * @return mixed   Soit une chaine soit un flottant
1413
     */
1414
    public static function getTTC($ht = 0, $vat = 0, $edit = false, $format = 's')
1415
    {
1416
        $ht               = (int)$ht;
1417
        $vat              = (int)$vat;
1418
        $oledrionCurrency = Oledrion\Currency::getInstance();
1419
        $ttc              = $ht * (1 + ($vat / 100));
1420
        if (!$edit) {
1421
            return $oledrionCurrency->amountForDisplay($ttc, $format);
1422
        }
1423
1424
        return $ttc;
1425
    }
1426
1427
    /**
1428
     * Renvoie le montant de la tva à partir du montant HT
1429
     * @param $ht
1430
     * @param $vat
1431
     * @return float
1432
     */
1433
    public static function getVAT($ht, $vat)
1434
    {
1435
        return (($ht * $vat) / 100);
1436
    }
1437
1438
    /**
1439
     * Retourne le montant TTC
1440
     *
1441
     * @param  float $product_price Le montant du produit
0 ignored issues
show
Unused Code introduced by
The assignment to $vat is dead and can be removed.
Loading history...
1442
     * @param int    $vat_id        Le numéro de TVA
1443
     * @return float Le montant TTC si on a trouvé sa TVA sinon
1444
     */
0 ignored issues
show
Bug introduced by
The type XoopsDatabaseFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1445
    public static function getAmountWithVat($product_price, $vat_id)
1446
    {
1447
        $vat = null;
1448
        static $vats = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $vat is dead and can be removed.
Loading history...
1449
        $vat_rate   = null;
1450
        $vatHandler = new Oledrion\VatHandler(\XoopsDatabaseFactory::getDatabaseConnection());
1451
        if (is_array($vats) && in_array($vat_id, $vats, true)) {
0 ignored issues
show
Bug introduced by
The type XoopsDatabaseFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1452
            $vat_rate = $vats[$vat_id];
1453
        } else {
1454
            //            $handlers = \HandlerManager::getInstance();
1455
            require_once dirname(__DIR__) . '/include/common.php';
1456
            $vat = $vatHandler->get($vat_id);
1457
            if (is_object($vat)) {
1458
                $vat_rate      = $vat->getVar('vat_rate', 'e');
1459
                $vats[$vat_id] = $vat_rate;
1460
            }
1461
        }
1462
1463
        if (null !== $vat_rate) {
1464
            return ((float)$product_price * (float)$vat_rate / 100) + (float)$product_price;
1465
        }
1466
1467
        return $product_price;
1468
    }
1469
1470
    /**
1471
     * @param $datastream
1472
     * @param $url
1473
     * @return string
1474
     */
1475
    public static function postIt($datastream, $url)
1476
    {
1477
        $url     = preg_replace('@^http://@i', '', $url);
1478
        $host    = mb_substr($url, 0, mb_strpos($url, '/'));
1479
        $uri     = mb_strstr($url, '/');
1480
        $reqbody = '';
1481
        foreach ($datastream as $key => $val) {
1482
            if (!empty($reqbody)) {
1483
                $reqbody .= '&';
1484
            }
1485
            $reqbody .= $key . '=' . urlencode($val);
1486
        }
1487
        $contentlength = mb_strlen($reqbody);
1488
        $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";
1489
1490
        return $reqheader;
1491
    }
1492
1493
    /**
1494
     * Retourne le type Mime d'un fichier en utilisant d'abord finfo puis mime_content
1495
     *
1496
     * @param  string $filename Le fichier (avec son chemin d'accès complet) dont on veut connaître le type mime
1497
     * @return string
1498
     */
1499
    public static function getMimeType($filename)
1500
    {
1501
        if (function_exists('finfo_open')) {
1502
            $finfo    = finfo_open();
1503
            $mimetype = finfo_file($finfo, $filename, FILEINFO_MIME_TYPE);
1504
            finfo_close($finfo);
1505
1506
            return $mimetype;
1507
        }
1508
1509
        if (function_exists('mime_content_type')) {
1510
            return mime_content_type($filename);
1511
        }
1512
1513
        return '';
1514
    }
1515
1516
    /**
1517
     * Retourne un criteria compo qui permet de filtrer les produits sur le mois courant
0 ignored issues
show
Bug introduced by
date('n') of type string is incompatible with the type integer expected by parameter $month of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1517
     * Retourne un criteria compo qui permet /** @scrutinizer ignore-type */ de filtrer les produits sur le mois courant
Loading history...
Bug introduced by
date('Y') of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1517
     * Retourne un criteria compo qui permet de filtrer les produit/** @scrutinizer ignore-type */ s sur le mois courant
Loading history...
Bug introduced by
date('j') of type string is incompatible with the type integer expected by parameter $day of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1517
     * Retourne un criteria compo qui permet de filtrer /** @scrutinizer ignore-type */ les produits sur le mois courant
Loading history...
1518
     *
1519
     * @return \CriteriaCompo
0 ignored issues
show
Bug introduced by
The type CriteriaCompo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1520
     */
0 ignored issues
show
Bug introduced by
The type Criteria was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1521
    public static function getThisMonthCriteria()
1522
    {
1523
        $start             = mktime(0, 1, 0, date('n'), date('j'), date('Y'));
1524
        $end               = mktime(0, 0, 0, date('n'), date('t'), date('Y'));
0 ignored issues
show
Bug introduced by
date('Y') of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1524
        $end               = mktime(0, 0, 0, date('n'), date('t'), /** @scrutinizer ignore-type */ date('Y'));
Loading history...
Bug introduced by
date('n') of type string is incompatible with the type integer expected by parameter $month of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1524
        $end               = mktime(0, 0, 0, /** @scrutinizer ignore-type */ date('n'), date('t'), date('Y'));
Loading history...
Bug introduced by
date('j') of type string is incompatible with the type integer expected by parameter $day of mktime(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1524
        $end               = mktime(0, 0, 0, date('n'), /** @scrutinizer ignore-type */ date('t'), date('Y'));
Loading history...
1525
        $criteriaThisMonth = new \CriteriaCompo();
1526
        $criteriaThisMonth->add(new \Criteria('product_submitted', $start, '>='));
0 ignored issues
show
Bug introduced by
The type CriteriaCompo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1527
        $criteriaThisMonth->add(new \Criteria('product_submitted', $end, '<='));
0 ignored issues
show
Bug introduced by
The type Criteria was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1528
1529
        return $criteriaThisMonth;
1530
    }
1531
1532
    /**
1533
     * Retourne une liste d'objets XoopsUsers à partir d'une liste d'identifiants
1534
     *
1535
     * @param  array $xoopsUsersIDs La liste des ID
1536
     * @return array Les objets XoopsUsers
1537
     */
1538
    public static function getUsersFromIds($xoopsUsersIDs)
1539
    {
1540
        $users = [];
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1540
        $users = [];/** @scrutinizer ignore-call */ 
Loading history...
1541
        if (is_array($xoopsUsersIDs) && count($xoopsUsersIDs) > 0) {
1542
            $xoopsUsersIDs = array_unique($xoopsUsersIDs);
1543
            sort($xoopsUsersIDs);
1544
            if (count($xoopsUsersIDs) > 0) {
1545
                /** @var \XoopsUserHandler $userHandler */
1546
                $userHandler = xoops_getHandler('user');
1547
                $criteria      = new \Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1547
                $criteria      /** @scrutinizer ignore-call */ = new \Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
Loading history...
1548
                $criteria->setSort('uid');
1549
                $users = $userHandler->getObjects($criteria, true);
1550
            }
1551
        }
1552
1553
        return $users;
1554
    }
1555
1556
    /**
1557
     * Retourne l'ID de l'utilisateur courant (s'il est connecté)
1558
     * @return int L'uid ou 0
1559
     */
1560
    public static function getCurrentUserID()
1561
    {
1562
        global $xoopsUser;
1563
        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
1564
1565
        return $uid;
1566
    }
1567
1568
    /**
1569
     * Retourne la liste des groupes de l'utilisateur courant (avec cache)
1570
     * @param  int $uid
1571
     * @return array Les ID des groupes auquel l'utilisateur courant appartient
1572
     */
1573
    public function getMemberGroups($uid = 0)
1574
    {
1575
        static $buffer = [];
1576
        if (0 == $uid) {
1577
            $uid = static::getCurrentUserID();
1578
        }
1579
1580
        if (is_array($buffer) && count($buffer) > 0 && isset($buffer[$uid])) {
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1580
        if (is_array($buffer)/** @scrutinizer ignore-call */  && count($buffer) > 0 && isset($buffer[$uid])) {
Loading history...
1581
            return $buffer[$uid];
1582
        }
1583
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_GROUP_ANONYMOUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1584
        if ($uid > 0) {
1585
            /** @var \XoopsMemberHandler $memberHandler */
1586
            $memberHandler = xoops_getHandler('member');
1587
            $buffer[$uid]  = $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1587
            $buffer[$uid]  = /** @scrutinizer ignore-call */ $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
Loading history...
1588
        } else {
1589
            $buffer[$uid] = [XOOPS_GROUP_ANONYMOUS];
1590
        }
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_GROUP_ANONYMOUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1591
1592
        return $buffer[$uid];
1593
    }
1594
1595
    /**
1596
     * Indique si l'utilisateur courant fait partie d'une groupe donné (avec gestion de cache)
1597
     *
1598
     * @param int  $group Groupe recherché
1599
     * @param  int $uid
1600
     * @return bool    vrai si l'utilisateur fait partie du groupe, faux sinon
1601
     */
1602
    public static function isMemberOfGroup($group = 0, $uid = 0)
1603
    {
1604
        static $buffer = [];
1605
        $retval = false;
1606
        if (0 == $uid) {
1607
            $uid = static::getCurrentUserID();
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1607
            $uid = static::get/** @scrutinizer ignore-call */ CurrentUserID();
Loading history...
1608
        }
1609
        if (is_array($buffer) && array_key_exists($group, $buffer)) {
1610
            $retval = $buffer[$group];
1611
        } else {
1612
            /** @var \XoopsMemberHandler $memberHandler */
1613
            $memberHandler  = xoops_getHandler('member');
1614
            $groups         = $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1614
            $groups         = /** @scrutinizer ignore-call */ $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
Loading history...
1615
            $retval         = in_array($group, $groups, true);
1616
            $buffer[$group] = $retval;
1617
        }
1618
1619
        return $retval;
1620
    }
1621
1622
    /**
1623
     * Fonction chargée de vérifier qu'un répertoire existe, qu'on peut écrire dedans et création d'un fichier index.html
1624
     *
1625
     * @param  string $folder Le chemin complet du répertoire à vérifier
1626
     */
1627
    public static function prepareFolder($folder)
1628
    {
1629
        if (!is_dir($folder)) {
1630
            if (!mkdir($folder, 0777) && !is_dir($folder)) {
1631
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $folder));
1632
            }
1633
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
1634
        }
1635
        chmod($folder, 0777);
1636
    }
1637
1638
    /**
1639
     * Duplicate a file in local
1640
     *
1641
     * @param  string $path     The file's path
1642
     * @param  string $filename The filename
1643
     * @return mixed  If the copy succeed, the new filename else false
1644
     * @since 2.1
1645
     */
1646
    public static function duplicateFile($path, $filename)
1647
    {
1648
        $newName = static::createUploadName($path, $filename);
1649
        if (copy($path . '/' . $filename, $path . '/' . $newName)) {
1650
            return $newName;
1651
        }
1652
1653
        return false;
1654
    }
1655
1656
    /**
1657
     * Load a language file
1658
     *
1659
     * @param string $languageFile     The required language file
1660
     * @param string $defaultExtension Default extension to use
0 ignored issues
show
Unused Code introduced by
The assignment to $root is dead and can be removed.
Loading history...
1661
     * @since 2.2.2009.02.13
1662
     */
1663
    public static function loadLanguageFile($languageFile, $defaultExtension = '.php')
1664
    {
1665
        global $xoopsConfig;
1666
        $root = OLEDRION_PATH;
1667
        if (false === mb_strpos($languageFile, $defaultExtension)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $root is dead and can be removed.
Loading history...
1668
            $languageFile .= $defaultExtension;
1669
        }
1670
        /** @var Oledrion\Helper $helper */
1671
        $helper = Oledrion\Helper::getInstance();
1672
        $helper->loadLanguage($languageFile);
1673
    }
1674
1675
    /**
1676
     * Formatage d'un floattant pour la base de données
1677
     *
1678
     * @param mixed $amount
1679
     * @return string le montant formaté
1680
     * @since 2.2.2009.02.25
1681
     */
1682
    public static function formatFloatForDB($amount)
1683
    {
1684
        return number_format($amount, 2, '.', '');
1685
    }
1686
1687
    /**
1688
     * Appelle un fichier Javascript à la manière de Xoops
1689
     *
1690
     * @note, l'url complète ne doit pas être fournie, la méthode se charge d'ajouter
1691
     * le chemin vers le répertoire js en fonction de la requête, c'est à dire que si
1692
     * on appelle un fichier de langue, la méthode ajoute l'url vers le répertoire de
1693
     * langue, dans le cas contraire on ajoute l'url vers le répertoire JS du module.
1694
     *
1695
     * @param string $javascriptFile
1696
     * @param bool   $inLanguageFolder
1697
     * @param bool   $oldWay
0 ignored issues
show
Unused Code introduced by
The assignment to $fileToCall is dead and can be removed.
Loading history...
1698
     * @since 2.3.2009.03.14
1699
     */
1700
    public static function callJavascriptFile($javascriptFile, $inLanguageFolder = false, $oldWay = false)
1701
    {
1702
        global $xoopsConfig, $xoTheme;
1703
        $fileToCall = $javascriptFile;
1704
        if ($inLanguageFolder) {
0 ignored issues
show
Unused Code introduced by
The assignment to $fileToCall is dead and can be removed.
Loading history...
1705
            $root    = OLEDRION_PATH;
1706
            $rootUrl = OLEDRION_URL;
1707
            if (file_exists($root . 'language/' . $xoopsConfig['language'] . '/' . $javascriptFile)) {
1708
                $fileToCall = $rootUrl . 'language/' . $xoopsConfig['language'] . '/' . $javascriptFile;
1709
            } else {
1710
                // Fallback
1711
                $fileToCall = $rootUrl . 'language/english/' . $javascriptFile;
1712
            }
1713
        } else {
1714
            $fileToCall = OLEDRION_JS_URL . $javascriptFile;
1715
        }
1716
1717
        $xoTheme->addScript('browse.php?Frameworks/jquery/jquery.js');
1718
        $xoTheme->addScript($fileToCall);
1719
    }
1720
1721
    /**
1722
     * Create the <option> of an html select
1723
     *
1724
     * @param  array $array   Array of index and labels
1725
     * @param  mixed $default the default value
1726
     * @param  bool  $withNull
1727
     * @return string
1728
     * @since 2.3.2009.03.13
1729
     */
1730
    public static function htmlSelectOptions($array, $default = 0, $withNull = true)
1731
    {
1732
        $ret      = [];
1733
        $selected = '';
1734
        if ($withNull) {
1735
            if (0 === $default) {
1736
                $selected = " selected = 'selected'";
1737
            }
1738
            $ret[] = '<option value=0' . $selected . '>---</option>';
1739
        }
1740
1741
        foreach ($array as $index => $label) {
1742
            $selected = '';
1743
            if ($index == $default) {
1744
                $selected = " selected = 'selected'";
1745
            }
1746
            $ret[] = '<option value="' . $index . '"' . $selected . '>' . $label . '</option>';
1747
        }
1748
1749
        return implode("\n", $ret);
1750
    }
1751
1752
    /**
1753
     * Creates an html select
1754
     *
1755
     * @param  string $selectName Selector's name
1756
     * @param  array  $array      Options
1757
     * @param  mixed  $default    Default's value
1758
     * @param  bool   $withNull   Do we include a null option ?
1759
     * @return string
1760
     * @since 2.3.2009.03.13
1761
     */
1762
    public static function htmlSelect($selectName, $array, $default, $withNull = true)
1763
    {
1764
        $ret = '';
1765
        $ret .= "<select name='" . $selectName . "' id='" . $selectName . "'>\n";
1766
        $ret .= static::htmlSelectOptions($array, $default, $withNull);
1767
        $ret .= "</select>\n";
1768
1769
        return $ret;
1770
    }
1771
1772
    /**
1773
     * Extrait l'id d'une chaine formatée sous la forme xxxx-99 (duquel on récupère 99)
1774
     *
1775
     * @note: utilisé par les attributs produits
1776
     * @param  string $string    La chaine de travail
1777
     * @param  string $separator Le séparateur
1778
     * @return string
1779
     */
1780
    public static function getId($string, $separator = '_')
1781
    {
1782
        $pos = mb_strrpos($string, $separator);
1783
        if (false === $pos) {
1784
            return $string;
1785
        }
1786
1787
        return (int)mb_substr($string, $pos + 1);
1788
    }
1789
1790
    /**
1791
     * Fonction "inverse" de getId (depuis xxxx-99 on récupère xxxx)
1792
     *
1793
     * @note: utilisé par les attributs produits
1794
     * @param  string $string    La chaine de travail
1795
     * @param  string $separator Le séparateur
1796
     * @return string
1797
     */
1798
    public static function getName($string, $separator = '_')
1799
    {
1800
        $pos = mb_strrpos($string, $separator);
1801
        if (false === $pos) {
1802
            return $string;
1803
        }
1804
1805
        return mb_substr($string, 0, $pos);
1806
    }
1807
1808
    /**
1809
     * Renvoie un montant nul si le montant est négatif
1810
     *
1811
     * @param  float $amount
1812
     */
1813
    public static function doNotAcceptNegativeAmounts(&$amount)
1814
    {
1815
        if ($amount < 0) {
1816
            $amount = 0.0;
1817
        }
1818
    }
1819
1820
    /**
1821
     * Returns a string from the request
1822
     *
1823
     * @param  string $valueName    Name of the parameter you want to get
1824
     * @param  mixed  $defaultValue Default value to return if the parameter is not set in the request
1825
     * @return mixed
1826
     */
1827
    public static function getFromRequest($valueName, $defaultValue = '')
1828
    {
1829
        return isset($_REQUEST[$valueName]) ? $_REQUEST[$valueName] : $defaultValue;
1830
    }
1831
1832
    /**
1833
     * Verify that a mysql table exists
1834
     *
1835
     * @author        Instant Zero (http://xoops.instant-zero.com)
1836
     * @copyright (c) Instant Zero
1837
     * @param $tablename
1838
     * @return bool
1839
     */
1840
    public static function tableExists($tablename)
1841
    {
1842
        global $xoopsDB;
1843
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
1844
1845
        return ($xoopsDB->getRowsNum($result) > 0);
1846
    }
1847
1848
    /**
1849
     * Verify that a field exists inside a mysql table
1850
     *
1851
     * @author        Instant Zero (http://xoops.instant-zero.com)
1852
     * @copyright (c) Instant Zero
1853
     * @param $fieldname
1854
     * @param $table
1855
     * @return bool
1856
     */
1857
    public static function fieldExists($fieldname, $table)
1858
    {
1859
        global $xoopsDB;
1860
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1861
1862
        return ($xoopsDB->getRowsNum($result) > 0);
1863
    }
1864
1865
    /**
1866
     * Retourne la définition d'un champ
1867
     *
1868
     * @param  string $fieldname
1869
     * @param  string $table
1870
     * @return array|string
1871
     */
1872
    public static function getFieldDefinition($fieldname, $table)
1873
    {
1874
        global $xoopsDB;
1875
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1876
        if ($result) {
1877
            return $xoopsDB->fetchArray($result);
1878
        }
1879
1880
        return '';
1881
    }
1882
1883
    /**
1884
     * Add a field to a mysql table
1885
     *
1886
     * @author        Instant Zero (http://xoops.instant-zero.com)
1887
     * @copyright (c) Instant Zero
1888
     * @param $field
1889
     * @param $table
1890
     * @return bool|\mysqli_result
1891
     */
1892
    public static function addField($field, $table)
1893
    {
1894
        global $xoopsDB;
1895
        $result = $xoopsDB->queryF("ALTER TABLE $table ADD $field;");
1896
1897
        return $result;
1898
    }
1899
1900
    /**
1901
     * @param $info
1902
     * @return string
1903
     */
1904
    public static function packingHtmlSelect($info)
1905
    {
1906
        $ret = '';
1907
        $ret .= '<div class="oledrion_htmlform">';
1908
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['packing_image_url'] . '" alt="' . $info['packing_title'] . '">';
1909
        $ret .= '<h3>' . $info['packing_title'] . '</h3>';
1910
        if ($info['packing_price'] > 0) {
1911
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['packing_price_fordisplay'] . '</p>';
1912
        } else {
1913
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1914
        }
1915
        $ret .= '<p>' . $info['packing_description'] . '</p>';
1916
        $ret .= '</div>';
1917
1918
        return $ret;
1919
    }
1920
1921
    /**
1922
     * @param $info
1923
     * @return string
1924
     */
1925
    public static function deliveryHtmlSelect($info)
1926
    {
1927
        $ret = '';
1928
        $ret .= '<div class="oledrion_htmlform">';
1929
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['delivery_image_url'] . '" alt="' . $info['delivery_title'] . '">';
1930
        $ret .= '<h3>' . $info['delivery_title'] . '</h3>';
1931
        if ($info['delivery_price'] > 0) {
1932
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['delivery_price_fordisplay'] . '</p>';
1933
        } else {
1934
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1935
        }
1936
        $ret .= '<p><span class="bold">' . _OLEDRION_DELIVERY_TIME . '</span> : ' . $info['delivery_time'] . _OLEDRION_DELIVERY_DAY . '</p>';
1937
        $ret .= '<p>' . $info['delivery_description'] . '</p>';
1938
        $ret .= '</div>';
1939
1940
        return $ret;
1941
    }
1942
1943
    /**
1944
     * @param $info
1945
     * @return string
1946
     */
1947
    public static function paymentHtmlSelect($info)
1948
    {
1949
        $ret = '';
1950
        $ret .= '<div class="oledrion_htmlform">';
1951
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['payment_image_url'] . '" alt="' . $info['payment_title'] . '">';
1952
        $ret .= '<h3>' . $info['payment_title'] . '</h3>';
1953
        $ret .= '<p>' . $info['payment_description'] . '</p>';
1954
        $ret .= '</div>';
1955
1956
        return $ret;
1957
    }
1958
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1959
    /**
1960
     * @return array
0 ignored issues
show
Bug introduced by
The type XoopsLists was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1961
     */
1962
    public static function getCountriesList()
1963
    {
1964
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
1965
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1966
        return \XoopsLists::getCountryList();
1967
    }
0 ignored issues
show
Bug introduced by
The type XoopsLists was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1968
1969
    /**
1970
     * Retourne la liste des groupes de l'utlisateur courant (avec cache)
1971
     * @return array Les ID des groupes auquel l'utilisateur courant appartient
1972
     */
1973
    public static function getCurrentMemberGroups()
1974
    {
1975
        static $buffer = [];
1976
1977
        if (is_array($buffer) && count($buffer) > 0) {
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1977
        if (is_array($buffer) && /** @scrutinizer ignore-call */ count($buffer) > 0) {
Loading history...
1978
            return $buffer;
1979
        } else {
1980
            $uid = self::getCurrentUserID();
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_GROUP_ANONYMOUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1981
            if ($uid > 0) {
1982
                /** @var \XoopsMemberHandler $memberHandler */
1983
                $memberHandler = xoops_getHandler('member');
1984
                $buffer        = $memberHandler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1984
                $buffer        = /** @scrutinizer ignore-call */ $memberHandler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
Loading history...
1985
            } else {
1986
                $buffer = [XOOPS_GROUP_ANONYMOUS];
1987
            }
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_GROUP_ANONYMOUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1988
        }
1989
1990
        return $buffer;
1991
    }
1992
}
1993