Completed
Push — master ( 3d1c18...5b4e4c )
by Michael
03:05
created
class/references_utils.php 2 patches
Indentation   +1529 added lines, -1529 removed lines patch added patch discarded remove patch
@@ -36,1533 +36,1533 @@
 block discarded – undo
36 36
 
37 37
 class references_utils
38 38
 {
39
-    // Pour la portabilité de module à module
40
-    const MODULE_NAME    = 'references';
41
-    const MODULE_DIRNAME = REFERENCES_DIRNAME;
42
-    const MODULE_PATH    = REFERENCES_PATH;
43
-    const MODULE_URL     = REFERENCES_URL;
44
-    const MODULE_JS_URL  = REFERENCES_JS_URL;
45
-
46
-    /**
47
-     * Access the only instance of this class
48
-     *
49
-     * @return object
50
-     *
51
-     * @static
52
-     * @staticvar   object
53
-     */
54
-    public static function getInstance()
55
-    {
56
-        static $instance;
57
-        if (null === $instance) {
58
-            $instance = new static();
59
-        }
60
-
61
-        return $instance;
62
-    }
63
-
64
-    /**
65
-     * Returns a module's option (with cache)
66
-     *
67
-     * @param  string  $option    module option's name
68
-     * @param  boolean $withCache Do we have to use some cache ?
69
-     * @return mixed   option's value
70
-     */
71
-    public static function getModuleOption($option, $withCache = true)
72
-    {
73
-        global $xoopsModuleConfig, $xoopsModule;
74
-        $repmodule = self::MODULE_NAME;
75
-        static $options = array();
76
-        if (is_array($options) && array_key_exists($option, $options) && $withCache) {
77
-            return $options[$option];
78
-        }
79
-
80
-        $retval = false;
81
-        if (isset($xoopsModuleConfig) && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
82
-            if (isset($xoopsModuleConfig[$option])) {
83
-                $retval = $xoopsModuleConfig[$option];
84
-            }
85
-        } else {
86
-            $module_handler = xoops_getHandler('module');
87
-            $module         = $module_handler->getByDirname($repmodule);
88
-            $config_handler = xoops_getHandler('config');
89
-            if ($module) {
90
-                $moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
91
-                if (isset($moduleConfig[$option])) {
92
-                    $retval = $moduleConfig[$option];
93
-                }
94
-            }
95
-        }
96
-        $options[$option] = $retval;
97
-
98
-        return $retval;
99
-    }
100
-
101
-    /**
102
-     * Is Xoops 2.3.x ?
103
-     *
104
-     * @return boolean need to say it ?
105
-     */
106
-    public static function isX23()
107
-    {
108
-        $x23 = false;
109
-        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
110
-        if ((int)substr($xv, 2, 1) >= 3) {
111
-            $x23 = true;
112
-        }
113
-
114
-        return $x23;
115
-    }
116
-
117
-    /**
118
-     * Retreive an editor according to the module's option "form_options"
119
-     *
120
-     * @param  string $caption Caption to give to the editor
121
-     * @param  string $name    Editor's name
122
-     * @param  string $value   Editor's value
123
-     * @param  string $width   Editor's width
124
-     * @param  string $height  Editor's height
125
-     * @param string  $supplemental
126
-     * @return object The editor to use
127
-     */
128
-    public static function getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
129
-    {
130
-        $editor                   = false;
131
-        $editor_configs           = array();
132
-        $editor_configs['name']   = $name;
133
-        $editor_configs['value']  = $value;
134
-        $editor_configs['rows']   = 35;
135
-        $editor_configs['cols']   = 60;
136
-        $editor_configs['width']  = '100%';
137
-        $editor_configs['height'] = '400px';
138
-
139
-        $editor_option = strtolower(self::getModuleOption('form_options'));
140
-
141
-        if (self::isX23()) {
142
-            $editor = new XoopsFormEditor($caption, $editor_option, $editor_configs);
143
-
144
-            return $editor;
145
-        }
146
-
147
-        // Only for Xoops 2.0.x
148
-        switch ($editor_option) {
149
-            case 'fckeditor':
150
-                if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
151
-                    require_once(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php');
152
-                    $editor = new XoopsFormFckeditor($caption, $name, $value);
153
-                }
154
-                break;
155
-
156
-            case 'htmlarea':
157
-                if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
158
-                    require_once(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php');
159
-                    $editor = new XoopsFormHtmlarea($caption, $name, $value);
160
-                }
161
-                break;
162
-
163
-            case 'dhtmltextarea':
164
-                $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
165
-                break;
166
-
167
-            case 'textarea':
168
-                $editor = new XoopsFormTextArea($caption, $name, $value);
169
-                break;
170
-
171
-            case 'tinyeditor':
172
-            case 'tinymce':
173
-                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
174
-                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
175
-                    $editor = new XoopsFormTinyeditorTextArea(array('caption' => $caption, 'name' => $name, 'value' => $value, 'width' => '100%', 'height' => '400px'));
176
-                }
177
-                break;
178
-
179
-            case 'koivi':
180
-                if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
181
-                    require_once(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php');
182
-                    $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
183
-                }
184
-                break;
185
-        }
186
-        if (!is_object($editor)) {
187
-            trigger_error('Error, impossible to get the requested text editor', E_USER_ERROR);
188
-        }
189
-
190
-        return $editor;
191
-    }
192
-
193
-    /**
194
-     * Create (in a link) a javascript confirmation's box
195
-     *
196
-     * @param  string  $message Message to display
197
-     * @param  boolean $form    Is this a confirmation for a form ?
198
-     * @return string  the javascript code to insert in the link (or in the form)
199
-     */
200
-    public static function javascriptLinkConfirm($message, $form = false)
201
-    {
202
-        if (!$form) {
203
-            return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
204
-        } else {
205
-            return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
206
-        }
207
-    }
208
-
209
-    /**
210
-     * Get current user IP
211
-     *
212
-     * @return string IP address (format Ipv4)
213
-     */
214
-    public static function IP()
215
-    {
216
-        $proxy_ip = '';
217
-        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
218
-            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
219
-        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
220
-            $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
221
-        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
222
-            $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
223
-        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
224
-            $proxy_ip = $_SERVER['HTTP_FORWARDED'];
225
-        } elseif (!empty($_SERVER['HTTP_VIA'])) {
226
-            $proxy_ip = $_SERVER['HTTP_VIA'];
227
-        } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
228
-            $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
229
-        } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
230
-            $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
231
-        }
232
-        $regs = array();
233
-        if (!empty($proxy_ip) && $is_ip = ereg('^([0-9]{1,3}\.){3,3}[0-9]{1,3}', $proxy_ip, $regs) && count($regs) > 0) {
234
-            $the_IP = $regs[0];
235
-        } else {
236
-            $the_IP = $_SERVER['REMOTE_ADDR'];
237
-        }
238
-
239
-        return $the_IP;
240
-    }
241
-
242
-    /**
243
-     * Set the page's title, meta description and meta keywords
244
-     * Datas are supposed to be sanitized
245
-     *
246
-     * @param  string $pageTitle       Page's Title
247
-     * @param  string $metaDescription Page's meta description
248
-     * @param  string $metaKeywords    Page's meta keywords
249
-     * @return void
250
-     */
251
-    public static function setMetas($pageTitle = '', $metaDescription = '', $metaKeywords = '')
252
-    {
253
-        global $xoTheme, $xoTheme, $xoopsTpl;
254
-        $xoopsTpl->assign('xoops_pagetitle', $pageTitle);
255
-        if (isset($xoTheme) && is_object($xoTheme)) {
256
-            if (!empty($metaKeywords)) {
257
-                $xoTheme->addMeta('meta', 'keywords', $metaKeywords);
258
-            }
259
-            if (!empty($metaDescription)) {
260
-                $xoTheme->addMeta('meta', 'description', $metaDescription);
261
-            }
262
-        } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) {    // Compatibility for old Xoops versions
263
-            if (!empty($metaKeywords)) {
264
-                $xoopsTpl->assign('xoops_meta_keywords', $metaKeywords);
265
-            }
266
-            if (!empty($metaDescription)) {
267
-                $xoopsTpl->assign('xoops_meta_description', $metaDescription);
268
-            }
269
-        }
270
-    }
271
-
272
-    /**
273
-     * Send an email from a template to a list of recipients
274
-     *
275
-     * @param         $tplName
276
-     * @param  array  $recipients List of recipients
277
-     * @param  string $subject    Email's subject
278
-     * @param  array  $variables  Varirables to give to the template
279
-     * @return bool Result of the send
280
-     * @internal param string $tpl_name Template's name
281
-     */
282
-    public static function sendEmailFromTpl($tplName, $recipients, $subject, $variables)
283
-    {
284
-        global $xoopsConfig;
285
-        require_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
286
-        if (!is_array($recipients)) {
287
-            if (trim($recipients) == '') {
288
-                return false;
289
-            }
290
-        } else {
291
-            if (count($recipients) == 0) {
292
-                return false;
293
-            }
294
-        }
295
-        if (function_exists('xoops_getMailer')) {
296
-            $xoopsMailer = xoops_getMailer();
297
-        } else {
298
-            $xoopsMailer =& getMailer();
299
-        }
300
-
301
-        $xoopsMailer->useMail();
302
-        $xoopsMailer->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/' . $xoopsConfig['language'] . '/mail_template');
303
-        $xoopsMailer->setTemplate($tplName);
304
-        $xoopsMailer->setToEmails($recipients);
305
-        // TODO: Change !
306
-        // $xoopsMailer->setFromEmail('[email protected]');
307
-        //$xoopsMailer->setFromName('MonSite');
308
-        $xoopsMailer->setSubject($subject);
309
-        foreach ($variables as $key => $value) {
310
-            $xoopsMailer->assign($key, $value);
311
-        }
312
-        $res = $xoopsMailer->send();
313
-        unset($xoopsMailer);
314
-        $filename = XOOPS_UPLOAD_PATH . '/logmail_' . self::MODULE_NAME . '.php';
315
-        if (!file_exists($filename)) {
316
-            $fp = @fopen($filename, 'a');
317
-            if ($fp) {
318
-                fwrite($fp, '<?php exit(); ?>');
319
-                fclose($fp);
320
-            }
321
-        }
322
-        $fp = @fopen($filename, 'a');
323
-
324
-        if ($fp) {
325
-            fwrite($fp, str_repeat('-', 120) . "\n");
326
-            fwrite($fp, date('d/m/Y H:i:s') . "\n");
327
-            fwrite($fp, 'Template name : ' . $tplName . "\n");
328
-            fwrite($fp, 'Email subject : ' . $subject . "\n");
329
-            if (is_array($recipients)) {
330
-                fwrite($fp, 'Recipient(s) : ' . implode(',', $recipients) . "\n");
331
-            } else {
332
-                fwrite($fp, 'Recipient(s) : ' . $recipients . "\n");
333
-            }
334
-            fwrite($fp, 'Transmited variables : ' . implode(',', $variables) . "\n");
335
-            fclose($fp);
336
-        }
337
-
338
-        return $res;
339
-    }
340
-
341
-    /**
342
-     * Remove module's cache
343
-     */
344
-    public static function updateCache()
345
-    {
346
-        global $xoopsModule;
347
-        $folder  = $xoopsModule->getVar('dirname');
348
-        $tpllist = array();
349
-        require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
350
-        require_once XOOPS_ROOT_PATH . '/class/template.php';
351
-        $tplfile_handler = xoops_getHandler('tplfile');
352
-        $tpllist         = $tplfile_handler->find(null, null, null, $folder);
353
-        xoops_template_clear_module_cache($xoopsModule->getVar('mid'));            // Clear module's blocks cache
354
-
355
-        foreach ($tpllist as $onetemplate) {    // Remove cache for each page.
356
-            if ($onetemplate->getVar('tpl_type') === 'module') {
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 = array();
359
-                $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
360
-                if (count($files_del) > 0 && is_array($files_del)) {
361
-                    foreach ($files_del as $one_file) {
362
-                        if (is_file($one_file)) {
363
-                            unlink($one_file);
364
-                        }
365
-                    }
366
-                }
367
-            }
368
-        }
369
-    }
370
-
371
-    /**
372
-     * Redirect user with a message
373
-     *
374
-     * @param string $message message to display
375
-     * @param string $url     The place where to go
376
-     * @param        integer  timeout Time to wait before to redirect
377
-     */
378
-    public static function redirect($message = '', $url = 'index.php', $time = 2)
379
-    {
380
-        redirect_header($url, $time, $message);
381
-        exit();
382
-    }
383
-
384
-    /**
385
-     * Internal function used to get the handler of the current module
386
-     *
387
-     * @return object The module
388
-     */
389
-    public static function getModule()
390
-    {
391
-        static $mymodule;
392
-        if (!isset($mymodule)) {
393
-            global $xoopsModule;
394
-            if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == REFERENCES_DIRNAME) {
395
-                $mymodule =& $xoopsModule;
396
-            } else {
397
-                $hModule  = xoops_getHandler('module');
398
-                $mymodule = $hModule->getByDirname(REFERENCES_DIRNAME);
399
-            }
400
-        }
401
-
402
-        return $mymodule;
403
-    }
404
-
405
-    /**
406
-     * Returns the module's name (as defined by the user in the module manager) with cache
407
-     * @return string Module's name
408
-     */
409
-    public static function getModuleName()
410
-    {
411
-        static $moduleName;
412
-        if (!isset($moduleName)) {
413
-            $mymodule   = self::getModule();
414
-            $moduleName = $mymodule->getVar('name');
415
-        }
416
-
417
-        return $moduleName;
418
-    }
419
-
420
-    /**
421
-     * Create a title for the href tags inside html links
422
-     *
423
-     * @param  string $title Text to use
424
-     * @return string Formated text
425
-     */
426
-    public static function makeHrefTitle($title)
427
-    {
428
-        $s = "\"'";
429
-        $r = '  ';
430
-
431
-        return strtr($title, $s, $r);
432
-    }
433
-
434
-    /**
435
-     * Retourne la liste des utilisateurs appartenants � un groupe
436
-     *
437
-     * @param  int $groupId Searched group
438
-     * @return array Array of XoopsUsers
439
-     */
440
-    public static function getUsersFromGroup($groupId)
441
-    {
442
-        $users          = array();
443
-        $member_handler = xoops_getHandler('member');
444
-        $users          = $member_handler->getUsersByGroup($groupId, true);
445
-
446
-        return $users;
447
-    }
448
-
449
-    /**
450
-     * Retourne les ID des utilisateurs faisant partie de plusieurs groupes
451
-     * @param  array $groups Les ID des groupes dont on recherche les ID utilisateurs
452
-     * @return array Les ID utilisateurs
453
-     */
454
-    public static function getUsersIdsFromGroups($groups)
455
-    {
456
-        $usersIds       = array();
457
-        $member_handler = xoops_getHandler('member');
458
-        foreach ($groups as $groupId) {
459
-            $temporaryGroup = array();
460
-            $temporaryGroup = $member_handler->getUsersByGroup($groupId);
461
-            if (count($temporaryGroup) > 0) {
462
-                $usersIds = array_merge($usersIds, $temporaryGroup);
463
-            }
464
-        }
465
-
466
-        return array_unique($usersIds);
467
-    }
468
-
469
-    /**
470
-     * Retourne la liste des emails des utilisateurs membres d'un groupe
471
-     *
472
-     * @param $groupId
473
-     * @return array Emails list
474
-     * @internal param int $group_id Group's number
475
-     */
476
-    public static function getEmailsFromGroup($groupId)
477
-    {
478
-        $ret   = array();
479
-        $users = self::getUsersFromGroup($groupId);
480
-        foreach ($users as $user) {
481
-            $ret[] = $user->getVar('email');
482
-        }
483
-
484
-        return $ret;
485
-    }
486
-
487
-    /**
488
-     * V�rifie que l'utilisateur courant fait partie du groupe des administrateurs
489
-     *
490
-     * @return booleean Admin or not
491
-     */
492
-    public static function isAdmin()
493
-    {
494
-        global $xoopsUser, $xoopsModule;
495
-        if (is_object($xoopsUser)) {
496
-            if (in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups())) {
497
-                return true;
498
-            } elseif (isset($xoopsModule) && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
499
-                return true;
500
-            }
501
-        }
502
-
503
-        return false;
504
-    }
505
-
506
-    /**
507
-     * Returns the current date in the Mysql format
508
-     *
509
-     * @return string Date in the Mysql format
510
-     */
511
-    public static function getCurrentSQLDate()
512
-    {
513
-        return date('Y-m-d');    // 2007-05-02
514
-    }
515
-
516
-    public static function getCurrentSQLDateTime()
517
-    {
518
-        return date('Y-m-d H:i:s');    // 2007-05-02
519
-    }
520
-
521
-    /**
522
-     * Convert a Mysql date to the human's format
523
-     *
524
-     * @param  string $date The date to convert
525
-     * @param string  $format
526
-     * @return string The date in a human form
527
-     */
528
-    public static function SQLDateToHuman($date, $format = 'l')
529
-    {
530
-        if ($date != '0000-00-00' && xoops_trim($date) != '') {
531
-            return formatTimestamp(strtotime($date), $format);
532
-        } else {
533
-            return '';
534
-        }
535
-    }
536
-
537
-    /**
538
-     * Convert a timestamp to a Mysql date
539
-     *
540
-     * @param  integer $timestamp The timestamp to use
541
-     * @return string  The date in the Mysql format
542
-     */
543
-    public static function timestampToMysqlDate($timestamp)
544
-    {
545
-        return date('Y-m-d', (int)$timestamp);
546
-    }
547
-
548
-    /**
549
-     * Conversion d'un dateTime Mysql en date lisible en fran�ais
550
-     * @param $dateTime
551
-     * @return bool|string
552
-     */
553
-    public static function sqlDateTimeToFrench($dateTime)
554
-    {
555
-        return date('d/m/Y H:i:s', strtotime($dateTime));
556
-    }
557
-
558
-    /**
559
-     * Convert a timestamp to a Mysql datetime form
560
-     * @param  integer $timestamp The timestamp to use
561
-     * @return string  The date and time in the Mysql format
562
-     */
563
-    public static function timestampToMysqlDateTime($timestamp)
564
-    {
565
-        return date('Y-m-d H:i:s', $timestamp);
566
-    }
567
-
568
-    /**
569
-     * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
570
-     *
571
-     * @return boolean Yes = we need to add them, false = no
572
-     */
573
-    public static function needsAsterisk()
574
-    {
575
-        if (self::isX23()) {
576
-            return false;
577
-        }
578
-        if (strpos(strtolower(XOOPS_VERSION), 'impresscms') !== false) {
579
-            return false;
580
-        }
581
-        if (strpos(strtolower(XOOPS_VERSION), 'legacy') === false) {
582
-            $xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
583
-            if ((int)substr($xv, 4, 2) >= 17) {
584
-                return false;
585
-            }
586
-        }
587
-
588
-        return true;
589
-    }
590
-
591
-    /**
592
-     * Mark the mandatory fields of a form with a star
593
-     *
594
-     * @param  object $sform The form to modify
595
-     * @return object The modified form
596
-     * @internal param string $caracter The character to use to mark fields
597
-     */
598
-    public static function &formMarkRequiredFields(&$sform)
599
-    {
600
-        if (self::needsAsterisk()) {
601
-            $required = array();
602
-            foreach ($sform->getRequired() as $item) {
603
-                $required[] = $item->_name;
604
-            }
605
-            $elements = array();
606
-            $elements = &$sform->getElements();
607
-            $cnt      = count($elements);
608
-            for ($i = 0; $i < $cnt; ++$i) {
609
-                if (is_object($elements[$i]) && in_array($elements[$i]->_name, $required)) {
610
-                    $elements[$i]->_caption .= ' *';
611
-                }
612
-            }
613
-        }
614
-
615
-        return $sform;
616
-    }
617
-
618
-    /**
619
-     * Create an html heading (from h1 to h6)
620
-     *
621
-     * @param  string  $title The text to use
622
-     * @param  integer $level Level to return
623
-     * @return string  The heading
624
-     */
625
-    public static function htitle($title = '', $level = 1)
626
-    {
627
-        printf('<h%01d>%s</h%01d>', $level, $title, $level);
628
-    }
629
-
630
-    /**
631
-     * Create a unique upload filename
632
-     *
633
-     * @param  string  $folder   The folder where the file will be saved
634
-     * @param  string  $fileName Original filename (coming from the user)
635
-     * @param  boolean $trimName Do we need to create a short unique name ?
636
-     * @return string  The unique filename to use (with its extension)
637
-     */
638
-    public static function createUploadName($folder, $fileName, $trimName = false)
639
-    {
640
-        $workingfolder = $folder;
641
-        if (substr($workingfolder, strlen($workingfolder) - 1, 1) !== '/') {
642
-            $workingfolder .= '/';
643
-        }
644
-        $ext  = basename($fileName);
645
-        $ext  = explode('.', $ext);
646
-        $ext  = '.' . $ext[count($ext) - 1];
647
-        $true = true;
648
-        while ($true) {
649
-            $ipbits = explode('.', $_SERVER['REMOTE_ADDR']);
650
-            list($usec, $sec) = explode(' ', microtime());
651
-            $usec = (integer)($usec * 65536);
652
-            $sec  = ((integer)$sec) & 0xFFFF;
653
-
654
-            if ($trimName) {
655
-                $uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
656
-            } else {
657
-                $uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
658
-            }
659
-            if (!file_exists($workingfolder . $uid . $ext)) {
660
-                $true = false;
661
-            }
662
-        }
663
-
664
-        return $uid . $ext;
665
-    }
666
-
667
-    /**
668
-     * Replace html entities with their ASCII equivalent
669
-     *
670
-     * @param  string $chaine The string undecode
671
-     * @return string The undecoded string
672
-     */
673
-    public static function unhtml($chaine)
674
-    {
675
-        $search = $replace = array();
676
-        $chaine = html_entity_decode($chaine);
677
-
678
-        for ($i = 0; $i <= 255; ++$i) {
679
-            $search[]  = '&#' . $i . ';';
680
-            $replace[] = chr($i);
681
-        }
682
-        $replace[]='...'; $search[]='…';
683
-        $replace[]="'"; $search[]='‘';
684
-        $replace[]="'"; $search[]= '’';
685
-        $replace[]='-'; $search[] = '&bull;';   // $replace[] = '•';
686
-        $replace[]='—'; $search[]='&mdash;';
687
-        $replace[]='-'; $search[]='&ndash;';
688
-        $replace[]='-'; $search[]='&shy;';
689
-        $replace[]='"'; $search[]='&quot;';
690
-        $replace[]='&'; $search[]='&amp;';
691
-        $replace[]='ˆ'; $search[]='&circ;';
692
-        $replace[]='¡'; $search[]='&iexcl;';
693
-        $replace[]='¦'; $search[]='&brvbar;';
694
-        $replace[]='¨'; $search[]='&uml;';
695
-        $replace[]='¯'; $search[]='&macr;';
696
-        $replace[]='´'; $search[]='&acute;';
697
-        $replace[]='¸'; $search[]='&cedil;';
698
-        $replace[]='¿'; $search[]='&iquest;';
699
-        $replace[]='˜'; $search[]='&tilde;';
700
-        $replace[]="'"; $search[]='&lsquo;';    // $replace[]='‘';
701
-        $replace[]="'"; $search[]='&rsquo;';    // $replace[]='’';
702
-        $replace[]='‚'; $search[]='&sbquo;';
703
-        $replace[]="'"; $search[]='&ldquo;';    // $replace[]='“';
704
-        $replace[]="'"; $search[]='&rdquo;';    // $replace[]='”';
705
-        $replace[]='„'; $search[]='&bdquo;';
706
-        $replace[]='‹'; $search[]='&lsaquo;';
707
-        $replace[]='›'; $search[]='&rsaquo;';
708
-        $replace[]='<'; $search[]='&lt;';
709
-        $replace[]='>'; $search[]='&gt;';
710
-        $replace[]='±'; $search[]='&plusmn;';
711
-        $replace[]='«'; $search[]='&laquo;';
712
-        $replace[]='»'; $search[]='&raquo;';
713
-        $replace[]='×'; $search[]='&times;';
714
-        $replace[]='÷'; $search[]='&divide;';
715
-        $replace[]='¢'; $search[]='&cent;';
716
-        $replace[]='£'; $search[]='&pound;';
717
-        $replace[]='¤'; $search[]='&curren;';
718
-        $replace[]='¥'; $search[]='&yen;';
719
-        $replace[]='§'; $search[]='&sect;';
720
-        $replace[]='©'; $search[]='&copy;';
721
-        $replace[]='¬'; $search[]='&not;';
722
-        $replace[]='®'; $search[]='&reg;';
723
-        $replace[]='°'; $search[]='&deg;';
724
-        $replace[]='µ'; $search[]='&micro;';
725
-        $replace[]='¶'; $search[]='&para;';
726
-        $replace[]='·'; $search[]='&middot;';
727
-        $replace[]='†'; $search[]='&dagger;';
728
-        $replace[]='‡'; $search[]='&Dagger;';
729
-        $replace[]='‰'; $search[]='&permil;';
730
-        $replace[]='Euro'; $search[]='&euro;';      // $replace[]='€'
731
-        $replace[]='¼'; $search[]='&frac14;';
732
-        $replace[]='½'; $search[]='&frac12;';
733
-        $replace[]='¾'; $search[]='&frac34;';
734
-        $replace[]='¹'; $search[]='&sup1;';
735
-        $replace[]='²'; $search[]='&sup2;';
736
-        $replace[]='³'; $search[]='&sup3;';
737
-        $replace[]='á'; $search[]='&aacute;';
738
-        $replace[]='Á'; $search[]='&Aacute;';
739
-        $replace[]='â'; $search[]='&acirc;';
740
-        $replace[]='Â'; $search[]='&Acirc;';
741
-        $replace[]='à'; $search[]='&agrave;';
742
-        $replace[]='À'; $search[]='&Agrave;';
743
-        $replace[]='å'; $search[]='&aring;';
744
-        $replace[]='Å'; $search[]='&Aring;';
745
-        $replace[]='ã'; $search[]='&atilde;';
746
-        $replace[]='Ã'; $search[]='&Atilde;';
747
-        $replace[]='ä'; $search[]='&auml;';
748
-        $replace[]='Ä'; $search[]='&Auml;';
749
-        $replace[]='ª'; $search[]='&ordf;';
750
-        $replace[]='æ'; $search[]='&aelig;';
751
-        $replace[]='Æ'; $search[]='&AElig;';
752
-        $replace[]='ç'; $search[]='&ccedil;';
753
-        $replace[]='Ç'; $search[]='&Ccedil;';
754
-        $replace[]='ð'; $search[]='&eth;';
755
-        $replace[]='Ð'; $search[]='&ETH;';
756
-        $replace[]='é'; $search[]='&eacute;';
757
-        $replace[]='É'; $search[]='&Eacute;';
758
-        $replace[]='ê'; $search[]='&ecirc;';
759
-        $replace[]='Ê'; $search[]='&Ecirc;';
760
-        $replace[]='è'; $search[]='&egrave;';
761
-        $replace[]='È'; $search[]='&Egrave;';
762
-        $replace[]='ë'; $search[]='&euml;';
763
-        $replace[]='Ë'; $search[]='&Euml;';
764
-        $replace[]='ƒ'; $search[]='&fnof;';
765
-        $replace[]='í'; $search[]='&iacute;';
766
-        $replace[]='Í'; $search[]='&Iacute;';
767
-        $replace[]='î'; $search[]='&icirc;';
768
-        $replace[]='Î'; $search[]='&Icirc;';
769
-        $replace[]='ì'; $search[]='&igrave;';
770
-        $replace[]='Ì'; $search[]='&Igrave;';
771
-        $replace[]='ï'; $search[]='&iuml;';
772
-        $replace[]='Ï'; $search[]='&Iuml;';
773
-        $replace[]='ñ'; $search[]='&ntilde;';
774
-        $replace[]='Ñ'; $search[]='&Ntilde;';
775
-        $replace[]='ó'; $search[]='&oacute;';
776
-        $replace[]='Ó'; $search[]='&Oacute;';
777
-        $replace[]='ô'; $search[]='&ocirc;';
778
-        $replace[]='Ô'; $search[]='&Ocirc;';
779
-        $replace[]='ò'; $search[]='&ograve;';
780
-        $replace[]='Ò'; $search[]='&Ograve;';
781
-        $replace[]='º'; $search[]='&ordm;';
782
-        $replace[]='ø'; $search[]='&oslash;';
783
-        $replace[]='Ø'; $search[]='&Oslash;';
784
-        $replace[]='õ'; $search[]='&otilde;';
785
-        $replace[]='Õ'; $search[]='&Otilde;';
786
-        $replace[]='ö'; $search[]='&ouml;';
787
-        $replace[]='Ö'; $search[]='&Ouml;';
788
-        $replace[]='œ'; $search[]='&oelig;';
789
-        $replace[]='Œ'; $search[]='&OElig;';
790
-        $replace[]='š'; $search[]='&scaron;';
791
-        $replace[]='Š'; $search[]='&Scaron;';
792
-        $replace[]='ß'; $search[]='&szlig;';
793
-        $replace[]='þ'; $search[]='&thorn;';
794
-        $replace[]='Þ'; $search[]='&THORN;';
795
-        $replace[]='ú'; $search[]='&uacute;';
796
-        $replace[]='Ú'; $search[]='&Uacute;';
797
-        $replace[]='û'; $search[]='&ucirc;';
798
-        $replace[]='Û'; $search[]='&Ucirc;';
799
-        $replace[]='ù'; $search[]='&ugrave;';
800
-        $replace[]='Ù'; $search[]='&Ugrave;';
801
-        $replace[]='ü'; $search[]='&uuml;';
802
-        $replace[]='Ü'; $search[]='&Uuml;';
803
-        $replace[]='ý'; $search[]='&yacute;';
804
-        $replace[]='Ý'; $search[]='&Yacute;';
805
-        $replace[]='ÿ'; $search[]='&yuml;';
806
-        $replace[]='Ÿ'; $search[]='&Yuml;';
807
-        $chaine    = str_replace($search, $replace, $chaine);
808
-
809
-        return $chaine;
810
-    }
811
-
812
-    /**
813
-     * Création d'une titre pour être utilisé par l'url rewriting
814
-     *
815
-     * @param string  $content  Le texte à utiliser pour créer l'url
816
-     * @param integer $urw      La limite basse pour créer les mots
817
-     * @return string Le texte à utiliser pour l'url
818
-     *                          Note, some parts are from Solo's code
819
-     */
820
-    public static function makeSeoUrl($content, $urw = 1)
821
-    {
822
-        $s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛÜŸÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
823
-        $r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
824
-        $content = self::unhtml($content);    // First, remove html entities
825
-        $content = strtr($content, $s, $r);
826
-        $content = strip_tags($content);
827
-        $content = strtolower($content);
828
-        $content = htmlentities($content);    // TODO: Vérifier
829
-        $content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
830
-        $content = html_entity_decode($content);
831
-        $content = eregi_replace('quot', ' ', $content);
832
-        $content = eregi_replace("'", ' ', $content);
833
-        $content = eregi_replace('-', ' ', $content);
834
-        $content = eregi_replace('[[:punct:]]', '', $content);
835
-        // Selon option mais attention au fichier .htaccess !
836
-        // $content = eregi_replace('[[:digit:]]','', $content);
837
-        $content = preg_replace('/[^a-z|A-Z|0-9]/', '-', $content);
838
-
839
-        $words    = explode(' ', $content);
840
-        $keywords = '';
841
-        foreach ($words as $word) {
842
-            if (strlen($word) >= $urw) {
843
-                $keywords .= '-' . trim($word);
844
-            }
845
-        }
846
-        if (!$keywords) {
847
-            $keywords = '-';
848
-        }
849
-        // Supprime les tirets en double
850
-        $keywords = str_replace('---', '-', $keywords);
851
-        $keywords = str_replace('--', '-', $keywords);
852
-        // Supprime un éventuel tiret à la fin de la chaine
853
-        if (substr($keywords, strlen($keywords) - 1, 1) == '-') {
854
-            $keywords = substr($keywords, 0, strlen($keywords) - 1);
855
-        }
856
-
857
-        return $keywords;
858
-    }
859
-
860
-    /**
861
-     * Create the meta keywords based on the content
862
-     *
863
-     * @param  string $content Content from which we have to create metakeywords
864
-     * @return string The list of meta keywords
865
-     */
866
-    public static function createMetaKeywords($content)
867
-    {
868
-        $keywordscount = REFERENCES_METAGEN_MAX_KEYWORDS;
869
-        $keywordsorder = REFERENCES_METAGEN_KEYWORDS_ORDER;
870
-
871
-        $tmp = array();
872
-        // Search for the "Minimum keyword length"
873
-        // TODO: Remplacer references_keywords_limit par une constante
874
-        if (isset($_SESSION['references_keywords_limit'])) {
875
-            $limit = $_SESSION['references_keywords_limit'];
876
-        } else {
877
-            $config_handler                        = xoops_getHandler('config');
878
-            $xoopsConfigSearch                     =& $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
879
-            $limit                                 = $xoopsConfigSearch['keyword_min'];
880
-            $_SESSION['references_keywords_limit'] = $limit;
881
-        }
882
-        $myts            = MyTextSanitizer::getInstance();
883
-        $content         = str_replace('<br>', ' ', $content);
884
-        $content         = $myts->undoHtmlSpecialChars($content);
885
-        $content         = strip_tags($content);
886
-        $content         = strtolower($content);
887
-        $search_pattern  = array('&nbsp;', "\t", "\r\n", "\r", "\n", ',', '.', "'", ';', ':', ')', '(', '"', '?', '!', '{', '}', '[', ']', '<', '>', '/', '+', '-', '_', '\\', '*');
888
-        $replace_pattern = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
889
-        $content         = str_replace($search_pattern, $replace_pattern, $content);
890
-        $keywords        = explode(' ', $content);
891
-        switch ($keywordsorder) {
892
-            case 0:    // Ordre d'apparition dans le texte
893
-                $keywords = array_unique($keywords);
894
-                break;
895
-            case 1:    // Ordre de fréquence des mots
896
-                $keywords = array_count_values($keywords);
897
-                asort($keywords);
898
-                $keywords = array_keys($keywords);
899
-                break;
900
-            case 2:    // Ordre inverse de la fréquence des mots
901
-                $keywords = array_count_values($keywords);
902
-                arsort($keywords);
903
-                $keywords = array_keys($keywords);
904
-                break;
905
-        }
906
-        // Remove black listed words
907
-        if (xoops_trim(self::getModuleOption('metagen_blacklist')) != '') {
908
-            $metagen_blacklist = str_replace("\r", '', self::getModuleOption('metagen_blacklist'));
909
-            $metablack         = explode("\n", $metagen_blacklist);
910
-            array_walk($metablack, 'trim');
911
-            $keywords = array_diff($keywords, $metablack);
912
-        }
913
-
914
-        foreach ($keywords as $keyword) {
915
-            if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
916
-                $tmp[] = $keyword;
917
-            }
918
-        }
919
-        $tmp = array_slice($tmp, 0, $keywordscount);
920
-        if (count($tmp) > 0) {
921
-            return implode(',', $tmp);
922
-        } else {
923
-            if (!isset($config_handler) || !is_object($config_handler)) {
924
-                $config_handler = xoops_getHandler('config');
925
-            }
926
-            $xoopsConfigMetaFooter =& $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
927
-            if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
928
-                return $xoopsConfigMetaFooter['meta_keywords'];
929
-            } else {
930
-                return '';
931
-            }
932
-        }
933
-    }
934
-
935
-    /**
936
-     * Fonction chargée de gérer l'upload
937
-     *
938
-     * @param integer $indice L'indice du fichier à télécharger
939
-     * @param string  $dstpath
940
-     * @param null    $mimeTypes
941
-     * @param null    $uploadMaxSize
942
-     * @param null    $maxWidth
943
-     * @param null    $maxHeight
944
-     * @return mixed True si l'upload s'est bien déroulé sinon le message d'erreur correspondant
945
-     */
946
-    public static function uploadFile($indice, $dstpath = XOOPS_UPLOAD_PATH, $mimeTypes = null, $uploadMaxSize = null, $maxWidth = null, $maxHeight = null)
947
-    {
948
-        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
949
-        global $destname;
950
-        if (isset($_POST['xoops_upload_file'])) {
951
-            require_once XOOPS_ROOT_PATH . '/class/uploader.php';
952
-            $fldname = '';
953
-            $fldname = $_FILES[$_POST['xoops_upload_file'][$indice]];
954
-            $fldname = get_magic_quotes_gpc() ? stripslashes($fldname['name']) : $fldname['name'];
955
-            if (xoops_trim($fldname != '')) {
956
-                $destname = self::createUploadName($dstpath, $fldname, true);
957
-                if ($mimeTypes === null) {
958
-                    $permittedtypes = explode("\n", str_replace("\r", '', self::getModuleOption('mimetypes')));
959
-                    array_walk($permittedtypes, 'trim');
960
-                } else {
961
-                    $permittedtypes = $mimeTypes;
962
-                }
963
-                if ($uploadMaxSize === null) {
964
-                    $uploadSize = self::getModuleOption('maxuploadsize');
965
-                } else {
966
-                    $uploadSize = $uploadMaxSize;
967
-                }
968
-                $uploader = new XoopsMediaUploader($dstpath, $permittedtypes, $uploadSize, $maxWidth, $maxHeight);
969
-                //$uploader->allowUnknownTypes = true;
970
-                $uploader->setTargetFileName($destname);
971
-                if ($uploader->fetchMedia($_POST['xoops_upload_file'][$indice])) {
972
-                    if ($uploader->upload()) {
973
-                        return true;
974
-                    } else {
975
-                        return _ERRORS . ' ' . htmlentities($uploader->getErrors());
976
-                    }
977
-                } else {
978
-                    return htmlentities($uploader->getErrors());
979
-                }
980
-            } else {
981
-                return false;
982
-            }
983
-        } else {
984
-            return false;
985
-        }
986
-    }
987
-
988
-    /**
989
-     * Resize a Picture to some given dimensions (using the wideImage library)
990
-     *
991
-     * @param string  $src_path      Picture's source
992
-     * @param string  $dst_path      Picture's destination
993
-     * @param integer $param_width   Maximum picture's width
994
-     * @param integer $param_height  Maximum picture's height
995
-     * @param boolean $keep_original Do we have to keep the original picture ?
996
-     * @param string  $fit           Resize mode (see the wideImage library for more information)
997
-     * @return bool
998
-     */
999
-    public static function resizePicture($src_path, $dst_path, $param_width, $param_height, $keep_original = false, $fit = 'inside')
1000
-    {
1001
-        //        require_once self::MODULE_PATH . 'class/wideimage/WideImage.php';
1002
-        $img    = WideImage::load($src_path);
1003
-        $result = $img->resize($param_width, $param_height, $fit);
1004
-        $result->saveToFile($dst_path, null);
1005
-        if (!$keep_original) {
1006
-            @unlink($src_path);
1007
-        }
1008
-
1009
-        return true;
1010
-    }
1011
-
1012
-    /**
1013
-     * Déclenchement d'une alerte Xoops suite à un évènement
1014
-     *
1015
-     * @param string       $category La catégorie de l'évènement
1016
-     * @param integer      $itemId   L'ID de l'élément (trop général pour être décris précisément)
1017
-     * @param unknown_type $event    L'évènement qui est déclencé
1018
-     * @param unknown_type $tags     Les variables à passer au template
1019
-     */
1020
-    public static function notify($category, $itemId, $event, $tags)
1021
-    {
1022
-        $notification_handler = xoops_getHandler('notification');
1023
-        $tags['X_MODULE_URL'] = REFERENCES_URL;
1024
-        $notification_handler->triggerEvent($category, $itemId, $event, $tags);
1025
-    }
1026
-
1027
-    /**
1028
-     * Ajoute des jours à une date et retourne la nouvelle date au format Date de Mysql
1029
-     *
1030
-     * @param int     $duration
1031
-     * @param integer $startingDate Date de départ (timestamp)
1032
-     * @return bool|string
1033
-     * @internal param int $durations Durée en jours
1034
-     */
1035
-    public static function addDaysToDate($duration = 1, $startingDate = 0)
1036
-    {
1037
-        if ($startingDate == 0) {
1038
-            $startingDate = time();
1039
-        }
1040
-        $endingDate = $startingDate + ($duration * 86400);
1041
-
1042
-        return date('Y-m-d', $endingDate);
1043
-    }
1044
-
1045
-    /**
1046
-     * Retourne un breadcrumb en fonction des paramètres passés et en partant (d'office) de la racine du module
1047
-     *
1048
-     * @param array  $path  Le chemin complet (excepté la racine) du breadcrumb sous la forme clé=url valeur=titre
1049
-     * @param string $raquo Le séparateur par défaut à utiliser
1050
-     * @return string le breadcrumb
1051
-     */
1052
-    public static function breadcrumb($path, $raquo = ' &raquo; ')
1053
-    {
1054
-        $breadcrumb        = '';
1055
-        $workingBreadcrumb = array();
1056
-        if (is_array($path)) {
1057
-            $moduleName          = self::getModuleName();
1058
-            $workingBreadcrumb[] = "<a href='" . REFERENCES_URL . "' title='" . self::makeHrefTitle($moduleName) . "'>" . $moduleName . '</a>';
1059
-            foreach ($path as $url => $title) {
1060
-                $workingBreadcrumb[] = "<a href='" . $url . "'>" . $title . '</a>';
1061
-            }
1062
-            $cnt = count($workingBreadcrumb);
1063
-            for ($i = 0; $i < $cnt; ++$i) {
1064
-                if ($i == $cnt - 1) {
1065
-                    $workingBreadcrumb[$i] = strip_tags($workingBreadcrumb[$i]);
1066
-                }
1067
-            }
1068
-            $breadcrumb = implode($raquo, $workingBreadcrumb);
1069
-        }
1070
-
1071
-        return $breadcrumb;
1072
-    }
1073
-
1074
-    public static function close_tags($string)
1075
-    {
1076
-        // match opened tags
1077
-        if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
1078
-            $start_tags = $start_tags[1];
1079
-
1080
-            // match closed tags
1081
-            if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
1082
-                $complete_tags = array();
1083
-                $end_tags      = $end_tags[1];
1084
-
1085
-                foreach ($start_tags as $key => $val) {
1086
-                    $posb = array_search($val, $end_tags);
1087
-                    if (is_int($posb)) {
1088
-                        unset($end_tags[$posb]);
1089
-                    } else {
1090
-                        $complete_tags[] = $val;
1091
-                    }
1092
-                }
1093
-            } else {
1094
-                $complete_tags = $start_tags;
1095
-            }
1096
-
1097
-            $complete_tags = array_reverse($complete_tags);
1098
-            for ($i = 0; $i < count($complete_tags); ++$i) {
1099
-                $string .= '</' . $complete_tags[$i] . '>';
1100
-            }
1101
-        }
1102
-
1103
-        return $string;
1104
-    }
1105
-
1106
-    public static function truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
1107
-    {
1108
-        if ($length == 0) {
1109
-            return '';
1110
-        }
1111
-
1112
-        if (strlen($string) > $length) {
1113
-            $length -= strlen($etc);
1114
-            if (!$break_words) {
1115
-                $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
1116
-                $string = preg_replace('/<[^>]*$/', '', $string);
1117
-                $string = self::close_tags($string);
1118
-            }
1119
-
1120
-            return $string . $etc;
1121
-        } else {
1122
-            return $string;
1123
-        }
1124
-    }
1125
-
1126
-    /**
1127
-     * Create an infotip
1128
-     * @param $text
1129
-     * @return string
1130
-     */
1131
-    public static function makeInfotips($text)
1132
-    {
1133
-        $ret      = '';
1134
-        $infotips = self::getModuleOption('infotips');
1135
-        if ($infotips > 0) {
1136
-            $myts = MyTextSanitizer::getInstance();
1137
-            $ret  = $myts->htmlSpecialChars(substr(strip_tags($text), 0, $infotips));
1138
-        }
1139
-
1140
-        return $ret;
1141
-    }
1142
-
1143
-    /**
1144
-     * Retourne le type Mime d'un fichier en utilisant d'abord finfo puis mime_content
1145
-     *
1146
-     * @param string $filename Le fichier (avec son chemin d'accès complet) dont on veut connaître le type mime
1147
-     * @return string
1148
-     */
1149
-    public static function getMimeType($filename)
1150
-    {
1151
-        if (function_exists('finfo_open')) {
1152
-            $pathToMagic = REFERENCES_PATH . 'mime/magic';
1153
-            $finfo       = new finfo(FILEINFO_MIME, $pathToMagic);
1154
-            $mimetype    = $finfo->file($filename);
1155
-            finfo_close($finfo);
1156
-            unset($finfo);
1157
-
1158
-            return $mimetype;
1159
-        } else {
1160
-            if (function_exists('mime_content_type')) {
1161
-                return mime_content_type($filename);
1162
-            } else {
1163
-                return '';
1164
-            }
1165
-        }
1166
-    }
1167
-
1168
-    /**
1169
-     * Retourne une liste d'objets XoopsUsers à partir d'une liste d'identifiants
1170
-     *
1171
-     * @param  array $xoopsUsersIDs La liste des ID
1172
-     * @return array Les objets XoopsUsers
1173
-     */
1174
-    public static function getUsersFromIds($xoopsUsersIDs)
1175
-    {
1176
-        $users = array();
1177
-        if (is_array($xoopsUsersIDs) && count($xoopsUsersIDs) > 0) {
1178
-            $xoopsUsersIDs = array_unique($xoopsUsersIDs);
1179
-            sort($xoopsUsersIDs);
1180
-            if (count($xoopsUsersIDs) > 0) {
1181
-                $member_handler = xoops_getHandler('user');
1182
-                $criteria       = new Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
1183
-                $criteria->setSort('uid');
1184
-                $users = $member_handler->getObjects($criteria, true);
1185
-            }
1186
-        }
1187
-
1188
-        return $users;
1189
-    }
1190
-
1191
-    /**
1192
-     * Retourne l'ID de l'utilisateur courant (s'il est connecté)
1193
-     * @return integer L'uid ou 0
1194
-     */
1195
-    public static function getCurrentUserID()
1196
-    {
1197
-        global $xoopsUser;
1198
-        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
1199
-
1200
-        return $uid;
1201
-    }
1202
-
1203
-    /**
1204
-     * Retourne la liste des groupes de l'utilisateur courant (avec cache)
1205
-     * @param int $uid
1206
-     * @return array Les ID des groupes auquel l'utilisateur courant appartient
1207
-     */
1208
-    public static function getMemberGroups($uid = 0)
1209
-    {
1210
-        static $buffer = array();
1211
-        if ($uid == 0) {
1212
-            $uid = self::getCurrentUserID();
1213
-        }
1214
-
1215
-        if (is_array($buffer) && count($buffer) > 0 && isset($buffer[$uid])) {
1216
-            return $buffer[$uid];
1217
-        } else {
1218
-            if ($uid > 0) {
1219
-                $member_handler = xoops_getHandler('member');
1220
-                $buffer[$uid]   = $member_handler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
1221
-            } else {
1222
-                $buffer[$uid] = array(XOOPS_GROUP_ANONYMOUS);
1223
-            }
1224
-        }
1225
-
1226
-        return $buffer[$uid];
1227
-    }
1228
-
1229
-    /**
1230
-     * Indique si l'utilisateur courant fait partie d'une groupe donné (avec gestion de cache)
1231
-     *
1232
-     * @param integer $group Groupe recherché
1233
-     * @param int     $uid
1234
-     * @return bool vrai si l'utilisateur fait partie du groupe, faux sinon
1235
-     */
1236
-    public static function isMemberOfGroup($group = 0, $uid = 0)
1237
-    {
1238
-        static $buffer = array();
1239
-        $retval = false;
1240
-        if ($uid == 0) {
1241
-            $uid = self::getCurrentUserID();
1242
-        }
1243
-        if (is_array($buffer) && array_key_exists($group, $buffer)) {
1244
-            $retval = $buffer[$group];
1245
-        } else {
1246
-            $member_handler = xoops_getHandler('member');
1247
-            $groups         = $member_handler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
1248
-            $retval         = in_array($group, $groups);
1249
-            $buffer[$group] = $retval;
1250
-        }
1251
-
1252
-        return $retval;
1253
-    }
1254
-
1255
-    /**
1256
-     * Indique si un utilisateur fait partie de plusieurs groupes
1257
-     * La fonction renvoie vrai dès qu'on trouve que le membre fait partir d'un des groupes
1258
-     * @param array    $groups La liste des groupes à vérifier
1259
-     * @param  integer $uid    L'ID de l'utilisateur
1260
-     * @return boolean
1261
-     */
1262
-    public static function isMemberOfGroups($groups, $uid = 0)
1263
-    {
1264
-        if (count($groups) == 0) {
1265
-            return false;
1266
-        }
1267
-        if ($uid == 0) {
1268
-            $uid = self::getCurrentUserID();
1269
-        }
1270
-        foreach ($groups as $groupId) {
1271
-            if (self::isMemberOfGroup($groupId, $uid)) {
1272
-                return true;
1273
-            }
1274
-        }
1275
-
1276
-        return false;
1277
-    }
1278
-
1279
-    /**
1280
-     * Retourne le nombre total de groupes (y compris les anonymes)
1281
-     */
1282
-    public static function getGroupsCount()
1283
-    {
1284
-        static $cache = -1;
1285
-        if ($cache == -1) {
1286
-            global $xoopsDB;
1287
-            $sql    = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix('groups');
1288
-            $result = $xoopsDB->query($sql);
1289
-            if (!$result) {
1290
-                return false;
1291
-            }
1292
-            list($cache) = $xoopsDB->fetchRow($result);
1293
-        }
1294
-
1295
-        return $cache;
1296
-    }
1297
-
1298
-    /**
1299
-     * Fonction chargée de vérifier qu'un répertoire existe, qu'on peut écrire dedans et création d'un fichier index.html
1300
-     *
1301
-     * @param string $folder Le chemin complet du répertoire à vérifier
1302
-     * @return void
1303
-     */
1304
-    public static function prepareFolder($folder)
1305
-    {
1306
-        if (!is_dir($folder)) {
1307
-            mkdir($folder, 0777);
1308
-            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
1309
-        } else {
1310
-            if (!is_writable($folder)) {
1311
-                chmod($folder, 0777);
1312
-            }
1313
-        }
1314
-    }
1315
-
1316
-    /**
1317
-     * Load a language file
1318
-     *
1319
-     * @param string $languageFile     The required language file
1320
-     * @param string $defaultExtension Default extension to use
1321
-     */
1322
-    public static function loadLanguageFile($languageFile, $defaultExtension = '.php')
1323
-    {
1324
-        global $xoopsConfig;
1325
-        $root = self::MODULE_PATH;
1326
-        if (strstr($languageFile, $defaultExtension) === false) {
1327
-            $languageFile .= $defaultExtension;
1328
-        }
1329
-        if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile)) {
1330
-            require_once $root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile;
1331
-        } else {    // Fallback
1332
-            require_once $root . 'language' . DIRECTORY_SEPARATOR . 'english' . DIRECTORY_SEPARATOR . $languageFile;
1333
-        }
1334
-    }
1335
-
1336
-    /**
1337
-     * Création d'une vignette en tenant compte des options du module concernant le mode de création des vignettes
1338
-     *
1339
-     * @param  string  $src_path
1340
-     * @param  string  $dst_path
1341
-     * @param  integer $param_width
1342
-     * @param  integer $param_height
1343
-     * @param  boolean $keep_original
1344
-     * @param string   $fit Utilisé uniquement pour la méthode 0 (redimensionnement)
1345
-     * @return boolean
1346
-     */
1347
-    public static function createThumb($src_path, $dst_path, $param_width, $param_height, $keep_original = false, $fit = 'inside')
1348
-    {
1349
-        //        require_once self::MODULE_PATH . 'class/wideimage/WideImage.php';
1350
-        $resize = true;
1351
-        // On commence par vérifier que l'image originale n'est pas plus petite que les dimensions demandées auquel cas il n'y a rien à faire
1352
-        $pictureDimensions = getimagesize($src_path);
1353
-        if (is_array($pictureDimensions)) {
1354
-            $pictureWidth  = $pictureDimensions[0];
1355
-            $pictureHeight = $pictureDimensions[1];
1356
-            if ($pictureWidth < $param_width && $pictureHeight < $param_height) {
1357
-                $resize = false;
1358
-            }
1359
-        }
1360
-        $img = WideImage::load($src_path);
1361
-        if ($resize) { // L'image est suffisament grande pour être réduite
1362
-            $thumbMethod = 0;
1363
-            if ($thumbMethod == 0) { // Redimensionnement de l'image
1364
-                $result = $img->resize($param_width, $param_height, $fit);
1365
-            } else { // Récupération d'une partie de l'image depuis le centre
1366
-                // Calcul de left et top
1367
-                $left = $top = 0;
1368
-                if (is_array($pictureDimensions)) {
1369
-                    if ($pictureWidth > $param_width) {
1370
-                        $left = (int)(($pictureWidth / 2) - ($param_width / 2));
1371
-                    }
1372
-                    if ($pictureHeight > $param_height) {
1373
-                        $top = (int)(($pictureHeight / 2) - ($param_height / 2));
1374
-                    }
1375
-                }
1376
-                $result = $img->crop($left, $top, $param_width, $param_height);
1377
-            }
1378
-            $result->saveToFile($dst_path, null);
1379
-        } else {
1380
-            if ($src_path != $dst_path) {
1381
-                @copy($src_path, $dst_path);
1382
-            }
1383
-        }
1384
-        if (!$keep_original) {
1385
-            @unlink($src_path);
1386
-        }
1387
-
1388
-        return true;
1389
-    }
1390
-
1391
-    /**
1392
-     * Create the <option> of an html select
1393
-     *
1394
-     * @param  array $array   Array of index and labels
1395
-     * @param  mixed $default the default value
1396
-     * @param bool   $withNull
1397
-     * @return string
1398
-     */
1399
-    private static function htmlSelectOptions($array, $default = 0, $withNull = true)
1400
-    {
1401
-        $ret      = array();
1402
-        $selected = '';
1403
-        if ($withNull) {
1404
-            if (!is_array($default)) {
1405
-                if ($default === 0) {
1406
-                    $selected = " selected = 'selected'";
1407
-                }
1408
-            } else {
1409
-                if (in_array(0, $default)) {
1410
-                    $selected = " selected = 'selected'";
1411
-                }
1412
-            }
1413
-            $ret[] = '<option value=0' . $selected . '>---</option>';
1414
-        }
1415
-
1416
-        foreach ($array as $index => $label) {
1417
-            $selected = '';
1418
-            if (!is_array($default)) {
1419
-                if ($index == $default) {
1420
-                    $selected = " selected = 'selected'";
1421
-                }
1422
-            } else {
1423
-                if (in_array($index, $default)) {
1424
-                    $selected = " selected = 'selected'";
1425
-                }
1426
-            }
1427
-            $ret[] = "<option value=\"" . $index . "\"" . $selected . '>' . $label . '</option>';
1428
-        }
1429
-
1430
-        return implode("\n", $ret);
1431
-    }
1432
-
1433
-    /**
1434
-     * Creates an html select an returns its code
1435
-     *
1436
-     * @param  string  $selectName Select's name
1437
-     * @param  array   $array      Key = value of each option, value = label of each option
1438
-     * @param  mixed   $default    Default's value
1439
-     * @param  boolean $withNull   Do we want a null option
1440
-     * @param  string  $style      Is there a style to apply ?
1441
-     * @param  boolean $multiple   Can we select multiple elements ?
1442
-     * @param  integer $size       Size of the selectbox, only used with multiple selectboxes
1443
-     * @param string   $extra
1444
-     * @return string
1445
-     */
1446
-    public static function htmlSelect($selectName, $array, $default, $withNull = true, $style = '', $multiple = false, $size = 1, $extra = '')
1447
-    {
1448
-        $ret = '';
1449
-        $ret .= "<select name='" . $selectName . "' id='" . $selectName . "'";
1450
-        if (xoops_trim($style) != '') {
1451
-            $ret .= " style='" . $style . "' ";
1452
-        }
1453
-        if (xoops_trim($multiple) != '') {
1454
-            $ret .= " multiple = 'multiple' size='" . $size . "' ";
1455
-        }
1456
-        $ret .= $extra . ">\n";
1457
-        $ret .= self::htmlSelectOptions($array, $default, $withNull);
1458
-        $ret .= "</select>\n";
1459
-
1460
-        return $ret;
1461
-    }
1462
-
1463
-    /**
1464
-     * Verify that a mysql table exists
1465
-     * @param $tablename
1466
-     * @return bool
1467
-     */
1468
-    public static function tableExists($tablename)
1469
-    {
1470
-        global $xoopsDB;
1471
-        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
1472
-
1473
-        return ($xoopsDB->getRowsNum($result) > 0);
1474
-    }
1475
-
1476
-    /**
1477
-     * Verify that a field exists inside a mysql table
1478
-     * @param $fieldname
1479
-     * @param $table
1480
-     * @return bool
1481
-     */
1482
-    public static function fieldExists($fieldname, $table)
1483
-    {
1484
-        global $xoopsDB;
1485
-        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1486
-
1487
-        return ($xoopsDB->getRowsNum($result) > 0);
1488
-    }
1489
-
1490
-    /**
1491
-     * Retourne la définition d'un champ
1492
-     *
1493
-     * @param  string $fieldname
1494
-     * @param  string $table
1495
-     * @return array
1496
-     */
1497
-    public static function getFieldDefinition($fieldname, $table)
1498
-    {
1499
-        global $xoopsDB;
1500
-        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1501
-        if ($result) {
1502
-            return $xoopsDB->fetchArray($result);
1503
-        }
1504
-
1505
-        return '';
1506
-    }
1507
-
1508
-    /**
1509
-     * Add a field to a mysql table
1510
-     * @param $field
1511
-     * @param $table
1512
-     * @return resource
1513
-     */
1514
-    public static function addField($field, $table)
1515
-    {
1516
-        global $xoopsDB;
1517
-        $result = $xoopsDB->queryF("ALTER TABLE $table ADD $field;");
1518
-
1519
-        return $result;
1520
-    }
1521
-
1522
-    /**
1523
-     * Maintenance des tables du module et de son cache de requêtes
1524
-     *
1525
-     * @return void
1526
-     */
1527
-    public static function maintainTablesCache()
1528
-    {
1529
-        global $xoopsDB;
1530
-        define('REFERENCES_MAINTAIN', true);
1531
-        require self::MODULE_PATH . 'xoops_version.php';
1532
-        $tables = array();
1533
-        foreach ($modversion['tables'] as $table) {
1534
-            $tables[] = $xoopsDB->prefix($table);
1535
-        }
1536
-        if (count($tables) > 0) {
1537
-            $list = implode(',', $tables);
1538
-            $xoopsDB->queryF('CHECK TABLE ' . $list);
1539
-            $xoopsDB->queryF('ANALYZE TABLE ' . $list);
1540
-            $xoopsDB->queryF('OPTIMIZE TABLE ' . $list);
1541
-        }
1542
-        self::updateCache();
1543
-        $handlers = references_handler::getInstance();
1544
-        $handlers->h_references_articles->forceCacheClean();
1545
-    }
1546
-
1547
-    /**
1548
-     * Indique si le module Tag existe et est activé
1549
-     *
1550
-     * @return boolean
1551
-     * @credit: smartfactory
1552
-     */
1553
-    public static function tagModuleExists()
1554
-    {
1555
-        static $moduleExistsAndIsActive;
1556
-        if (!isset($moduleExistsAndIsActive)) {
1557
-            $modules_handler = xoops_getHandler('module');
1558
-            $tagModule       = $modules_handler->getByDirName('tag');
1559
-            if (!$tagModule) {
1560
-                $moduleExistsAndIsActive = false;
1561
-            } else {
1562
-                $moduleExistsAndIsActive = $tagModule->getVar('isactive') == 1;
1563
-            }
1564
-        }
1565
-
1566
-        return $moduleExistsAndIsActive;
1567
-    }
39
+	// Pour la portabilité de module à module
40
+	const MODULE_NAME    = 'references';
41
+	const MODULE_DIRNAME = REFERENCES_DIRNAME;
42
+	const MODULE_PATH    = REFERENCES_PATH;
43
+	const MODULE_URL     = REFERENCES_URL;
44
+	const MODULE_JS_URL  = REFERENCES_JS_URL;
45
+
46
+	/**
47
+	 * Access the only instance of this class
48
+	 *
49
+	 * @return object
50
+	 *
51
+	 * @static
52
+	 * @staticvar   object
53
+	 */
54
+	public static function getInstance()
55
+	{
56
+		static $instance;
57
+		if (null === $instance) {
58
+			$instance = new static();
59
+		}
60
+
61
+		return $instance;
62
+	}
63
+
64
+	/**
65
+	 * Returns a module's option (with cache)
66
+	 *
67
+	 * @param  string  $option    module option's name
68
+	 * @param  boolean $withCache Do we have to use some cache ?
69
+	 * @return mixed   option's value
70
+	 */
71
+	public static function getModuleOption($option, $withCache = true)
72
+	{
73
+		global $xoopsModuleConfig, $xoopsModule;
74
+		$repmodule = self::MODULE_NAME;
75
+		static $options = array();
76
+		if (is_array($options) && array_key_exists($option, $options) && $withCache) {
77
+			return $options[$option];
78
+		}
79
+
80
+		$retval = false;
81
+		if (isset($xoopsModuleConfig) && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
82
+			if (isset($xoopsModuleConfig[$option])) {
83
+				$retval = $xoopsModuleConfig[$option];
84
+			}
85
+		} else {
86
+			$module_handler = xoops_getHandler('module');
87
+			$module         = $module_handler->getByDirname($repmodule);
88
+			$config_handler = xoops_getHandler('config');
89
+			if ($module) {
90
+				$moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
91
+				if (isset($moduleConfig[$option])) {
92
+					$retval = $moduleConfig[$option];
93
+				}
94
+			}
95
+		}
96
+		$options[$option] = $retval;
97
+
98
+		return $retval;
99
+	}
100
+
101
+	/**
102
+	 * Is Xoops 2.3.x ?
103
+	 *
104
+	 * @return boolean need to say it ?
105
+	 */
106
+	public static function isX23()
107
+	{
108
+		$x23 = false;
109
+		$xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
110
+		if ((int)substr($xv, 2, 1) >= 3) {
111
+			$x23 = true;
112
+		}
113
+
114
+		return $x23;
115
+	}
116
+
117
+	/**
118
+	 * Retreive an editor according to the module's option "form_options"
119
+	 *
120
+	 * @param  string $caption Caption to give to the editor
121
+	 * @param  string $name    Editor's name
122
+	 * @param  string $value   Editor's value
123
+	 * @param  string $width   Editor's width
124
+	 * @param  string $height  Editor's height
125
+	 * @param string  $supplemental
126
+	 * @return object The editor to use
127
+	 */
128
+	public static function getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
129
+	{
130
+		$editor                   = false;
131
+		$editor_configs           = array();
132
+		$editor_configs['name']   = $name;
133
+		$editor_configs['value']  = $value;
134
+		$editor_configs['rows']   = 35;
135
+		$editor_configs['cols']   = 60;
136
+		$editor_configs['width']  = '100%';
137
+		$editor_configs['height'] = '400px';
138
+
139
+		$editor_option = strtolower(self::getModuleOption('form_options'));
140
+
141
+		if (self::isX23()) {
142
+			$editor = new XoopsFormEditor($caption, $editor_option, $editor_configs);
143
+
144
+			return $editor;
145
+		}
146
+
147
+		// Only for Xoops 2.0.x
148
+		switch ($editor_option) {
149
+			case 'fckeditor':
150
+				if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
151
+					require_once(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php');
152
+					$editor = new XoopsFormFckeditor($caption, $name, $value);
153
+				}
154
+				break;
155
+
156
+			case 'htmlarea':
157
+				if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
158
+					require_once(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php');
159
+					$editor = new XoopsFormHtmlarea($caption, $name, $value);
160
+				}
161
+				break;
162
+
163
+			case 'dhtmltextarea':
164
+				$editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
165
+				break;
166
+
167
+			case 'textarea':
168
+				$editor = new XoopsFormTextArea($caption, $name, $value);
169
+				break;
170
+
171
+			case 'tinyeditor':
172
+			case 'tinymce':
173
+				if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
174
+					require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
175
+					$editor = new XoopsFormTinyeditorTextArea(array('caption' => $caption, 'name' => $name, 'value' => $value, 'width' => '100%', 'height' => '400px'));
176
+				}
177
+				break;
178
+
179
+			case 'koivi':
180
+				if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
181
+					require_once(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php');
182
+					$editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
183
+				}
184
+				break;
185
+		}
186
+		if (!is_object($editor)) {
187
+			trigger_error('Error, impossible to get the requested text editor', E_USER_ERROR);
188
+		}
189
+
190
+		return $editor;
191
+	}
192
+
193
+	/**
194
+	 * Create (in a link) a javascript confirmation's box
195
+	 *
196
+	 * @param  string  $message Message to display
197
+	 * @param  boolean $form    Is this a confirmation for a form ?
198
+	 * @return string  the javascript code to insert in the link (or in the form)
199
+	 */
200
+	public static function javascriptLinkConfirm($message, $form = false)
201
+	{
202
+		if (!$form) {
203
+			return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
204
+		} else {
205
+			return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
206
+		}
207
+	}
208
+
209
+	/**
210
+	 * Get current user IP
211
+	 *
212
+	 * @return string IP address (format Ipv4)
213
+	 */
214
+	public static function IP()
215
+	{
216
+		$proxy_ip = '';
217
+		if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
218
+			$proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
219
+		} elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
220
+			$proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
221
+		} elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
222
+			$proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
223
+		} elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
224
+			$proxy_ip = $_SERVER['HTTP_FORWARDED'];
225
+		} elseif (!empty($_SERVER['HTTP_VIA'])) {
226
+			$proxy_ip = $_SERVER['HTTP_VIA'];
227
+		} elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
228
+			$proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
229
+		} elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
230
+			$proxy_ip = $_SERVER['HTTP_COMING_FROM'];
231
+		}
232
+		$regs = array();
233
+		if (!empty($proxy_ip) && $is_ip = ereg('^([0-9]{1,3}\.){3,3}[0-9]{1,3}', $proxy_ip, $regs) && count($regs) > 0) {
234
+			$the_IP = $regs[0];
235
+		} else {
236
+			$the_IP = $_SERVER['REMOTE_ADDR'];
237
+		}
238
+
239
+		return $the_IP;
240
+	}
241
+
242
+	/**
243
+	 * Set the page's title, meta description and meta keywords
244
+	 * Datas are supposed to be sanitized
245
+	 *
246
+	 * @param  string $pageTitle       Page's Title
247
+	 * @param  string $metaDescription Page's meta description
248
+	 * @param  string $metaKeywords    Page's meta keywords
249
+	 * @return void
250
+	 */
251
+	public static function setMetas($pageTitle = '', $metaDescription = '', $metaKeywords = '')
252
+	{
253
+		global $xoTheme, $xoTheme, $xoopsTpl;
254
+		$xoopsTpl->assign('xoops_pagetitle', $pageTitle);
255
+		if (isset($xoTheme) && is_object($xoTheme)) {
256
+			if (!empty($metaKeywords)) {
257
+				$xoTheme->addMeta('meta', 'keywords', $metaKeywords);
258
+			}
259
+			if (!empty($metaDescription)) {
260
+				$xoTheme->addMeta('meta', 'description', $metaDescription);
261
+			}
262
+		} elseif (isset($xoopsTpl) && is_object($xoopsTpl)) {    // Compatibility for old Xoops versions
263
+			if (!empty($metaKeywords)) {
264
+				$xoopsTpl->assign('xoops_meta_keywords', $metaKeywords);
265
+			}
266
+			if (!empty($metaDescription)) {
267
+				$xoopsTpl->assign('xoops_meta_description', $metaDescription);
268
+			}
269
+		}
270
+	}
271
+
272
+	/**
273
+	 * Send an email from a template to a list of recipients
274
+	 *
275
+	 * @param         $tplName
276
+	 * @param  array  $recipients List of recipients
277
+	 * @param  string $subject    Email's subject
278
+	 * @param  array  $variables  Varirables to give to the template
279
+	 * @return bool Result of the send
280
+	 * @internal param string $tpl_name Template's name
281
+	 */
282
+	public static function sendEmailFromTpl($tplName, $recipients, $subject, $variables)
283
+	{
284
+		global $xoopsConfig;
285
+		require_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
286
+		if (!is_array($recipients)) {
287
+			if (trim($recipients) == '') {
288
+				return false;
289
+			}
290
+		} else {
291
+			if (count($recipients) == 0) {
292
+				return false;
293
+			}
294
+		}
295
+		if (function_exists('xoops_getMailer')) {
296
+			$xoopsMailer = xoops_getMailer();
297
+		} else {
298
+			$xoopsMailer =& getMailer();
299
+		}
300
+
301
+		$xoopsMailer->useMail();
302
+		$xoopsMailer->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/' . $xoopsConfig['language'] . '/mail_template');
303
+		$xoopsMailer->setTemplate($tplName);
304
+		$xoopsMailer->setToEmails($recipients);
305
+		// TODO: Change !
306
+		// $xoopsMailer->setFromEmail('[email protected]');
307
+		//$xoopsMailer->setFromName('MonSite');
308
+		$xoopsMailer->setSubject($subject);
309
+		foreach ($variables as $key => $value) {
310
+			$xoopsMailer->assign($key, $value);
311
+		}
312
+		$res = $xoopsMailer->send();
313
+		unset($xoopsMailer);
314
+		$filename = XOOPS_UPLOAD_PATH . '/logmail_' . self::MODULE_NAME . '.php';
315
+		if (!file_exists($filename)) {
316
+			$fp = @fopen($filename, 'a');
317
+			if ($fp) {
318
+				fwrite($fp, '<?php exit(); ?>');
319
+				fclose($fp);
320
+			}
321
+		}
322
+		$fp = @fopen($filename, 'a');
323
+
324
+		if ($fp) {
325
+			fwrite($fp, str_repeat('-', 120) . "\n");
326
+			fwrite($fp, date('d/m/Y H:i:s') . "\n");
327
+			fwrite($fp, 'Template name : ' . $tplName . "\n");
328
+			fwrite($fp, 'Email subject : ' . $subject . "\n");
329
+			if (is_array($recipients)) {
330
+				fwrite($fp, 'Recipient(s) : ' . implode(',', $recipients) . "\n");
331
+			} else {
332
+				fwrite($fp, 'Recipient(s) : ' . $recipients . "\n");
333
+			}
334
+			fwrite($fp, 'Transmited variables : ' . implode(',', $variables) . "\n");
335
+			fclose($fp);
336
+		}
337
+
338
+		return $res;
339
+	}
340
+
341
+	/**
342
+	 * Remove module's cache
343
+	 */
344
+	public static function updateCache()
345
+	{
346
+		global $xoopsModule;
347
+		$folder  = $xoopsModule->getVar('dirname');
348
+		$tpllist = array();
349
+		require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
350
+		require_once XOOPS_ROOT_PATH . '/class/template.php';
351
+		$tplfile_handler = xoops_getHandler('tplfile');
352
+		$tpllist         = $tplfile_handler->find(null, null, null, $folder);
353
+		xoops_template_clear_module_cache($xoopsModule->getVar('mid'));            // Clear module's blocks cache
354
+
355
+		foreach ($tpllist as $onetemplate) {    // Remove cache for each page.
356
+			if ($onetemplate->getVar('tpl_type') === 'module') {
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 = array();
359
+				$files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
360
+				if (count($files_del) > 0 && is_array($files_del)) {
361
+					foreach ($files_del as $one_file) {
362
+						if (is_file($one_file)) {
363
+							unlink($one_file);
364
+						}
365
+					}
366
+				}
367
+			}
368
+		}
369
+	}
370
+
371
+	/**
372
+	 * Redirect user with a message
373
+	 *
374
+	 * @param string $message message to display
375
+	 * @param string $url     The place where to go
376
+	 * @param        integer  timeout Time to wait before to redirect
377
+	 */
378
+	public static function redirect($message = '', $url = 'index.php', $time = 2)
379
+	{
380
+		redirect_header($url, $time, $message);
381
+		exit();
382
+	}
383
+
384
+	/**
385
+	 * Internal function used to get the handler of the current module
386
+	 *
387
+	 * @return object The module
388
+	 */
389
+	public static function getModule()
390
+	{
391
+		static $mymodule;
392
+		if (!isset($mymodule)) {
393
+			global $xoopsModule;
394
+			if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == REFERENCES_DIRNAME) {
395
+				$mymodule =& $xoopsModule;
396
+			} else {
397
+				$hModule  = xoops_getHandler('module');
398
+				$mymodule = $hModule->getByDirname(REFERENCES_DIRNAME);
399
+			}
400
+		}
401
+
402
+		return $mymodule;
403
+	}
404
+
405
+	/**
406
+	 * Returns the module's name (as defined by the user in the module manager) with cache
407
+	 * @return string Module's name
408
+	 */
409
+	public static function getModuleName()
410
+	{
411
+		static $moduleName;
412
+		if (!isset($moduleName)) {
413
+			$mymodule   = self::getModule();
414
+			$moduleName = $mymodule->getVar('name');
415
+		}
416
+
417
+		return $moduleName;
418
+	}
419
+
420
+	/**
421
+	 * Create a title for the href tags inside html links
422
+	 *
423
+	 * @param  string $title Text to use
424
+	 * @return string Formated text
425
+	 */
426
+	public static function makeHrefTitle($title)
427
+	{
428
+		$s = "\"'";
429
+		$r = '  ';
430
+
431
+		return strtr($title, $s, $r);
432
+	}
433
+
434
+	/**
435
+	 * Retourne la liste des utilisateurs appartenants � un groupe
436
+	 *
437
+	 * @param  int $groupId Searched group
438
+	 * @return array Array of XoopsUsers
439
+	 */
440
+	public static function getUsersFromGroup($groupId)
441
+	{
442
+		$users          = array();
443
+		$member_handler = xoops_getHandler('member');
444
+		$users          = $member_handler->getUsersByGroup($groupId, true);
445
+
446
+		return $users;
447
+	}
448
+
449
+	/**
450
+	 * Retourne les ID des utilisateurs faisant partie de plusieurs groupes
451
+	 * @param  array $groups Les ID des groupes dont on recherche les ID utilisateurs
452
+	 * @return array Les ID utilisateurs
453
+	 */
454
+	public static function getUsersIdsFromGroups($groups)
455
+	{
456
+		$usersIds       = array();
457
+		$member_handler = xoops_getHandler('member');
458
+		foreach ($groups as $groupId) {
459
+			$temporaryGroup = array();
460
+			$temporaryGroup = $member_handler->getUsersByGroup($groupId);
461
+			if (count($temporaryGroup) > 0) {
462
+				$usersIds = array_merge($usersIds, $temporaryGroup);
463
+			}
464
+		}
465
+
466
+		return array_unique($usersIds);
467
+	}
468
+
469
+	/**
470
+	 * Retourne la liste des emails des utilisateurs membres d'un groupe
471
+	 *
472
+	 * @param $groupId
473
+	 * @return array Emails list
474
+	 * @internal param int $group_id Group's number
475
+	 */
476
+	public static function getEmailsFromGroup($groupId)
477
+	{
478
+		$ret   = array();
479
+		$users = self::getUsersFromGroup($groupId);
480
+		foreach ($users as $user) {
481
+			$ret[] = $user->getVar('email');
482
+		}
483
+
484
+		return $ret;
485
+	}
486
+
487
+	/**
488
+	 * V�rifie que l'utilisateur courant fait partie du groupe des administrateurs
489
+	 *
490
+	 * @return booleean Admin or not
491
+	 */
492
+	public static function isAdmin()
493
+	{
494
+		global $xoopsUser, $xoopsModule;
495
+		if (is_object($xoopsUser)) {
496
+			if (in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups())) {
497
+				return true;
498
+			} elseif (isset($xoopsModule) && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
499
+				return true;
500
+			}
501
+		}
502
+
503
+		return false;
504
+	}
505
+
506
+	/**
507
+	 * Returns the current date in the Mysql format
508
+	 *
509
+	 * @return string Date in the Mysql format
510
+	 */
511
+	public static function getCurrentSQLDate()
512
+	{
513
+		return date('Y-m-d');    // 2007-05-02
514
+	}
515
+
516
+	public static function getCurrentSQLDateTime()
517
+	{
518
+		return date('Y-m-d H:i:s');    // 2007-05-02
519
+	}
520
+
521
+	/**
522
+	 * Convert a Mysql date to the human's format
523
+	 *
524
+	 * @param  string $date The date to convert
525
+	 * @param string  $format
526
+	 * @return string The date in a human form
527
+	 */
528
+	public static function SQLDateToHuman($date, $format = 'l')
529
+	{
530
+		if ($date != '0000-00-00' && xoops_trim($date) != '') {
531
+			return formatTimestamp(strtotime($date), $format);
532
+		} else {
533
+			return '';
534
+		}
535
+	}
536
+
537
+	/**
538
+	 * Convert a timestamp to a Mysql date
539
+	 *
540
+	 * @param  integer $timestamp The timestamp to use
541
+	 * @return string  The date in the Mysql format
542
+	 */
543
+	public static function timestampToMysqlDate($timestamp)
544
+	{
545
+		return date('Y-m-d', (int)$timestamp);
546
+	}
547
+
548
+	/**
549
+	 * Conversion d'un dateTime Mysql en date lisible en fran�ais
550
+	 * @param $dateTime
551
+	 * @return bool|string
552
+	 */
553
+	public static function sqlDateTimeToFrench($dateTime)
554
+	{
555
+		return date('d/m/Y H:i:s', strtotime($dateTime));
556
+	}
557
+
558
+	/**
559
+	 * Convert a timestamp to a Mysql datetime form
560
+	 * @param  integer $timestamp The timestamp to use
561
+	 * @return string  The date and time in the Mysql format
562
+	 */
563
+	public static function timestampToMysqlDateTime($timestamp)
564
+	{
565
+		return date('Y-m-d H:i:s', $timestamp);
566
+	}
567
+
568
+	/**
569
+	 * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
570
+	 *
571
+	 * @return boolean Yes = we need to add them, false = no
572
+	 */
573
+	public static function needsAsterisk()
574
+	{
575
+		if (self::isX23()) {
576
+			return false;
577
+		}
578
+		if (strpos(strtolower(XOOPS_VERSION), 'impresscms') !== false) {
579
+			return false;
580
+		}
581
+		if (strpos(strtolower(XOOPS_VERSION), 'legacy') === false) {
582
+			$xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
583
+			if ((int)substr($xv, 4, 2) >= 17) {
584
+				return false;
585
+			}
586
+		}
587
+
588
+		return true;
589
+	}
590
+
591
+	/**
592
+	 * Mark the mandatory fields of a form with a star
593
+	 *
594
+	 * @param  object $sform The form to modify
595
+	 * @return object The modified form
596
+	 * @internal param string $caracter The character to use to mark fields
597
+	 */
598
+	public static function &formMarkRequiredFields(&$sform)
599
+	{
600
+		if (self::needsAsterisk()) {
601
+			$required = array();
602
+			foreach ($sform->getRequired() as $item) {
603
+				$required[] = $item->_name;
604
+			}
605
+			$elements = array();
606
+			$elements = &$sform->getElements();
607
+			$cnt      = count($elements);
608
+			for ($i = 0; $i < $cnt; ++$i) {
609
+				if (is_object($elements[$i]) && in_array($elements[$i]->_name, $required)) {
610
+					$elements[$i]->_caption .= ' *';
611
+				}
612
+			}
613
+		}
614
+
615
+		return $sform;
616
+	}
617
+
618
+	/**
619
+	 * Create an html heading (from h1 to h6)
620
+	 *
621
+	 * @param  string  $title The text to use
622
+	 * @param  integer $level Level to return
623
+	 * @return string  The heading
624
+	 */
625
+	public static function htitle($title = '', $level = 1)
626
+	{
627
+		printf('<h%01d>%s</h%01d>', $level, $title, $level);
628
+	}
629
+
630
+	/**
631
+	 * Create a unique upload filename
632
+	 *
633
+	 * @param  string  $folder   The folder where the file will be saved
634
+	 * @param  string  $fileName Original filename (coming from the user)
635
+	 * @param  boolean $trimName Do we need to create a short unique name ?
636
+	 * @return string  The unique filename to use (with its extension)
637
+	 */
638
+	public static function createUploadName($folder, $fileName, $trimName = false)
639
+	{
640
+		$workingfolder = $folder;
641
+		if (substr($workingfolder, strlen($workingfolder) - 1, 1) !== '/') {
642
+			$workingfolder .= '/';
643
+		}
644
+		$ext  = basename($fileName);
645
+		$ext  = explode('.', $ext);
646
+		$ext  = '.' . $ext[count($ext) - 1];
647
+		$true = true;
648
+		while ($true) {
649
+			$ipbits = explode('.', $_SERVER['REMOTE_ADDR']);
650
+			list($usec, $sec) = explode(' ', microtime());
651
+			$usec = (integer)($usec * 65536);
652
+			$sec  = ((integer)$sec) & 0xFFFF;
653
+
654
+			if ($trimName) {
655
+				$uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
656
+			} else {
657
+				$uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
658
+			}
659
+			if (!file_exists($workingfolder . $uid . $ext)) {
660
+				$true = false;
661
+			}
662
+		}
663
+
664
+		return $uid . $ext;
665
+	}
666
+
667
+	/**
668
+	 * Replace html entities with their ASCII equivalent
669
+	 *
670
+	 * @param  string $chaine The string undecode
671
+	 * @return string The undecoded string
672
+	 */
673
+	public static function unhtml($chaine)
674
+	{
675
+		$search = $replace = array();
676
+		$chaine = html_entity_decode($chaine);
677
+
678
+		for ($i = 0; $i <= 255; ++$i) {
679
+			$search[]  = '&#' . $i . ';';
680
+			$replace[] = chr($i);
681
+		}
682
+		$replace[]='...'; $search[]='…';
683
+		$replace[]="'"; $search[]='‘';
684
+		$replace[]="'"; $search[]= '’';
685
+		$replace[]='-'; $search[] = '&bull;';   // $replace[] = '•';
686
+		$replace[]='—'; $search[]='&mdash;';
687
+		$replace[]='-'; $search[]='&ndash;';
688
+		$replace[]='-'; $search[]='&shy;';
689
+		$replace[]='"'; $search[]='&quot;';
690
+		$replace[]='&'; $search[]='&amp;';
691
+		$replace[]='ˆ'; $search[]='&circ;';
692
+		$replace[]='¡'; $search[]='&iexcl;';
693
+		$replace[]='¦'; $search[]='&brvbar;';
694
+		$replace[]='¨'; $search[]='&uml;';
695
+		$replace[]='¯'; $search[]='&macr;';
696
+		$replace[]='´'; $search[]='&acute;';
697
+		$replace[]='¸'; $search[]='&cedil;';
698
+		$replace[]='¿'; $search[]='&iquest;';
699
+		$replace[]='˜'; $search[]='&tilde;';
700
+		$replace[]="'"; $search[]='&lsquo;';    // $replace[]='‘';
701
+		$replace[]="'"; $search[]='&rsquo;';    // $replace[]='’';
702
+		$replace[]='‚'; $search[]='&sbquo;';
703
+		$replace[]="'"; $search[]='&ldquo;';    // $replace[]='“';
704
+		$replace[]="'"; $search[]='&rdquo;';    // $replace[]='”';
705
+		$replace[]='„'; $search[]='&bdquo;';
706
+		$replace[]='‹'; $search[]='&lsaquo;';
707
+		$replace[]='›'; $search[]='&rsaquo;';
708
+		$replace[]='<'; $search[]='&lt;';
709
+		$replace[]='>'; $search[]='&gt;';
710
+		$replace[]='±'; $search[]='&plusmn;';
711
+		$replace[]='«'; $search[]='&laquo;';
712
+		$replace[]='»'; $search[]='&raquo;';
713
+		$replace[]='×'; $search[]='&times;';
714
+		$replace[]='÷'; $search[]='&divide;';
715
+		$replace[]='¢'; $search[]='&cent;';
716
+		$replace[]='£'; $search[]='&pound;';
717
+		$replace[]='¤'; $search[]='&curren;';
718
+		$replace[]='¥'; $search[]='&yen;';
719
+		$replace[]='§'; $search[]='&sect;';
720
+		$replace[]='©'; $search[]='&copy;';
721
+		$replace[]='¬'; $search[]='&not;';
722
+		$replace[]='®'; $search[]='&reg;';
723
+		$replace[]='°'; $search[]='&deg;';
724
+		$replace[]='µ'; $search[]='&micro;';
725
+		$replace[]='¶'; $search[]='&para;';
726
+		$replace[]='·'; $search[]='&middot;';
727
+		$replace[]='†'; $search[]='&dagger;';
728
+		$replace[]='‡'; $search[]='&Dagger;';
729
+		$replace[]='‰'; $search[]='&permil;';
730
+		$replace[]='Euro'; $search[]='&euro;';      // $replace[]='€'
731
+		$replace[]='¼'; $search[]='&frac14;';
732
+		$replace[]='½'; $search[]='&frac12;';
733
+		$replace[]='¾'; $search[]='&frac34;';
734
+		$replace[]='¹'; $search[]='&sup1;';
735
+		$replace[]='²'; $search[]='&sup2;';
736
+		$replace[]='³'; $search[]='&sup3;';
737
+		$replace[]='á'; $search[]='&aacute;';
738
+		$replace[]='Á'; $search[]='&Aacute;';
739
+		$replace[]='â'; $search[]='&acirc;';
740
+		$replace[]='Â'; $search[]='&Acirc;';
741
+		$replace[]='à'; $search[]='&agrave;';
742
+		$replace[]='À'; $search[]='&Agrave;';
743
+		$replace[]='å'; $search[]='&aring;';
744
+		$replace[]='Å'; $search[]='&Aring;';
745
+		$replace[]='ã'; $search[]='&atilde;';
746
+		$replace[]='Ã'; $search[]='&Atilde;';
747
+		$replace[]='ä'; $search[]='&auml;';
748
+		$replace[]='Ä'; $search[]='&Auml;';
749
+		$replace[]='ª'; $search[]='&ordf;';
750
+		$replace[]='æ'; $search[]='&aelig;';
751
+		$replace[]='Æ'; $search[]='&AElig;';
752
+		$replace[]='ç'; $search[]='&ccedil;';
753
+		$replace[]='Ç'; $search[]='&Ccedil;';
754
+		$replace[]='ð'; $search[]='&eth;';
755
+		$replace[]='Ð'; $search[]='&ETH;';
756
+		$replace[]='é'; $search[]='&eacute;';
757
+		$replace[]='É'; $search[]='&Eacute;';
758
+		$replace[]='ê'; $search[]='&ecirc;';
759
+		$replace[]='Ê'; $search[]='&Ecirc;';
760
+		$replace[]='è'; $search[]='&egrave;';
761
+		$replace[]='È'; $search[]='&Egrave;';
762
+		$replace[]='ë'; $search[]='&euml;';
763
+		$replace[]='Ë'; $search[]='&Euml;';
764
+		$replace[]='ƒ'; $search[]='&fnof;';
765
+		$replace[]='í'; $search[]='&iacute;';
766
+		$replace[]='Í'; $search[]='&Iacute;';
767
+		$replace[]='î'; $search[]='&icirc;';
768
+		$replace[]='Î'; $search[]='&Icirc;';
769
+		$replace[]='ì'; $search[]='&igrave;';
770
+		$replace[]='Ì'; $search[]='&Igrave;';
771
+		$replace[]='ï'; $search[]='&iuml;';
772
+		$replace[]='Ï'; $search[]='&Iuml;';
773
+		$replace[]='ñ'; $search[]='&ntilde;';
774
+		$replace[]='Ñ'; $search[]='&Ntilde;';
775
+		$replace[]='ó'; $search[]='&oacute;';
776
+		$replace[]='Ó'; $search[]='&Oacute;';
777
+		$replace[]='ô'; $search[]='&ocirc;';
778
+		$replace[]='Ô'; $search[]='&Ocirc;';
779
+		$replace[]='ò'; $search[]='&ograve;';
780
+		$replace[]='Ò'; $search[]='&Ograve;';
781
+		$replace[]='º'; $search[]='&ordm;';
782
+		$replace[]='ø'; $search[]='&oslash;';
783
+		$replace[]='Ø'; $search[]='&Oslash;';
784
+		$replace[]='õ'; $search[]='&otilde;';
785
+		$replace[]='Õ'; $search[]='&Otilde;';
786
+		$replace[]='ö'; $search[]='&ouml;';
787
+		$replace[]='Ö'; $search[]='&Ouml;';
788
+		$replace[]='œ'; $search[]='&oelig;';
789
+		$replace[]='Œ'; $search[]='&OElig;';
790
+		$replace[]='š'; $search[]='&scaron;';
791
+		$replace[]='Š'; $search[]='&Scaron;';
792
+		$replace[]='ß'; $search[]='&szlig;';
793
+		$replace[]='þ'; $search[]='&thorn;';
794
+		$replace[]='Þ'; $search[]='&THORN;';
795
+		$replace[]='ú'; $search[]='&uacute;';
796
+		$replace[]='Ú'; $search[]='&Uacute;';
797
+		$replace[]='û'; $search[]='&ucirc;';
798
+		$replace[]='Û'; $search[]='&Ucirc;';
799
+		$replace[]='ù'; $search[]='&ugrave;';
800
+		$replace[]='Ù'; $search[]='&Ugrave;';
801
+		$replace[]='ü'; $search[]='&uuml;';
802
+		$replace[]='Ü'; $search[]='&Uuml;';
803
+		$replace[]='ý'; $search[]='&yacute;';
804
+		$replace[]='Ý'; $search[]='&Yacute;';
805
+		$replace[]='ÿ'; $search[]='&yuml;';
806
+		$replace[]='Ÿ'; $search[]='&Yuml;';
807
+		$chaine    = str_replace($search, $replace, $chaine);
808
+
809
+		return $chaine;
810
+	}
811
+
812
+	/**
813
+	 * Création d'une titre pour être utilisé par l'url rewriting
814
+	 *
815
+	 * @param string  $content  Le texte à utiliser pour créer l'url
816
+	 * @param integer $urw      La limite basse pour créer les mots
817
+	 * @return string Le texte à utiliser pour l'url
818
+	 *                          Note, some parts are from Solo's code
819
+	 */
820
+	public static function makeSeoUrl($content, $urw = 1)
821
+	{
822
+		$s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛÜŸÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
823
+		$r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
824
+		$content = self::unhtml($content);    // First, remove html entities
825
+		$content = strtr($content, $s, $r);
826
+		$content = strip_tags($content);
827
+		$content = strtolower($content);
828
+		$content = htmlentities($content);    // TODO: Vérifier
829
+		$content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
830
+		$content = html_entity_decode($content);
831
+		$content = eregi_replace('quot', ' ', $content);
832
+		$content = eregi_replace("'", ' ', $content);
833
+		$content = eregi_replace('-', ' ', $content);
834
+		$content = eregi_replace('[[:punct:]]', '', $content);
835
+		// Selon option mais attention au fichier .htaccess !
836
+		// $content = eregi_replace('[[:digit:]]','', $content);
837
+		$content = preg_replace('/[^a-z|A-Z|0-9]/', '-', $content);
838
+
839
+		$words    = explode(' ', $content);
840
+		$keywords = '';
841
+		foreach ($words as $word) {
842
+			if (strlen($word) >= $urw) {
843
+				$keywords .= '-' . trim($word);
844
+			}
845
+		}
846
+		if (!$keywords) {
847
+			$keywords = '-';
848
+		}
849
+		// Supprime les tirets en double
850
+		$keywords = str_replace('---', '-', $keywords);
851
+		$keywords = str_replace('--', '-', $keywords);
852
+		// Supprime un éventuel tiret à la fin de la chaine
853
+		if (substr($keywords, strlen($keywords) - 1, 1) == '-') {
854
+			$keywords = substr($keywords, 0, strlen($keywords) - 1);
855
+		}
856
+
857
+		return $keywords;
858
+	}
859
+
860
+	/**
861
+	 * Create the meta keywords based on the content
862
+	 *
863
+	 * @param  string $content Content from which we have to create metakeywords
864
+	 * @return string The list of meta keywords
865
+	 */
866
+	public static function createMetaKeywords($content)
867
+	{
868
+		$keywordscount = REFERENCES_METAGEN_MAX_KEYWORDS;
869
+		$keywordsorder = REFERENCES_METAGEN_KEYWORDS_ORDER;
870
+
871
+		$tmp = array();
872
+		// Search for the "Minimum keyword length"
873
+		// TODO: Remplacer references_keywords_limit par une constante
874
+		if (isset($_SESSION['references_keywords_limit'])) {
875
+			$limit = $_SESSION['references_keywords_limit'];
876
+		} else {
877
+			$config_handler                        = xoops_getHandler('config');
878
+			$xoopsConfigSearch                     =& $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
879
+			$limit                                 = $xoopsConfigSearch['keyword_min'];
880
+			$_SESSION['references_keywords_limit'] = $limit;
881
+		}
882
+		$myts            = MyTextSanitizer::getInstance();
883
+		$content         = str_replace('<br>', ' ', $content);
884
+		$content         = $myts->undoHtmlSpecialChars($content);
885
+		$content         = strip_tags($content);
886
+		$content         = strtolower($content);
887
+		$search_pattern  = array('&nbsp;', "\t", "\r\n", "\r", "\n", ',', '.', "'", ';', ':', ')', '(', '"', '?', '!', '{', '}', '[', ']', '<', '>', '/', '+', '-', '_', '\\', '*');
888
+		$replace_pattern = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
889
+		$content         = str_replace($search_pattern, $replace_pattern, $content);
890
+		$keywords        = explode(' ', $content);
891
+		switch ($keywordsorder) {
892
+			case 0:    // Ordre d'apparition dans le texte
893
+				$keywords = array_unique($keywords);
894
+				break;
895
+			case 1:    // Ordre de fréquence des mots
896
+				$keywords = array_count_values($keywords);
897
+				asort($keywords);
898
+				$keywords = array_keys($keywords);
899
+				break;
900
+			case 2:    // Ordre inverse de la fréquence des mots
901
+				$keywords = array_count_values($keywords);
902
+				arsort($keywords);
903
+				$keywords = array_keys($keywords);
904
+				break;
905
+		}
906
+		// Remove black listed words
907
+		if (xoops_trim(self::getModuleOption('metagen_blacklist')) != '') {
908
+			$metagen_blacklist = str_replace("\r", '', self::getModuleOption('metagen_blacklist'));
909
+			$metablack         = explode("\n", $metagen_blacklist);
910
+			array_walk($metablack, 'trim');
911
+			$keywords = array_diff($keywords, $metablack);
912
+		}
913
+
914
+		foreach ($keywords as $keyword) {
915
+			if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
916
+				$tmp[] = $keyword;
917
+			}
918
+		}
919
+		$tmp = array_slice($tmp, 0, $keywordscount);
920
+		if (count($tmp) > 0) {
921
+			return implode(',', $tmp);
922
+		} else {
923
+			if (!isset($config_handler) || !is_object($config_handler)) {
924
+				$config_handler = xoops_getHandler('config');
925
+			}
926
+			$xoopsConfigMetaFooter =& $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
927
+			if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
928
+				return $xoopsConfigMetaFooter['meta_keywords'];
929
+			} else {
930
+				return '';
931
+			}
932
+		}
933
+	}
934
+
935
+	/**
936
+	 * Fonction chargée de gérer l'upload
937
+	 *
938
+	 * @param integer $indice L'indice du fichier à télécharger
939
+	 * @param string  $dstpath
940
+	 * @param null    $mimeTypes
941
+	 * @param null    $uploadMaxSize
942
+	 * @param null    $maxWidth
943
+	 * @param null    $maxHeight
944
+	 * @return mixed True si l'upload s'est bien déroulé sinon le message d'erreur correspondant
945
+	 */
946
+	public static function uploadFile($indice, $dstpath = XOOPS_UPLOAD_PATH, $mimeTypes = null, $uploadMaxSize = null, $maxWidth = null, $maxHeight = null)
947
+	{
948
+		require_once XOOPS_ROOT_PATH . '/class/uploader.php';
949
+		global $destname;
950
+		if (isset($_POST['xoops_upload_file'])) {
951
+			require_once XOOPS_ROOT_PATH . '/class/uploader.php';
952
+			$fldname = '';
953
+			$fldname = $_FILES[$_POST['xoops_upload_file'][$indice]];
954
+			$fldname = get_magic_quotes_gpc() ? stripslashes($fldname['name']) : $fldname['name'];
955
+			if (xoops_trim($fldname != '')) {
956
+				$destname = self::createUploadName($dstpath, $fldname, true);
957
+				if ($mimeTypes === null) {
958
+					$permittedtypes = explode("\n", str_replace("\r", '', self::getModuleOption('mimetypes')));
959
+					array_walk($permittedtypes, 'trim');
960
+				} else {
961
+					$permittedtypes = $mimeTypes;
962
+				}
963
+				if ($uploadMaxSize === null) {
964
+					$uploadSize = self::getModuleOption('maxuploadsize');
965
+				} else {
966
+					$uploadSize = $uploadMaxSize;
967
+				}
968
+				$uploader = new XoopsMediaUploader($dstpath, $permittedtypes, $uploadSize, $maxWidth, $maxHeight);
969
+				//$uploader->allowUnknownTypes = true;
970
+				$uploader->setTargetFileName($destname);
971
+				if ($uploader->fetchMedia($_POST['xoops_upload_file'][$indice])) {
972
+					if ($uploader->upload()) {
973
+						return true;
974
+					} else {
975
+						return _ERRORS . ' ' . htmlentities($uploader->getErrors());
976
+					}
977
+				} else {
978
+					return htmlentities($uploader->getErrors());
979
+				}
980
+			} else {
981
+				return false;
982
+			}
983
+		} else {
984
+			return false;
985
+		}
986
+	}
987
+
988
+	/**
989
+	 * Resize a Picture to some given dimensions (using the wideImage library)
990
+	 *
991
+	 * @param string  $src_path      Picture's source
992
+	 * @param string  $dst_path      Picture's destination
993
+	 * @param integer $param_width   Maximum picture's width
994
+	 * @param integer $param_height  Maximum picture's height
995
+	 * @param boolean $keep_original Do we have to keep the original picture ?
996
+	 * @param string  $fit           Resize mode (see the wideImage library for more information)
997
+	 * @return bool
998
+	 */
999
+	public static function resizePicture($src_path, $dst_path, $param_width, $param_height, $keep_original = false, $fit = 'inside')
1000
+	{
1001
+		//        require_once self::MODULE_PATH . 'class/wideimage/WideImage.php';
1002
+		$img    = WideImage::load($src_path);
1003
+		$result = $img->resize($param_width, $param_height, $fit);
1004
+		$result->saveToFile($dst_path, null);
1005
+		if (!$keep_original) {
1006
+			@unlink($src_path);
1007
+		}
1008
+
1009
+		return true;
1010
+	}
1011
+
1012
+	/**
1013
+	 * Déclenchement d'une alerte Xoops suite à un évènement
1014
+	 *
1015
+	 * @param string       $category La catégorie de l'évènement
1016
+	 * @param integer      $itemId   L'ID de l'élément (trop général pour être décris précisément)
1017
+	 * @param unknown_type $event    L'évènement qui est déclencé
1018
+	 * @param unknown_type $tags     Les variables à passer au template
1019
+	 */
1020
+	public static function notify($category, $itemId, $event, $tags)
1021
+	{
1022
+		$notification_handler = xoops_getHandler('notification');
1023
+		$tags['X_MODULE_URL'] = REFERENCES_URL;
1024
+		$notification_handler->triggerEvent($category, $itemId, $event, $tags);
1025
+	}
1026
+
1027
+	/**
1028
+	 * Ajoute des jours à une date et retourne la nouvelle date au format Date de Mysql
1029
+	 *
1030
+	 * @param int     $duration
1031
+	 * @param integer $startingDate Date de départ (timestamp)
1032
+	 * @return bool|string
1033
+	 * @internal param int $durations Durée en jours
1034
+	 */
1035
+	public static function addDaysToDate($duration = 1, $startingDate = 0)
1036
+	{
1037
+		if ($startingDate == 0) {
1038
+			$startingDate = time();
1039
+		}
1040
+		$endingDate = $startingDate + ($duration * 86400);
1041
+
1042
+		return date('Y-m-d', $endingDate);
1043
+	}
1044
+
1045
+	/**
1046
+	 * Retourne un breadcrumb en fonction des paramètres passés et en partant (d'office) de la racine du module
1047
+	 *
1048
+	 * @param array  $path  Le chemin complet (excepté la racine) du breadcrumb sous la forme clé=url valeur=titre
1049
+	 * @param string $raquo Le séparateur par défaut à utiliser
1050
+	 * @return string le breadcrumb
1051
+	 */
1052
+	public static function breadcrumb($path, $raquo = ' &raquo; ')
1053
+	{
1054
+		$breadcrumb        = '';
1055
+		$workingBreadcrumb = array();
1056
+		if (is_array($path)) {
1057
+			$moduleName          = self::getModuleName();
1058
+			$workingBreadcrumb[] = "<a href='" . REFERENCES_URL . "' title='" . self::makeHrefTitle($moduleName) . "'>" . $moduleName . '</a>';
1059
+			foreach ($path as $url => $title) {
1060
+				$workingBreadcrumb[] = "<a href='" . $url . "'>" . $title . '</a>';
1061
+			}
1062
+			$cnt = count($workingBreadcrumb);
1063
+			for ($i = 0; $i < $cnt; ++$i) {
1064
+				if ($i == $cnt - 1) {
1065
+					$workingBreadcrumb[$i] = strip_tags($workingBreadcrumb[$i]);
1066
+				}
1067
+			}
1068
+			$breadcrumb = implode($raquo, $workingBreadcrumb);
1069
+		}
1070
+
1071
+		return $breadcrumb;
1072
+	}
1073
+
1074
+	public static function close_tags($string)
1075
+	{
1076
+		// match opened tags
1077
+		if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
1078
+			$start_tags = $start_tags[1];
1079
+
1080
+			// match closed tags
1081
+			if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
1082
+				$complete_tags = array();
1083
+				$end_tags      = $end_tags[1];
1084
+
1085
+				foreach ($start_tags as $key => $val) {
1086
+					$posb = array_search($val, $end_tags);
1087
+					if (is_int($posb)) {
1088
+						unset($end_tags[$posb]);
1089
+					} else {
1090
+						$complete_tags[] = $val;
1091
+					}
1092
+				}
1093
+			} else {
1094
+				$complete_tags = $start_tags;
1095
+			}
1096
+
1097
+			$complete_tags = array_reverse($complete_tags);
1098
+			for ($i = 0; $i < count($complete_tags); ++$i) {
1099
+				$string .= '</' . $complete_tags[$i] . '>';
1100
+			}
1101
+		}
1102
+
1103
+		return $string;
1104
+	}
1105
+
1106
+	public static function truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
1107
+	{
1108
+		if ($length == 0) {
1109
+			return '';
1110
+		}
1111
+
1112
+		if (strlen($string) > $length) {
1113
+			$length -= strlen($etc);
1114
+			if (!$break_words) {
1115
+				$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
1116
+				$string = preg_replace('/<[^>]*$/', '', $string);
1117
+				$string = self::close_tags($string);
1118
+			}
1119
+
1120
+			return $string . $etc;
1121
+		} else {
1122
+			return $string;
1123
+		}
1124
+	}
1125
+
1126
+	/**
1127
+	 * Create an infotip
1128
+	 * @param $text
1129
+	 * @return string
1130
+	 */
1131
+	public static function makeInfotips($text)
1132
+	{
1133
+		$ret      = '';
1134
+		$infotips = self::getModuleOption('infotips');
1135
+		if ($infotips > 0) {
1136
+			$myts = MyTextSanitizer::getInstance();
1137
+			$ret  = $myts->htmlSpecialChars(substr(strip_tags($text), 0, $infotips));
1138
+		}
1139
+
1140
+		return $ret;
1141
+	}
1142
+
1143
+	/**
1144
+	 * Retourne le type Mime d'un fichier en utilisant d'abord finfo puis mime_content
1145
+	 *
1146
+	 * @param string $filename Le fichier (avec son chemin d'accès complet) dont on veut connaître le type mime
1147
+	 * @return string
1148
+	 */
1149
+	public static function getMimeType($filename)
1150
+	{
1151
+		if (function_exists('finfo_open')) {
1152
+			$pathToMagic = REFERENCES_PATH . 'mime/magic';
1153
+			$finfo       = new finfo(FILEINFO_MIME, $pathToMagic);
1154
+			$mimetype    = $finfo->file($filename);
1155
+			finfo_close($finfo);
1156
+			unset($finfo);
1157
+
1158
+			return $mimetype;
1159
+		} else {
1160
+			if (function_exists('mime_content_type')) {
1161
+				return mime_content_type($filename);
1162
+			} else {
1163
+				return '';
1164
+			}
1165
+		}
1166
+	}
1167
+
1168
+	/**
1169
+	 * Retourne une liste d'objets XoopsUsers à partir d'une liste d'identifiants
1170
+	 *
1171
+	 * @param  array $xoopsUsersIDs La liste des ID
1172
+	 * @return array Les objets XoopsUsers
1173
+	 */
1174
+	public static function getUsersFromIds($xoopsUsersIDs)
1175
+	{
1176
+		$users = array();
1177
+		if (is_array($xoopsUsersIDs) && count($xoopsUsersIDs) > 0) {
1178
+			$xoopsUsersIDs = array_unique($xoopsUsersIDs);
1179
+			sort($xoopsUsersIDs);
1180
+			if (count($xoopsUsersIDs) > 0) {
1181
+				$member_handler = xoops_getHandler('user');
1182
+				$criteria       = new Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
1183
+				$criteria->setSort('uid');
1184
+				$users = $member_handler->getObjects($criteria, true);
1185
+			}
1186
+		}
1187
+
1188
+		return $users;
1189
+	}
1190
+
1191
+	/**
1192
+	 * Retourne l'ID de l'utilisateur courant (s'il est connecté)
1193
+	 * @return integer L'uid ou 0
1194
+	 */
1195
+	public static function getCurrentUserID()
1196
+	{
1197
+		global $xoopsUser;
1198
+		$uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
1199
+
1200
+		return $uid;
1201
+	}
1202
+
1203
+	/**
1204
+	 * Retourne la liste des groupes de l'utilisateur courant (avec cache)
1205
+	 * @param int $uid
1206
+	 * @return array Les ID des groupes auquel l'utilisateur courant appartient
1207
+	 */
1208
+	public static function getMemberGroups($uid = 0)
1209
+	{
1210
+		static $buffer = array();
1211
+		if ($uid == 0) {
1212
+			$uid = self::getCurrentUserID();
1213
+		}
1214
+
1215
+		if (is_array($buffer) && count($buffer) > 0 && isset($buffer[$uid])) {
1216
+			return $buffer[$uid];
1217
+		} else {
1218
+			if ($uid > 0) {
1219
+				$member_handler = xoops_getHandler('member');
1220
+				$buffer[$uid]   = $member_handler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
1221
+			} else {
1222
+				$buffer[$uid] = array(XOOPS_GROUP_ANONYMOUS);
1223
+			}
1224
+		}
1225
+
1226
+		return $buffer[$uid];
1227
+	}
1228
+
1229
+	/**
1230
+	 * Indique si l'utilisateur courant fait partie d'une groupe donné (avec gestion de cache)
1231
+	 *
1232
+	 * @param integer $group Groupe recherché
1233
+	 * @param int     $uid
1234
+	 * @return bool vrai si l'utilisateur fait partie du groupe, faux sinon
1235
+	 */
1236
+	public static function isMemberOfGroup($group = 0, $uid = 0)
1237
+	{
1238
+		static $buffer = array();
1239
+		$retval = false;
1240
+		if ($uid == 0) {
1241
+			$uid = self::getCurrentUserID();
1242
+		}
1243
+		if (is_array($buffer) && array_key_exists($group, $buffer)) {
1244
+			$retval = $buffer[$group];
1245
+		} else {
1246
+			$member_handler = xoops_getHandler('member');
1247
+			$groups         = $member_handler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
1248
+			$retval         = in_array($group, $groups);
1249
+			$buffer[$group] = $retval;
1250
+		}
1251
+
1252
+		return $retval;
1253
+	}
1254
+
1255
+	/**
1256
+	 * Indique si un utilisateur fait partie de plusieurs groupes
1257
+	 * La fonction renvoie vrai dès qu'on trouve que le membre fait partir d'un des groupes
1258
+	 * @param array    $groups La liste des groupes à vérifier
1259
+	 * @param  integer $uid    L'ID de l'utilisateur
1260
+	 * @return boolean
1261
+	 */
1262
+	public static function isMemberOfGroups($groups, $uid = 0)
1263
+	{
1264
+		if (count($groups) == 0) {
1265
+			return false;
1266
+		}
1267
+		if ($uid == 0) {
1268
+			$uid = self::getCurrentUserID();
1269
+		}
1270
+		foreach ($groups as $groupId) {
1271
+			if (self::isMemberOfGroup($groupId, $uid)) {
1272
+				return true;
1273
+			}
1274
+		}
1275
+
1276
+		return false;
1277
+	}
1278
+
1279
+	/**
1280
+	 * Retourne le nombre total de groupes (y compris les anonymes)
1281
+	 */
1282
+	public static function getGroupsCount()
1283
+	{
1284
+		static $cache = -1;
1285
+		if ($cache == -1) {
1286
+			global $xoopsDB;
1287
+			$sql    = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix('groups');
1288
+			$result = $xoopsDB->query($sql);
1289
+			if (!$result) {
1290
+				return false;
1291
+			}
1292
+			list($cache) = $xoopsDB->fetchRow($result);
1293
+		}
1294
+
1295
+		return $cache;
1296
+	}
1297
+
1298
+	/**
1299
+	 * Fonction chargée de vérifier qu'un répertoire existe, qu'on peut écrire dedans et création d'un fichier index.html
1300
+	 *
1301
+	 * @param string $folder Le chemin complet du répertoire à vérifier
1302
+	 * @return void
1303
+	 */
1304
+	public static function prepareFolder($folder)
1305
+	{
1306
+		if (!is_dir($folder)) {
1307
+			mkdir($folder, 0777);
1308
+			file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
1309
+		} else {
1310
+			if (!is_writable($folder)) {
1311
+				chmod($folder, 0777);
1312
+			}
1313
+		}
1314
+	}
1315
+
1316
+	/**
1317
+	 * Load a language file
1318
+	 *
1319
+	 * @param string $languageFile     The required language file
1320
+	 * @param string $defaultExtension Default extension to use
1321
+	 */
1322
+	public static function loadLanguageFile($languageFile, $defaultExtension = '.php')
1323
+	{
1324
+		global $xoopsConfig;
1325
+		$root = self::MODULE_PATH;
1326
+		if (strstr($languageFile, $defaultExtension) === false) {
1327
+			$languageFile .= $defaultExtension;
1328
+		}
1329
+		if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile)) {
1330
+			require_once $root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile;
1331
+		} else {    // Fallback
1332
+			require_once $root . 'language' . DIRECTORY_SEPARATOR . 'english' . DIRECTORY_SEPARATOR . $languageFile;
1333
+		}
1334
+	}
1335
+
1336
+	/**
1337
+	 * Création d'une vignette en tenant compte des options du module concernant le mode de création des vignettes
1338
+	 *
1339
+	 * @param  string  $src_path
1340
+	 * @param  string  $dst_path
1341
+	 * @param  integer $param_width
1342
+	 * @param  integer $param_height
1343
+	 * @param  boolean $keep_original
1344
+	 * @param string   $fit Utilisé uniquement pour la méthode 0 (redimensionnement)
1345
+	 * @return boolean
1346
+	 */
1347
+	public static function createThumb($src_path, $dst_path, $param_width, $param_height, $keep_original = false, $fit = 'inside')
1348
+	{
1349
+		//        require_once self::MODULE_PATH . 'class/wideimage/WideImage.php';
1350
+		$resize = true;
1351
+		// On commence par vérifier que l'image originale n'est pas plus petite que les dimensions demandées auquel cas il n'y a rien à faire
1352
+		$pictureDimensions = getimagesize($src_path);
1353
+		if (is_array($pictureDimensions)) {
1354
+			$pictureWidth  = $pictureDimensions[0];
1355
+			$pictureHeight = $pictureDimensions[1];
1356
+			if ($pictureWidth < $param_width && $pictureHeight < $param_height) {
1357
+				$resize = false;
1358
+			}
1359
+		}
1360
+		$img = WideImage::load($src_path);
1361
+		if ($resize) { // L'image est suffisament grande pour être réduite
1362
+			$thumbMethod = 0;
1363
+			if ($thumbMethod == 0) { // Redimensionnement de l'image
1364
+				$result = $img->resize($param_width, $param_height, $fit);
1365
+			} else { // Récupération d'une partie de l'image depuis le centre
1366
+				// Calcul de left et top
1367
+				$left = $top = 0;
1368
+				if (is_array($pictureDimensions)) {
1369
+					if ($pictureWidth > $param_width) {
1370
+						$left = (int)(($pictureWidth / 2) - ($param_width / 2));
1371
+					}
1372
+					if ($pictureHeight > $param_height) {
1373
+						$top = (int)(($pictureHeight / 2) - ($param_height / 2));
1374
+					}
1375
+				}
1376
+				$result = $img->crop($left, $top, $param_width, $param_height);
1377
+			}
1378
+			$result->saveToFile($dst_path, null);
1379
+		} else {
1380
+			if ($src_path != $dst_path) {
1381
+				@copy($src_path, $dst_path);
1382
+			}
1383
+		}
1384
+		if (!$keep_original) {
1385
+			@unlink($src_path);
1386
+		}
1387
+
1388
+		return true;
1389
+	}
1390
+
1391
+	/**
1392
+	 * Create the <option> of an html select
1393
+	 *
1394
+	 * @param  array $array   Array of index and labels
1395
+	 * @param  mixed $default the default value
1396
+	 * @param bool   $withNull
1397
+	 * @return string
1398
+	 */
1399
+	private static function htmlSelectOptions($array, $default = 0, $withNull = true)
1400
+	{
1401
+		$ret      = array();
1402
+		$selected = '';
1403
+		if ($withNull) {
1404
+			if (!is_array($default)) {
1405
+				if ($default === 0) {
1406
+					$selected = " selected = 'selected'";
1407
+				}
1408
+			} else {
1409
+				if (in_array(0, $default)) {
1410
+					$selected = " selected = 'selected'";
1411
+				}
1412
+			}
1413
+			$ret[] = '<option value=0' . $selected . '>---</option>';
1414
+		}
1415
+
1416
+		foreach ($array as $index => $label) {
1417
+			$selected = '';
1418
+			if (!is_array($default)) {
1419
+				if ($index == $default) {
1420
+					$selected = " selected = 'selected'";
1421
+				}
1422
+			} else {
1423
+				if (in_array($index, $default)) {
1424
+					$selected = " selected = 'selected'";
1425
+				}
1426
+			}
1427
+			$ret[] = "<option value=\"" . $index . "\"" . $selected . '>' . $label . '</option>';
1428
+		}
1429
+
1430
+		return implode("\n", $ret);
1431
+	}
1432
+
1433
+	/**
1434
+	 * Creates an html select an returns its code
1435
+	 *
1436
+	 * @param  string  $selectName Select's name
1437
+	 * @param  array   $array      Key = value of each option, value = label of each option
1438
+	 * @param  mixed   $default    Default's value
1439
+	 * @param  boolean $withNull   Do we want a null option
1440
+	 * @param  string  $style      Is there a style to apply ?
1441
+	 * @param  boolean $multiple   Can we select multiple elements ?
1442
+	 * @param  integer $size       Size of the selectbox, only used with multiple selectboxes
1443
+	 * @param string   $extra
1444
+	 * @return string
1445
+	 */
1446
+	public static function htmlSelect($selectName, $array, $default, $withNull = true, $style = '', $multiple = false, $size = 1, $extra = '')
1447
+	{
1448
+		$ret = '';
1449
+		$ret .= "<select name='" . $selectName . "' id='" . $selectName . "'";
1450
+		if (xoops_trim($style) != '') {
1451
+			$ret .= " style='" . $style . "' ";
1452
+		}
1453
+		if (xoops_trim($multiple) != '') {
1454
+			$ret .= " multiple = 'multiple' size='" . $size . "' ";
1455
+		}
1456
+		$ret .= $extra . ">\n";
1457
+		$ret .= self::htmlSelectOptions($array, $default, $withNull);
1458
+		$ret .= "</select>\n";
1459
+
1460
+		return $ret;
1461
+	}
1462
+
1463
+	/**
1464
+	 * Verify that a mysql table exists
1465
+	 * @param $tablename
1466
+	 * @return bool
1467
+	 */
1468
+	public static function tableExists($tablename)
1469
+	{
1470
+		global $xoopsDB;
1471
+		$result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
1472
+
1473
+		return ($xoopsDB->getRowsNum($result) > 0);
1474
+	}
1475
+
1476
+	/**
1477
+	 * Verify that a field exists inside a mysql table
1478
+	 * @param $fieldname
1479
+	 * @param $table
1480
+	 * @return bool
1481
+	 */
1482
+	public static function fieldExists($fieldname, $table)
1483
+	{
1484
+		global $xoopsDB;
1485
+		$result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1486
+
1487
+		return ($xoopsDB->getRowsNum($result) > 0);
1488
+	}
1489
+
1490
+	/**
1491
+	 * Retourne la définition d'un champ
1492
+	 *
1493
+	 * @param  string $fieldname
1494
+	 * @param  string $table
1495
+	 * @return array
1496
+	 */
1497
+	public static function getFieldDefinition($fieldname, $table)
1498
+	{
1499
+		global $xoopsDB;
1500
+		$result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1501
+		if ($result) {
1502
+			return $xoopsDB->fetchArray($result);
1503
+		}
1504
+
1505
+		return '';
1506
+	}
1507
+
1508
+	/**
1509
+	 * Add a field to a mysql table
1510
+	 * @param $field
1511
+	 * @param $table
1512
+	 * @return resource
1513
+	 */
1514
+	public static function addField($field, $table)
1515
+	{
1516
+		global $xoopsDB;
1517
+		$result = $xoopsDB->queryF("ALTER TABLE $table ADD $field;");
1518
+
1519
+		return $result;
1520
+	}
1521
+
1522
+	/**
1523
+	 * Maintenance des tables du module et de son cache de requêtes
1524
+	 *
1525
+	 * @return void
1526
+	 */
1527
+	public static function maintainTablesCache()
1528
+	{
1529
+		global $xoopsDB;
1530
+		define('REFERENCES_MAINTAIN', true);
1531
+		require self::MODULE_PATH . 'xoops_version.php';
1532
+		$tables = array();
1533
+		foreach ($modversion['tables'] as $table) {
1534
+			$tables[] = $xoopsDB->prefix($table);
1535
+		}
1536
+		if (count($tables) > 0) {
1537
+			$list = implode(',', $tables);
1538
+			$xoopsDB->queryF('CHECK TABLE ' . $list);
1539
+			$xoopsDB->queryF('ANALYZE TABLE ' . $list);
1540
+			$xoopsDB->queryF('OPTIMIZE TABLE ' . $list);
1541
+		}
1542
+		self::updateCache();
1543
+		$handlers = references_handler::getInstance();
1544
+		$handlers->h_references_articles->forceCacheClean();
1545
+	}
1546
+
1547
+	/**
1548
+	 * Indique si le module Tag existe et est activé
1549
+	 *
1550
+	 * @return boolean
1551
+	 * @credit: smartfactory
1552
+	 */
1553
+	public static function tagModuleExists()
1554
+	{
1555
+		static $moduleExistsAndIsActive;
1556
+		if (!isset($moduleExistsAndIsActive)) {
1557
+			$modules_handler = xoops_getHandler('module');
1558
+			$tagModule       = $modules_handler->getByDirName('tag');
1559
+			if (!$tagModule) {
1560
+				$moduleExistsAndIsActive = false;
1561
+			} else {
1562
+				$moduleExistsAndIsActive = $tagModule->getVar('isactive') == 1;
1563
+			}
1564
+		}
1565
+
1566
+		return $moduleExistsAndIsActive;
1567
+	}
1568 1568
 }
Please login to merge, or discard this patch.
Spacing   +198 added lines, -198 removed lines patch added patch discarded remove patch
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
     {
108 108
         $x23 = false;
109 109
         $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
110
-        if ((int)substr($xv, 2, 1) >= 3) {
110
+        if ((int) substr($xv, 2, 1) >= 3) {
111 111
             $x23 = true;
112 112
         }
113 113
 
@@ -147,15 +147,15 @@  discard block
 block discarded – undo
147 147
         // Only for Xoops 2.0.x
148 148
         switch ($editor_option) {
149 149
             case 'fckeditor':
150
-                if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
151
-                    require_once(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php');
150
+                if (is_readable(XOOPS_ROOT_PATH.'/class/fckeditor/formfckeditor.php')) {
151
+                    require_once(XOOPS_ROOT_PATH.'/class/fckeditor/formfckeditor.php');
152 152
                     $editor = new XoopsFormFckeditor($caption, $name, $value);
153 153
                 }
154 154
                 break;
155 155
 
156 156
             case 'htmlarea':
157
-                if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
158
-                    require_once(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php');
157
+                if (is_readable(XOOPS_ROOT_PATH.'/class/htmlarea/formhtmlarea.php')) {
158
+                    require_once(XOOPS_ROOT_PATH.'/class/htmlarea/formhtmlarea.php');
159 159
                     $editor = new XoopsFormHtmlarea($caption, $name, $value);
160 160
                 }
161 161
                 break;
@@ -170,15 +170,15 @@  discard block
 block discarded – undo
170 170
 
171 171
             case 'tinyeditor':
172 172
             case 'tinymce':
173
-                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
174
-                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
173
+                if (is_readable(XOOPS_ROOT_PATH.'/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
174
+                    require_once XOOPS_ROOT_PATH.'/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
175 175
                     $editor = new XoopsFormTinyeditorTextArea(array('caption' => $caption, 'name' => $name, 'value' => $value, 'width' => '100%', 'height' => '400px'));
176 176
                 }
177 177
                 break;
178 178
 
179 179
             case 'koivi':
180
-                if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
181
-                    require_once(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php');
180
+                if (is_readable(XOOPS_ROOT_PATH.'/class/wysiwyg/formwysiwygtextarea.php')) {
181
+                    require_once(XOOPS_ROOT_PATH.'/class/wysiwyg/formwysiwygtextarea.php');
182 182
                     $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
183 183
                 }
184 184
                 break;
@@ -200,9 +200,9 @@  discard block
 block discarded – undo
200 200
     public static function javascriptLinkConfirm($message, $form = false)
201 201
     {
202 202
         if (!$form) {
203
-            return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
203
+            return "onclick=\"javascript:return confirm('".str_replace("'", ' ', $message)."')\"";
204 204
         } else {
205
-            return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
205
+            return "onSubmit=\"javascript:return confirm('".str_replace("'", ' ', $message)."')\"";
206 206
         }
207 207
     }
208 208
 
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
     public static function sendEmailFromTpl($tplName, $recipients, $subject, $variables)
283 283
     {
284 284
         global $xoopsConfig;
285
-        require_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
285
+        require_once XOOPS_ROOT_PATH.'/class/xoopsmailer.php';
286 286
         if (!is_array($recipients)) {
287 287
             if (trim($recipients) == '') {
288 288
                 return false;
@@ -295,11 +295,11 @@  discard block
 block discarded – undo
295 295
         if (function_exists('xoops_getMailer')) {
296 296
             $xoopsMailer = xoops_getMailer();
297 297
         } else {
298
-            $xoopsMailer =& getMailer();
298
+            $xoopsMailer = & getMailer();
299 299
         }
300 300
 
301 301
         $xoopsMailer->useMail();
302
-        $xoopsMailer->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/' . $xoopsConfig['language'] . '/mail_template');
302
+        $xoopsMailer->setTemplateDir(XOOPS_ROOT_PATH.'/modules/'.self::MODULE_NAME.'/language/'.$xoopsConfig['language'].'/mail_template');
303 303
         $xoopsMailer->setTemplate($tplName);
304 304
         $xoopsMailer->setToEmails($recipients);
305 305
         // TODO: Change !
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
         }
312 312
         $res = $xoopsMailer->send();
313 313
         unset($xoopsMailer);
314
-        $filename = XOOPS_UPLOAD_PATH . '/logmail_' . self::MODULE_NAME . '.php';
314
+        $filename = XOOPS_UPLOAD_PATH.'/logmail_'.self::MODULE_NAME.'.php';
315 315
         if (!file_exists($filename)) {
316 316
             $fp = @fopen($filename, 'a');
317 317
             if ($fp) {
@@ -322,16 +322,16 @@  discard block
 block discarded – undo
322 322
         $fp = @fopen($filename, 'a');
323 323
 
324 324
         if ($fp) {
325
-            fwrite($fp, str_repeat('-', 120) . "\n");
326
-            fwrite($fp, date('d/m/Y H:i:s') . "\n");
327
-            fwrite($fp, 'Template name : ' . $tplName . "\n");
328
-            fwrite($fp, 'Email subject : ' . $subject . "\n");
325
+            fwrite($fp, str_repeat('-', 120)."\n");
326
+            fwrite($fp, date('d/m/Y H:i:s')."\n");
327
+            fwrite($fp, 'Template name : '.$tplName."\n");
328
+            fwrite($fp, 'Email subject : '.$subject."\n");
329 329
             if (is_array($recipients)) {
330
-                fwrite($fp, 'Recipient(s) : ' . implode(',', $recipients) . "\n");
330
+                fwrite($fp, 'Recipient(s) : '.implode(',', $recipients)."\n");
331 331
             } else {
332
-                fwrite($fp, 'Recipient(s) : ' . $recipients . "\n");
332
+                fwrite($fp, 'Recipient(s) : '.$recipients."\n");
333 333
             }
334
-            fwrite($fp, 'Transmited variables : ' . implode(',', $variables) . "\n");
334
+            fwrite($fp, 'Transmited variables : '.implode(',', $variables)."\n");
335 335
             fclose($fp);
336 336
         }
337 337
 
@@ -346,17 +346,17 @@  discard block
 block discarded – undo
346 346
         global $xoopsModule;
347 347
         $folder  = $xoopsModule->getVar('dirname');
348 348
         $tpllist = array();
349
-        require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
350
-        require_once XOOPS_ROOT_PATH . '/class/template.php';
349
+        require_once XOOPS_ROOT_PATH.'/class/xoopsblock.php';
350
+        require_once XOOPS_ROOT_PATH.'/class/template.php';
351 351
         $tplfile_handler = xoops_getHandler('tplfile');
352 352
         $tpllist         = $tplfile_handler->find(null, null, null, $folder);
353
-        xoops_template_clear_module_cache($xoopsModule->getVar('mid'));            // Clear module's blocks cache
353
+        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
354 354
 
355 355
         foreach ($tpllist as $onetemplate) {    // Remove cache for each page.
356 356
             if ($onetemplate->getVar('tpl_type') === 'module') {
357 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 358
                 $files_del = array();
359
-                $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
359
+                $files_del = glob(XOOPS_CACHE_PATH.'/*'.$onetemplate->getVar('tpl_file').'*');
360 360
                 if (count($files_del) > 0 && is_array($files_del)) {
361 361
                     foreach ($files_del as $one_file) {
362 362
                         if (is_file($one_file)) {
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
         if (!isset($mymodule)) {
393 393
             global $xoopsModule;
394 394
             if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == REFERENCES_DIRNAME) {
395
-                $mymodule =& $xoopsModule;
395
+                $mymodule = & $xoopsModule;
396 396
             } else {
397 397
                 $hModule  = xoops_getHandler('module');
398 398
                 $mymodule = $hModule->getByDirname(REFERENCES_DIRNAME);
@@ -510,12 +510,12 @@  discard block
 block discarded – undo
510 510
      */
511 511
     public static function getCurrentSQLDate()
512 512
     {
513
-        return date('Y-m-d');    // 2007-05-02
513
+        return date('Y-m-d'); // 2007-05-02
514 514
     }
515 515
 
516 516
     public static function getCurrentSQLDateTime()
517 517
     {
518
-        return date('Y-m-d H:i:s');    // 2007-05-02
518
+        return date('Y-m-d H:i:s'); // 2007-05-02
519 519
     }
520 520
 
521 521
     /**
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
      */
543 543
     public static function timestampToMysqlDate($timestamp)
544 544
     {
545
-        return date('Y-m-d', (int)$timestamp);
545
+        return date('Y-m-d', (int) $timestamp);
546 546
     }
547 547
 
548 548
     /**
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
         }
581 581
         if (strpos(strtolower(XOOPS_VERSION), 'legacy') === false) {
582 582
             $xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
583
-            if ((int)substr($xv, 4, 2) >= 17) {
583
+            if ((int) substr($xv, 4, 2) >= 17) {
584 584
                 return false;
585 585
             }
586 586
         }
@@ -643,25 +643,25 @@  discard block
 block discarded – undo
643 643
         }
644 644
         $ext  = basename($fileName);
645 645
         $ext  = explode('.', $ext);
646
-        $ext  = '.' . $ext[count($ext) - 1];
646
+        $ext  = '.'.$ext[count($ext) - 1];
647 647
         $true = true;
648 648
         while ($true) {
649 649
             $ipbits = explode('.', $_SERVER['REMOTE_ADDR']);
650 650
             list($usec, $sec) = explode(' ', microtime());
651
-            $usec = (integer)($usec * 65536);
652
-            $sec  = ((integer)$sec) & 0xFFFF;
651
+            $usec = (integer) ($usec * 65536);
652
+            $sec  = ((integer) $sec)&0xFFFF;
653 653
 
654 654
             if ($trimName) {
655
-                $uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
655
+                $uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24)|($ipbits[1] << 16)|($ipbits[2] << 8)|$ipbits[3], $sec, $usec);
656 656
             } else {
657
-                $uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
657
+                $uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24)|($ipbits[1] << 16)|($ipbits[2] << 8)|$ipbits[3], $sec, $usec);
658 658
             }
659
-            if (!file_exists($workingfolder . $uid . $ext)) {
659
+            if (!file_exists($workingfolder.$uid.$ext)) {
660 660
                 $true = false;
661 661
             }
662 662
         }
663 663
 
664
-        return $uid . $ext;
664
+        return $uid.$ext;
665 665
     }
666 666
 
667 667
     /**
@@ -676,135 +676,135 @@  discard block
 block discarded – undo
676 676
         $chaine = html_entity_decode($chaine);
677 677
 
678 678
         for ($i = 0; $i <= 255; ++$i) {
679
-            $search[]  = '&#' . $i . ';';
679
+            $search[]  = '&#'.$i.';';
680 680
             $replace[] = chr($i);
681 681
         }
682
-        $replace[]='...'; $search[]='…';
683
-        $replace[]="'"; $search[]='‘';
684
-        $replace[]="'"; $search[]= '’';
685
-        $replace[]='-'; $search[] = '&bull;';   // $replace[] = '•';
686
-        $replace[]='—'; $search[]='&mdash;';
687
-        $replace[]='-'; $search[]='&ndash;';
688
-        $replace[]='-'; $search[]='&shy;';
689
-        $replace[]='"'; $search[]='&quot;';
690
-        $replace[]='&'; $search[]='&amp;';
691
-        $replace[]='ˆ'; $search[]='&circ;';
692
-        $replace[]='¡'; $search[]='&iexcl;';
693
-        $replace[]='¦'; $search[]='&brvbar;';
694
-        $replace[]='¨'; $search[]='&uml;';
695
-        $replace[]='¯'; $search[]='&macr;';
696
-        $replace[]='´'; $search[]='&acute;';
697
-        $replace[]='¸'; $search[]='&cedil;';
698
-        $replace[]='¿'; $search[]='&iquest;';
699
-        $replace[]='˜'; $search[]='&tilde;';
700
-        $replace[]="'"; $search[]='&lsquo;';    // $replace[]='‘';
701
-        $replace[]="'"; $search[]='&rsquo;';    // $replace[]='’';
702
-        $replace[]='‚'; $search[]='&sbquo;';
703
-        $replace[]="'"; $search[]='&ldquo;';    // $replace[]='“';
704
-        $replace[]="'"; $search[]='&rdquo;';    // $replace[]='”';
705
-        $replace[]='„'; $search[]='&bdquo;';
706
-        $replace[]='‹'; $search[]='&lsaquo;';
707
-        $replace[]='›'; $search[]='&rsaquo;';
708
-        $replace[]='<'; $search[]='&lt;';
709
-        $replace[]='>'; $search[]='&gt;';
710
-        $replace[]='±'; $search[]='&plusmn;';
711
-        $replace[]='«'; $search[]='&laquo;';
712
-        $replace[]='»'; $search[]='&raquo;';
713
-        $replace[]='×'; $search[]='&times;';
714
-        $replace[]='÷'; $search[]='&divide;';
715
-        $replace[]='¢'; $search[]='&cent;';
716
-        $replace[]='£'; $search[]='&pound;';
717
-        $replace[]='¤'; $search[]='&curren;';
718
-        $replace[]='¥'; $search[]='&yen;';
719
-        $replace[]='§'; $search[]='&sect;';
720
-        $replace[]='©'; $search[]='&copy;';
721
-        $replace[]='¬'; $search[]='&not;';
722
-        $replace[]='®'; $search[]='&reg;';
723
-        $replace[]='°'; $search[]='&deg;';
724
-        $replace[]='µ'; $search[]='&micro;';
725
-        $replace[]='¶'; $search[]='&para;';
726
-        $replace[]='·'; $search[]='&middot;';
727
-        $replace[]='†'; $search[]='&dagger;';
728
-        $replace[]='‡'; $search[]='&Dagger;';
729
-        $replace[]='‰'; $search[]='&permil;';
730
-        $replace[]='Euro'; $search[]='&euro;';      // $replace[]='€'
731
-        $replace[]='¼'; $search[]='&frac14;';
732
-        $replace[]='½'; $search[]='&frac12;';
733
-        $replace[]='¾'; $search[]='&frac34;';
734
-        $replace[]='¹'; $search[]='&sup1;';
735
-        $replace[]='²'; $search[]='&sup2;';
736
-        $replace[]='³'; $search[]='&sup3;';
737
-        $replace[]='á'; $search[]='&aacute;';
738
-        $replace[]='Á'; $search[]='&Aacute;';
739
-        $replace[]='â'; $search[]='&acirc;';
740
-        $replace[]='Â'; $search[]='&Acirc;';
741
-        $replace[]='à'; $search[]='&agrave;';
742
-        $replace[]='À'; $search[]='&Agrave;';
743
-        $replace[]='å'; $search[]='&aring;';
744
-        $replace[]='Å'; $search[]='&Aring;';
745
-        $replace[]='ã'; $search[]='&atilde;';
746
-        $replace[]='Ã'; $search[]='&Atilde;';
747
-        $replace[]='ä'; $search[]='&auml;';
748
-        $replace[]='Ä'; $search[]='&Auml;';
749
-        $replace[]='ª'; $search[]='&ordf;';
750
-        $replace[]='æ'; $search[]='&aelig;';
751
-        $replace[]='Æ'; $search[]='&AElig;';
752
-        $replace[]='ç'; $search[]='&ccedil;';
753
-        $replace[]='Ç'; $search[]='&Ccedil;';
754
-        $replace[]='ð'; $search[]='&eth;';
755
-        $replace[]='Ð'; $search[]='&ETH;';
756
-        $replace[]='é'; $search[]='&eacute;';
757
-        $replace[]='É'; $search[]='&Eacute;';
758
-        $replace[]='ê'; $search[]='&ecirc;';
759
-        $replace[]='Ê'; $search[]='&Ecirc;';
760
-        $replace[]='è'; $search[]='&egrave;';
761
-        $replace[]='È'; $search[]='&Egrave;';
762
-        $replace[]='ë'; $search[]='&euml;';
763
-        $replace[]='Ë'; $search[]='&Euml;';
764
-        $replace[]='ƒ'; $search[]='&fnof;';
765
-        $replace[]='í'; $search[]='&iacute;';
766
-        $replace[]='Í'; $search[]='&Iacute;';
767
-        $replace[]='î'; $search[]='&icirc;';
768
-        $replace[]='Î'; $search[]='&Icirc;';
769
-        $replace[]='ì'; $search[]='&igrave;';
770
-        $replace[]='Ì'; $search[]='&Igrave;';
771
-        $replace[]='ï'; $search[]='&iuml;';
772
-        $replace[]='Ï'; $search[]='&Iuml;';
773
-        $replace[]='ñ'; $search[]='&ntilde;';
774
-        $replace[]='Ñ'; $search[]='&Ntilde;';
775
-        $replace[]='ó'; $search[]='&oacute;';
776
-        $replace[]='Ó'; $search[]='&Oacute;';
777
-        $replace[]='ô'; $search[]='&ocirc;';
778
-        $replace[]='Ô'; $search[]='&Ocirc;';
779
-        $replace[]='ò'; $search[]='&ograve;';
780
-        $replace[]='Ò'; $search[]='&Ograve;';
781
-        $replace[]='º'; $search[]='&ordm;';
782
-        $replace[]='ø'; $search[]='&oslash;';
783
-        $replace[]='Ø'; $search[]='&Oslash;';
784
-        $replace[]='õ'; $search[]='&otilde;';
785
-        $replace[]='Õ'; $search[]='&Otilde;';
786
-        $replace[]='ö'; $search[]='&ouml;';
787
-        $replace[]='Ö'; $search[]='&Ouml;';
788
-        $replace[]='œ'; $search[]='&oelig;';
789
-        $replace[]='Œ'; $search[]='&OElig;';
790
-        $replace[]='š'; $search[]='&scaron;';
791
-        $replace[]='Š'; $search[]='&Scaron;';
792
-        $replace[]='ß'; $search[]='&szlig;';
793
-        $replace[]='þ'; $search[]='&thorn;';
794
-        $replace[]='Þ'; $search[]='&THORN;';
795
-        $replace[]='ú'; $search[]='&uacute;';
796
-        $replace[]='Ú'; $search[]='&Uacute;';
797
-        $replace[]='û'; $search[]='&ucirc;';
798
-        $replace[]='Û'; $search[]='&Ucirc;';
799
-        $replace[]='ù'; $search[]='&ugrave;';
800
-        $replace[]='Ù'; $search[]='&Ugrave;';
801
-        $replace[]='ü'; $search[]='&uuml;';
802
-        $replace[]='Ü'; $search[]='&Uuml;';
803
-        $replace[]='ý'; $search[]='&yacute;';
804
-        $replace[]='Ý'; $search[]='&Yacute;';
805
-        $replace[]='ÿ'; $search[]='&yuml;';
806
-        $replace[]='Ÿ'; $search[]='&Yuml;';
807
-        $chaine    = str_replace($search, $replace, $chaine);
682
+        $replace[] = '...'; $search[] = '…';
683
+        $replace[] = "'"; $search[] = '‘';
684
+        $replace[] = "'"; $search[] = '’';
685
+        $replace[] = '-'; $search[] = '&bull;'; // $replace[] = '•';
686
+        $replace[] = '—'; $search[] = '&mdash;';
687
+        $replace[] = '-'; $search[] = '&ndash;';
688
+        $replace[] = '-'; $search[] = '&shy;';
689
+        $replace[] = '"'; $search[] = '&quot;';
690
+        $replace[] = '&'; $search[] = '&amp;';
691
+        $replace[] = 'ˆ'; $search[] = '&circ;';
692
+        $replace[] = '¡'; $search[] = '&iexcl;';
693
+        $replace[] = '¦'; $search[] = '&brvbar;';
694
+        $replace[] = '¨'; $search[] = '&uml;';
695
+        $replace[] = '¯'; $search[] = '&macr;';
696
+        $replace[] = '´'; $search[] = '&acute;';
697
+        $replace[] = '¸'; $search[] = '&cedil;';
698
+        $replace[] = '¿'; $search[] = '&iquest;';
699
+        $replace[] = '˜'; $search[] = '&tilde;';
700
+        $replace[] = "'"; $search[] = '&lsquo;'; // $replace[]='‘';
701
+        $replace[] = "'"; $search[] = '&rsquo;'; // $replace[]='’';
702
+        $replace[] = '‚'; $search[] = '&sbquo;';
703
+        $replace[] = "'"; $search[] = '&ldquo;'; // $replace[]='“';
704
+        $replace[] = "'"; $search[] = '&rdquo;'; // $replace[]='”';
705
+        $replace[] = '„'; $search[] = '&bdquo;';
706
+        $replace[] = '‹'; $search[] = '&lsaquo;';
707
+        $replace[] = '›'; $search[] = '&rsaquo;';
708
+        $replace[] = '<'; $search[] = '&lt;';
709
+        $replace[] = '>'; $search[] = '&gt;';
710
+        $replace[] = '±'; $search[] = '&plusmn;';
711
+        $replace[] = '«'; $search[] = '&laquo;';
712
+        $replace[] = '»'; $search[] = '&raquo;';
713
+        $replace[] = '×'; $search[] = '&times;';
714
+        $replace[] = '÷'; $search[] = '&divide;';
715
+        $replace[] = '¢'; $search[] = '&cent;';
716
+        $replace[] = '£'; $search[] = '&pound;';
717
+        $replace[] = '¤'; $search[] = '&curren;';
718
+        $replace[] = '¥'; $search[] = '&yen;';
719
+        $replace[] = '§'; $search[] = '&sect;';
720
+        $replace[] = '©'; $search[] = '&copy;';
721
+        $replace[] = '¬'; $search[] = '&not;';
722
+        $replace[] = '®'; $search[] = '&reg;';
723
+        $replace[] = '°'; $search[] = '&deg;';
724
+        $replace[] = 'µ'; $search[] = '&micro;';
725
+        $replace[] = '¶'; $search[] = '&para;';
726
+        $replace[] = '·'; $search[] = '&middot;';
727
+        $replace[] = '†'; $search[] = '&dagger;';
728
+        $replace[] = '‡'; $search[] = '&Dagger;';
729
+        $replace[] = '‰'; $search[] = '&permil;';
730
+        $replace[] = 'Euro'; $search[] = '&euro;'; // $replace[]='€'
731
+        $replace[] = '¼'; $search[] = '&frac14;';
732
+        $replace[] = '½'; $search[] = '&frac12;';
733
+        $replace[] = '¾'; $search[] = '&frac34;';
734
+        $replace[] = '¹'; $search[] = '&sup1;';
735
+        $replace[] = '²'; $search[] = '&sup2;';
736
+        $replace[] = '³'; $search[] = '&sup3;';
737
+        $replace[] = 'á'; $search[] = '&aacute;';
738
+        $replace[] = 'Á'; $search[] = '&Aacute;';
739
+        $replace[] = 'â'; $search[] = '&acirc;';
740
+        $replace[] = 'Â'; $search[] = '&Acirc;';
741
+        $replace[] = 'à'; $search[] = '&agrave;';
742
+        $replace[] = 'À'; $search[] = '&Agrave;';
743
+        $replace[] = 'å'; $search[] = '&aring;';
744
+        $replace[] = 'Å'; $search[] = '&Aring;';
745
+        $replace[] = 'ã'; $search[] = '&atilde;';
746
+        $replace[] = 'Ã'; $search[] = '&Atilde;';
747
+        $replace[] = 'ä'; $search[] = '&auml;';
748
+        $replace[] = 'Ä'; $search[] = '&Auml;';
749
+        $replace[] = 'ª'; $search[] = '&ordf;';
750
+        $replace[] = 'æ'; $search[] = '&aelig;';
751
+        $replace[] = 'Æ'; $search[] = '&AElig;';
752
+        $replace[] = 'ç'; $search[] = '&ccedil;';
753
+        $replace[] = 'Ç'; $search[] = '&Ccedil;';
754
+        $replace[] = 'ð'; $search[] = '&eth;';
755
+        $replace[] = 'Ð'; $search[] = '&ETH;';
756
+        $replace[] = 'é'; $search[] = '&eacute;';
757
+        $replace[] = 'É'; $search[] = '&Eacute;';
758
+        $replace[] = 'ê'; $search[] = '&ecirc;';
759
+        $replace[] = 'Ê'; $search[] = '&Ecirc;';
760
+        $replace[] = 'è'; $search[] = '&egrave;';
761
+        $replace[] = 'È'; $search[] = '&Egrave;';
762
+        $replace[] = 'ë'; $search[] = '&euml;';
763
+        $replace[] = 'Ë'; $search[] = '&Euml;';
764
+        $replace[] = 'ƒ'; $search[] = '&fnof;';
765
+        $replace[] = 'í'; $search[] = '&iacute;';
766
+        $replace[] = 'Í'; $search[] = '&Iacute;';
767
+        $replace[] = 'î'; $search[] = '&icirc;';
768
+        $replace[] = 'Î'; $search[] = '&Icirc;';
769
+        $replace[] = 'ì'; $search[] = '&igrave;';
770
+        $replace[] = 'Ì'; $search[] = '&Igrave;';
771
+        $replace[] = 'ï'; $search[] = '&iuml;';
772
+        $replace[] = 'Ï'; $search[] = '&Iuml;';
773
+        $replace[] = 'ñ'; $search[] = '&ntilde;';
774
+        $replace[] = 'Ñ'; $search[] = '&Ntilde;';
775
+        $replace[] = 'ó'; $search[] = '&oacute;';
776
+        $replace[] = 'Ó'; $search[] = '&Oacute;';
777
+        $replace[] = 'ô'; $search[] = '&ocirc;';
778
+        $replace[] = 'Ô'; $search[] = '&Ocirc;';
779
+        $replace[] = 'ò'; $search[] = '&ograve;';
780
+        $replace[] = 'Ò'; $search[] = '&Ograve;';
781
+        $replace[] = 'º'; $search[] = '&ordm;';
782
+        $replace[] = 'ø'; $search[] = '&oslash;';
783
+        $replace[] = 'Ø'; $search[] = '&Oslash;';
784
+        $replace[] = 'õ'; $search[] = '&otilde;';
785
+        $replace[] = 'Õ'; $search[] = '&Otilde;';
786
+        $replace[] = 'ö'; $search[] = '&ouml;';
787
+        $replace[] = 'Ö'; $search[] = '&Ouml;';
788
+        $replace[] = 'œ'; $search[] = '&oelig;';
789
+        $replace[] = 'Œ'; $search[] = '&OElig;';
790
+        $replace[] = 'š'; $search[] = '&scaron;';
791
+        $replace[] = 'Š'; $search[] = '&Scaron;';
792
+        $replace[] = 'ß'; $search[] = '&szlig;';
793
+        $replace[] = 'þ'; $search[] = '&thorn;';
794
+        $replace[] = 'Þ'; $search[] = '&THORN;';
795
+        $replace[] = 'ú'; $search[] = '&uacute;';
796
+        $replace[] = 'Ú'; $search[] = '&Uacute;';
797
+        $replace[] = 'û'; $search[] = '&ucirc;';
798
+        $replace[] = 'Û'; $search[] = '&Ucirc;';
799
+        $replace[] = 'ù'; $search[] = '&ugrave;';
800
+        $replace[] = 'Ù'; $search[] = '&Ugrave;';
801
+        $replace[] = 'ü'; $search[] = '&uuml;';
802
+        $replace[] = 'Ü'; $search[] = '&Uuml;';
803
+        $replace[] = 'ý'; $search[] = '&yacute;';
804
+        $replace[] = 'Ý'; $search[] = '&Yacute;';
805
+        $replace[] = 'ÿ'; $search[] = '&yuml;';
806
+        $replace[] = 'Ÿ'; $search[] = '&Yuml;';
807
+        $chaine = str_replace($search, $replace, $chaine);
808 808
 
809 809
         return $chaine;
810 810
     }
@@ -821,11 +821,11 @@  discard block
 block discarded – undo
821 821
     {
822 822
         $s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛÜŸÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
823 823
         $r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
824
-        $content = self::unhtml($content);    // First, remove html entities
824
+        $content = self::unhtml($content); // First, remove html entities
825 825
         $content = strtr($content, $s, $r);
826 826
         $content = strip_tags($content);
827 827
         $content = strtolower($content);
828
-        $content = htmlentities($content);    // TODO: Vérifier
828
+        $content = htmlentities($content); // TODO: Vérifier
829 829
         $content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
830 830
         $content = html_entity_decode($content);
831 831
         $content = eregi_replace('quot', ' ', $content);
@@ -840,7 +840,7 @@  discard block
 block discarded – undo
840 840
         $keywords = '';
841 841
         foreach ($words as $word) {
842 842
             if (strlen($word) >= $urw) {
843
-                $keywords .= '-' . trim($word);
843
+                $keywords .= '-'.trim($word);
844 844
             }
845 845
         }
846 846
         if (!$keywords) {
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
             $limit = $_SESSION['references_keywords_limit'];
876 876
         } else {
877 877
             $config_handler                        = xoops_getHandler('config');
878
-            $xoopsConfigSearch                     =& $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
878
+            $xoopsConfigSearch                     = & $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
879 879
             $limit                                 = $xoopsConfigSearch['keyword_min'];
880 880
             $_SESSION['references_keywords_limit'] = $limit;
881 881
         }
@@ -923,7 +923,7 @@  discard block
 block discarded – undo
923 923
             if (!isset($config_handler) || !is_object($config_handler)) {
924 924
                 $config_handler = xoops_getHandler('config');
925 925
             }
926
-            $xoopsConfigMetaFooter =& $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
926
+            $xoopsConfigMetaFooter = & $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
927 927
             if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
928 928
                 return $xoopsConfigMetaFooter['meta_keywords'];
929 929
             } else {
@@ -945,10 +945,10 @@  discard block
 block discarded – undo
945 945
      */
946 946
     public static function uploadFile($indice, $dstpath = XOOPS_UPLOAD_PATH, $mimeTypes = null, $uploadMaxSize = null, $maxWidth = null, $maxHeight = null)
947 947
     {
948
-        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
948
+        require_once XOOPS_ROOT_PATH.'/class/uploader.php';
949 949
         global $destname;
950 950
         if (isset($_POST['xoops_upload_file'])) {
951
-            require_once XOOPS_ROOT_PATH . '/class/uploader.php';
951
+            require_once XOOPS_ROOT_PATH.'/class/uploader.php';
952 952
             $fldname = '';
953 953
             $fldname = $_FILES[$_POST['xoops_upload_file'][$indice]];
954 954
             $fldname = get_magic_quotes_gpc() ? stripslashes($fldname['name']) : $fldname['name'];
@@ -972,7 +972,7 @@  discard block
 block discarded – undo
972 972
                     if ($uploader->upload()) {
973 973
                         return true;
974 974
                     } else {
975
-                        return _ERRORS . ' ' . htmlentities($uploader->getErrors());
975
+                        return _ERRORS.' '.htmlentities($uploader->getErrors());
976 976
                     }
977 977
                 } else {
978 978
                     return htmlentities($uploader->getErrors());
@@ -1055,9 +1055,9 @@  discard block
 block discarded – undo
1055 1055
         $workingBreadcrumb = array();
1056 1056
         if (is_array($path)) {
1057 1057
             $moduleName          = self::getModuleName();
1058
-            $workingBreadcrumb[] = "<a href='" . REFERENCES_URL . "' title='" . self::makeHrefTitle($moduleName) . "'>" . $moduleName . '</a>';
1058
+            $workingBreadcrumb[] = "<a href='".REFERENCES_URL."' title='".self::makeHrefTitle($moduleName)."'>".$moduleName.'</a>';
1059 1059
             foreach ($path as $url => $title) {
1060
-                $workingBreadcrumb[] = "<a href='" . $url . "'>" . $title . '</a>';
1060
+                $workingBreadcrumb[] = "<a href='".$url."'>".$title.'</a>';
1061 1061
             }
1062 1062
             $cnt = count($workingBreadcrumb);
1063 1063
             for ($i = 0; $i < $cnt; ++$i) {
@@ -1096,7 +1096,7 @@  discard block
 block discarded – undo
1096 1096
 
1097 1097
             $complete_tags = array_reverse($complete_tags);
1098 1098
             for ($i = 0; $i < count($complete_tags); ++$i) {
1099
-                $string .= '</' . $complete_tags[$i] . '>';
1099
+                $string .= '</'.$complete_tags[$i].'>';
1100 1100
             }
1101 1101
         }
1102 1102
 
@@ -1117,7 +1117,7 @@  discard block
 block discarded – undo
1117 1117
                 $string = self::close_tags($string);
1118 1118
             }
1119 1119
 
1120
-            return $string . $etc;
1120
+            return $string.$etc;
1121 1121
         } else {
1122 1122
             return $string;
1123 1123
         }
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
     public static function getMimeType($filename)
1150 1150
     {
1151 1151
         if (function_exists('finfo_open')) {
1152
-            $pathToMagic = REFERENCES_PATH . 'mime/magic';
1152
+            $pathToMagic = REFERENCES_PATH.'mime/magic';
1153 1153
             $finfo       = new finfo(FILEINFO_MIME, $pathToMagic);
1154 1154
             $mimetype    = $finfo->file($filename);
1155 1155
             finfo_close($finfo);
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
             sort($xoopsUsersIDs);
1180 1180
             if (count($xoopsUsersIDs) > 0) {
1181 1181
                 $member_handler = xoops_getHandler('user');
1182
-                $criteria       = new Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
1182
+                $criteria       = new Criteria('uid', '('.implode(',', $xoopsUsersIDs).')', 'IN');
1183 1183
                 $criteria->setSort('uid');
1184 1184
                 $users = $member_handler->getObjects($criteria, true);
1185 1185
             }
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
         } else {
1218 1218
             if ($uid > 0) {
1219 1219
                 $member_handler = xoops_getHandler('member');
1220
-                $buffer[$uid]   = $member_handler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
1220
+                $buffer[$uid]   = $member_handler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1221 1221
             } else {
1222 1222
                 $buffer[$uid] = array(XOOPS_GROUP_ANONYMOUS);
1223 1223
             }
@@ -1244,7 +1244,7 @@  discard block
 block discarded – undo
1244 1244
             $retval = $buffer[$group];
1245 1245
         } else {
1246 1246
             $member_handler = xoops_getHandler('member');
1247
-            $groups         = $member_handler->getGroupsByUser($uid, false);    // Renvoie un tableau d'ID (de groupes)
1247
+            $groups         = $member_handler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1248 1248
             $retval         = in_array($group, $groups);
1249 1249
             $buffer[$group] = $retval;
1250 1250
         }
@@ -1284,7 +1284,7 @@  discard block
 block discarded – undo
1284 1284
         static $cache = -1;
1285 1285
         if ($cache == -1) {
1286 1286
             global $xoopsDB;
1287
-            $sql    = 'SELECT COUNT(*) FROM ' . $xoopsDB->prefix('groups');
1287
+            $sql    = 'SELECT COUNT(*) FROM '.$xoopsDB->prefix('groups');
1288 1288
             $result = $xoopsDB->query($sql);
1289 1289
             if (!$result) {
1290 1290
                 return false;
@@ -1305,7 +1305,7 @@  discard block
 block discarded – undo
1305 1305
     {
1306 1306
         if (!is_dir($folder)) {
1307 1307
             mkdir($folder, 0777);
1308
-            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
1308
+            file_put_contents($folder.'/index.html', '<script>history.go(-1);</script>');
1309 1309
         } else {
1310 1310
             if (!is_writable($folder)) {
1311 1311
                 chmod($folder, 0777);
@@ -1326,10 +1326,10 @@  discard block
 block discarded – undo
1326 1326
         if (strstr($languageFile, $defaultExtension) === false) {
1327 1327
             $languageFile .= $defaultExtension;
1328 1328
         }
1329
-        if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile)) {
1330
-            require_once $root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile;
1329
+        if (file_exists($root.'language'.DIRECTORY_SEPARATOR.$xoopsConfig['language'].DIRECTORY_SEPARATOR.$languageFile)) {
1330
+            require_once $root.'language'.DIRECTORY_SEPARATOR.$xoopsConfig['language'].DIRECTORY_SEPARATOR.$languageFile;
1331 1331
         } else {    // Fallback
1332
-            require_once $root . 'language' . DIRECTORY_SEPARATOR . 'english' . DIRECTORY_SEPARATOR . $languageFile;
1332
+            require_once $root.'language'.DIRECTORY_SEPARATOR.'english'.DIRECTORY_SEPARATOR.$languageFile;
1333 1333
         }
1334 1334
     }
1335 1335
 
@@ -1367,10 +1367,10 @@  discard block
 block discarded – undo
1367 1367
                 $left = $top = 0;
1368 1368
                 if (is_array($pictureDimensions)) {
1369 1369
                     if ($pictureWidth > $param_width) {
1370
-                        $left = (int)(($pictureWidth / 2) - ($param_width / 2));
1370
+                        $left = (int) (($pictureWidth / 2) - ($param_width / 2));
1371 1371
                     }
1372 1372
                     if ($pictureHeight > $param_height) {
1373
-                        $top = (int)(($pictureHeight / 2) - ($param_height / 2));
1373
+                        $top = (int) (($pictureHeight / 2) - ($param_height / 2));
1374 1374
                     }
1375 1375
                 }
1376 1376
                 $result = $img->crop($left, $top, $param_width, $param_height);
@@ -1410,7 +1410,7 @@  discard block
 block discarded – undo
1410 1410
                     $selected = " selected = 'selected'";
1411 1411
                 }
1412 1412
             }
1413
-            $ret[] = '<option value=0' . $selected . '>---</option>';
1413
+            $ret[] = '<option value=0'.$selected.'>---</option>';
1414 1414
         }
1415 1415
 
1416 1416
         foreach ($array as $index => $label) {
@@ -1424,7 +1424,7 @@  discard block
 block discarded – undo
1424 1424
                     $selected = " selected = 'selected'";
1425 1425
                 }
1426 1426
             }
1427
-            $ret[] = "<option value=\"" . $index . "\"" . $selected . '>' . $label . '</option>';
1427
+            $ret[] = "<option value=\"".$index."\"".$selected.'>'.$label.'</option>';
1428 1428
         }
1429 1429
 
1430 1430
         return implode("\n", $ret);
@@ -1446,14 +1446,14 @@  discard block
 block discarded – undo
1446 1446
     public static function htmlSelect($selectName, $array, $default, $withNull = true, $style = '', $multiple = false, $size = 1, $extra = '')
1447 1447
     {
1448 1448
         $ret = '';
1449
-        $ret .= "<select name='" . $selectName . "' id='" . $selectName . "'";
1449
+        $ret .= "<select name='".$selectName."' id='".$selectName."'";
1450 1450
         if (xoops_trim($style) != '') {
1451
-            $ret .= " style='" . $style . "' ";
1451
+            $ret .= " style='".$style."' ";
1452 1452
         }
1453 1453
         if (xoops_trim($multiple) != '') {
1454
-            $ret .= " multiple = 'multiple' size='" . $size . "' ";
1454
+            $ret .= " multiple = 'multiple' size='".$size."' ";
1455 1455
         }
1456
-        $ret .= $extra . ">\n";
1456
+        $ret .= $extra.">\n";
1457 1457
         $ret .= self::htmlSelectOptions($array, $default, $withNull);
1458 1458
         $ret .= "</select>\n";
1459 1459
 
@@ -1528,16 +1528,16 @@  discard block
 block discarded – undo
1528 1528
     {
1529 1529
         global $xoopsDB;
1530 1530
         define('REFERENCES_MAINTAIN', true);
1531
-        require self::MODULE_PATH . 'xoops_version.php';
1531
+        require self::MODULE_PATH.'xoops_version.php';
1532 1532
         $tables = array();
1533 1533
         foreach ($modversion['tables'] as $table) {
1534 1534
             $tables[] = $xoopsDB->prefix($table);
1535 1535
         }
1536 1536
         if (count($tables) > 0) {
1537 1537
             $list = implode(',', $tables);
1538
-            $xoopsDB->queryF('CHECK TABLE ' . $list);
1539
-            $xoopsDB->queryF('ANALYZE TABLE ' . $list);
1540
-            $xoopsDB->queryF('OPTIMIZE TABLE ' . $list);
1538
+            $xoopsDB->queryF('CHECK TABLE '.$list);
1539
+            $xoopsDB->queryF('ANALYZE TABLE '.$list);
1540
+            $xoopsDB->queryF('OPTIMIZE TABLE '.$list);
1541 1541
         }
1542 1542
         self::updateCache();
1543 1543
         $handlers = references_handler::getInstance();
Please login to merge, or discard this patch.
class/PersistableObjectHandler.php 2 patches
Indentation   +808 added lines, -808 removed lines patch added patch discarded remove patch
@@ -25,44 +25,44 @@  discard block
 block discarded – undo
25 25
 
26 26
 class references_Object extends XoopsObject
27 27
 {
28
-    public function toArray($format = 's')
29
-    {
30
-        $ret = array();
31
-        foreach ($this->vars as $k => $v) {
32
-            $ret[$k] = $this->getVar($k, $format);
33
-        }
34
-
35
-        return $ret;
36
-    }
37
-
38
-    // TODO: Rajouter une méthode intsert() et delete()
39
-
40
-    /**
41
-     * Permet de valoriser un champ de la table comme si c'était une propriété de la classe
42
-     *
43
-     * @example $enregistrement->nom_du_champ = 'ma chaine'
44
-     *
45
-     * @param string $key   Le nom du champ à traiter
46
-     * @param mixed  $value La valeur à lui attribuer
47
-     * @return void
48
-     */
49
-    public function __set($key, $value)
50
-    {
51
-        return $this->setVar($key, $value);
52
-    }
53
-
54
-    /**
55
-     * Permet d'accéder aux champs de la table comme à des propriétés de la classe
56
-     *
57
-     * @example echo $enregistrement->nom_du_champ;
58
-     *
59
-     * @param string $key Le nom du champ que l'on souhaite récupérer
60
-     * @return mixed
61
-     */
62
-    public function __get($key)
63
-    {
64
-        return $this->getVar($key);
65
-    }
28
+	public function toArray($format = 's')
29
+	{
30
+		$ret = array();
31
+		foreach ($this->vars as $k => $v) {
32
+			$ret[$k] = $this->getVar($k, $format);
33
+		}
34
+
35
+		return $ret;
36
+	}
37
+
38
+	// TODO: Rajouter une méthode intsert() et delete()
39
+
40
+	/**
41
+	 * Permet de valoriser un champ de la table comme si c'était une propriété de la classe
42
+	 *
43
+	 * @example $enregistrement->nom_du_champ = 'ma chaine'
44
+	 *
45
+	 * @param string $key   Le nom du champ à traiter
46
+	 * @param mixed  $value La valeur à lui attribuer
47
+	 * @return void
48
+	 */
49
+	public function __set($key, $value)
50
+	{
51
+		return $this->setVar($key, $value);
52
+	}
53
+
54
+	/**
55
+	 * Permet d'accéder aux champs de la table comme à des propriétés de la classe
56
+	 *
57
+	 * @example echo $enregistrement->nom_du_champ;
58
+	 *
59
+	 * @param string $key Le nom du champ que l'on souhaite récupérer
60
+	 * @return mixed
61
+	 */
62
+	public function __get($key)
63
+	{
64
+		return $this->getVar($key);
65
+	}
66 66
 }
67 67
 
68 68
 /**
@@ -73,778 +73,778 @@  discard block
 block discarded – undo
73 73
  */
74 74
 class references_XoopsPersistableObjectHandler extends XoopsObjectHandler
75 75
 {
76
-    /**#@+
76
+	/**#@+
77 77
      * Information about the class, the handler is managing
78 78
      *
79 79
      * @var string
80 80
      */
81
-    public    $table;
82
-    public    $keyName;
83
-    public    $className;
84
-    public    $identifierName;
85
-    protected $cacheOptions = array();
86
-    /**#@-*/
87
-
88
-    /**
89
-     * Constructor - called from child classes
90
-     * @param object $db           {@link XoopsDatabase} object
91
-     * @param string $tablename    Name of database table
92
-     * @param string $classname    Name of Class, this handler is managing
93
-     * @param string $keyname      Name of the property, holding the key
94
-     * @param string $idenfierName Name of the property, holding the label
95
-     * @param array  $cacheOptions Optional, options for the cache
96
-     *
97
-     */
98
-    public function __construct(&$db, $tablename, $classname, $keyname, $idenfierName = '', $cacheOptions = null)
99
-    {
100
-        parent::__construct($db);
101
-        $this->table     = $db->prefix($tablename);
102
-        $this->keyName   = $keyname;
103
-        $this->className = $classname;
104
-        if (trim($idenfierName) != '') {
105
-            $this->identifierName = $idenfierName;
106
-        }
107
-        // To diable cache, add this line after the first one : 'caching' => false,
108
-        if (is_null($cacheOptions)) {
109
-            $this->setCachingOptions(array('cacheDir' => REFERENCES_CACHE_PATH, 'lifeTime' => null, 'automaticSerialization' => true, 'fileNameProtection' => false));
110
-        } else {
111
-            $this->setCachingOptions($cacheOptions);
112
-        }
113
-    }
114
-
115
-    public function setCachingOptions($cacheOptions)
116
-    {
117
-        $this->cacheOptions = $cacheOptions;
118
-    }
119
-
120
-    /**
121
-     * Generates a unique ID for a Sql Query
122
-     *
123
-     * @param  string  $query The SQL query for which we want a unidque ID
124
-     * @param  integer $start Which record to start at
125
-     * @param  integer $limit Max number of objects to fetch
126
-     * @return string  An MD5 of the query
127
-     */
128
-    protected function _getIdForCache($query, $start, $limit)
129
-    {
130
-        $id = md5($query . '-' . (string)$start . '-' . (string)$limit);
131
-
132
-        return $id;
133
-    }
134
-
135
-    /**
136
-     * create a new object
137
-     *
138
-     * @param bool $isNew Flag the new objects as "new"?
139
-     *
140
-     * @return object
141
-     */
142
-    public function &create($isNew = true)
143
-    {
144
-        $obj = new $this->className();
145
-        if ($isNew === true) {
146
-            $obj->setNew();
147
-        }
148
-
149
-        return $obj;
150
-    }
151
-
152
-    /**
153
-     * retrieve an object
154
-     *
155
-     * @param  mixed $id        ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
156
-     * @param  bool  $as_object whether to return an object or an array
157
-     * @return mixed reference to the object, FALSE if failed
158
-     */
159
-    public function &get($id, $as_object = true)
160
-    {
161
-        if (is_array($this->keyName)) {
162
-            $criteria = new CriteriaCompo();
163
-            $vnb      = count($this->keyName);
164
-            for ($i = 0; $i < $vnb; ++$i) {
165
-                $criteria->add(new Criteria($this->keyName[$i], (int)$id[$i]));
166
-            }
167
-        } else {
168
-            $criteria = new Criteria($this->keyName, (int)$id);
169
-        }
170
-        $criteria->setLimit(1);
171
-        $obj_array = $this->getObjects($criteria, false, $as_object);
172
-        if (count($obj_array) != 1) {
173
-            $ret = null;
174
-        } else {
175
-            $ret =& $obj_array[0];
176
-        }
177
-
178
-        return $ret;
179
-    }
180
-
181
-    /**
182
-     * retrieve objects from the database
183
-     *
184
-     * @param null|CriteriaElement $criteria  {@link CriteriaElement} conditions to be met
185
-     * @param bool                 $id_as_key use the ID as key for the array?
186
-     * @param bool                 $as_object return an array of objects?
187
-     *
188
-     * @param string               $fields
189
-     * @param bool                 $autoSort
190
-     * @return array
191
-     */
192
-    public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false, $as_object = true, $fields = '*', $autoSort = true)
193
-    {
194
-        require_once __DIR__ . '/lite.php';
195
-        $ret   = array();
196
-        $limit = $start = 0;
197
-        $sql   = 'SELECT ' . $fields . ' FROM ' . $this->table;
198
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
199
-            $sql .= ' ' . $criteria->renderWhere();
200
-            if ($criteria->groupby != '') {
201
-                $sql .= $criteria->getGroupby();
202
-            }
203
-            if ($criteria->getSort() != '') {
204
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
205
-            } elseif ($this->identifierName != '' && $autoSort) {
206
-                $sql .= ' ORDER BY ' . $this->identifierName;
207
-            }
208
-            $limit = $criteria->getLimit();
209
-            $start = $criteria->getStart();
210
-        }
211
-        $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
212
-        $id         = $this->_getIdForCache($sql, $start, $limit);
213
-        $cacheData  = $Cache_Lite->get($id);
214
-        if ($cacheData === false) {
215
-            $result = $this->db->query($sql, $limit, $start);
216
-            if (!$result) {
217
-                return $ret;
218
-            }
219
-            $ret = $this->convertResultSet($result, $id_as_key, $as_object, $fields);
220
-            $Cache_Lite->save($ret);
221
-
222
-            return $ret;
223
-        } else {
224
-            return $cacheData;
225
-        }
226
-    }
227
-
228
-    /**
229
-     * Convert a database resultset to a returnable array
230
-     *
231
-     * @param object  $result    database resultset
232
-     * @param boolean $id_as_key - should NOT be used with joint keys
233
-     * @param boolean $as_object
234
-     * @param string  $fields    Requested fields from the query
235
-     *
236
-     * @return array
237
-     */
238
-    protected function convertResultSet($result, $id_as_key = false, $as_object = true, $fields = '*')
239
-    {
240
-        $ret = array();
241
-        while ($myrow = $this->db->fetchArray($result)) {
242
-            $obj =& $this->create(false);
243
-            $obj->assignVars($myrow);
244
-            if (!$id_as_key) {
245
-                if ($as_object) {
246
-                    $ret[] =& $obj;
247
-                } else {
248
-                    $row     = array();
249
-                    $vars    = $obj->getVars();
250
-                    $tbl_tmp = array_keys($vars);
251
-                    foreach ($tbl_tmp as $i) {
252
-                        $row[$i] = $obj->getVar($i);
253
-                    }
254
-                    $ret[] = $row;
255
-                }
256
-            } else {
257
-                if ($as_object) {
258
-                    if ($fields === '*') {
259
-                        $ret[$myrow[$this->keyName]] =& $obj;
260
-                    } else {
261
-                        $ret[] =& $obj;
262
-                    }
263
-                } else {
264
-                    $row     = array();
265
-                    $vars    = $obj->getVars();
266
-                    $tbl_tmp = array_keys($vars);
267
-                    foreach ($tbl_tmp as $i) {
268
-                        $row[$i] = $obj->getVar($i);
269
-                    }
270
-                    $ret[$myrow[$this->keyName]] = $row;
271
-                }
272
-            }
273
-            unset($obj);
274
-        }
275
-
276
-        return $ret;
277
-    }
278
-
279
-    /**
280
-     * get IDs of objects matching a condition
281
-     *
282
-     * @param  object $criteria {@link CriteriaElement} to match
283
-     * @return array  of object IDs
284
-     */
285
-    public function getIds($criteria = null)
286
-    {
287
-        require_once __DIR__ . '/lite.php';
288
-        $limit = $start = 0;
289
-
290
-        $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
291
-        $sql        = 'SELECT ' . $this->keyName . ' FROM ' . $this->table;
292
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
293
-            $sql .= ' ' . $criteria->renderWhere();
294
-            if ($criteria->groupby != '') {
295
-                $sql .= $criteria->getGroupby();
296
-            }
297
-            if ($criteria->getSort() != '') {
298
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
299
-            } elseif ($this->identifierName != '') {
300
-                $sql .= ' ORDER BY ' . $this->identifierName;
301
-            }
302
-            $limit = $criteria->getLimit();
303
-            $start = $criteria->getStart();
304
-        }
305
-
306
-        $id        = $this->_getIdForCache($sql, $start, $limit);
307
-        $cacheData = $Cache_Lite->get($id);
308
-        if ($cacheData === false) {
309
-            $result = $this->db->query($sql, $limit, $start);
310
-            $ret    = array();
311
-            while ($myrow = $this->db->fetchArray($result)) {
312
-                $ret[] = $myrow[$this->keyName];
313
-            }
314
-            $Cache_Lite->save($ret);
315
-
316
-            return $ret;
317
-        } else {
318
-            return $cacheData;
319
-        }
320
-    }
321
-
322
-    /**
323
-     * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS
324
-     *
325
-     * @param object $criteria {@link CriteriaElement} conditions to be met
326
-     * @return array
327
-     */
328
-    public function getList($criteria = null)
329
-    {
330
-        require_once __DIR__ . '/lite.php';
331
-        $limit      = $start = 0;
332
-        $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
333
-
334
-        $ret = array();
335
-
336
-        $sql = 'SELECT ' . $this->keyName;
337
-        if (!empty($this->identifierName)) {
338
-            $sql .= ', ' . $this->identifierName;
339
-        }
340
-        $sql .= ' FROM ' . $this->table;
341
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
342
-            $sql .= ' ' . $criteria->renderWhere();
343
-            if ($criteria->groupby != '') {
344
-                $sql .= $criteria->getGroupby();
345
-            }
346
-            if ($criteria->getSort() != '') {
347
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
348
-            } elseif ($this->identifierName != '') {
349
-                $sql .= ' ORDER BY ' . $this->identifierName;
350
-            }
351
-            $limit = $criteria->getLimit();
352
-            $start = $criteria->getStart();
353
-        }
354
-
355
-        $id        = $this->_getIdForCache($sql, $start, $limit);
356
-        $cacheData = $Cache_Lite->get($id);
357
-        if ($cacheData === false) {
358
-            $result = $this->db->query($sql, $limit, $start);
359
-            if (!$result) {
360
-                $Cache_Lite->save($ret);
361
-
362
-                return $ret;
363
-            }
364
-
365
-            $myts = MyTextSanitizer::getInstance();
366
-            while ($myrow = $this->db->fetchArray($result)) {
367
-                //identifiers should be textboxes, so sanitize them like that
368
-                $ret[$myrow[$this->keyName]] = empty($this->identifierName) ? 1 : $myts->htmlSpecialChars($myrow[$this->identifierName]);
369
-            }
370
-            $Cache_Lite->save($ret);
371
-
372
-            return $ret;
373
-        } else {
374
-            return $cacheData;
375
-        }
376
-    }
377
-
378
-    /**
379
-     * Retourne des éléments selon leur ID
380
-     *
381
-     * @param array $ids Les ID des éléments à retrouver
382
-     * @param null  $additionnal
383
-     * @return array Tableau d'objets
384
-     */
385
-    public function getItemsFromIds($ids, $additionnal = null)
386
-    {
387
-        $ret = array();
388
-        if (is_array($ids) && count($ids) > 0) {
389
-            $criteria = new CriteriaCompo();
390
-            $criteria->add(new Criteria($this->keyName, '(' . implode(',', $ids) . ')', 'IN'));
391
-            if (!is_null($additionnal)) {
392
-                $criteria->add($additionnal);
393
-            }
394
-            $ret = $this->getObjects($criteria, true);
395
-        }
396
-
397
-        return $ret;
398
-    }
399
-
400
-    /**
401
-     * count objects matching a condition
402
-     *
403
-     * @param  object $criteria {@link CriteriaElement} to match
404
-     * @return int    count of objects
405
-     */
406
-    public function getCount($criteria = null)
407
-    {
408
-        $field   = '';
409
-        $groupby = false;
410
-        $limit   = $start = 0;
411
-        require_once __DIR__ . '/lite.php';
412
-
413
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
414
-            if ($criteria->groupby != '') {
415
-                $groupby = true;
416
-                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
417
-            }
418
-        }
419
-        $sql = 'SELECT ' . $field . 'COUNT(*) FROM ' . $this->table;
420
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
421
-            $sql .= ' ' . $criteria->renderWhere();
422
-            if ($criteria->groupby != '') {
423
-                $sql .= $criteria->getGroupby();
424
-            }
425
-            $limit = $criteria->getLimit();
426
-            $start = $criteria->getStart();
427
-        }
428
-        $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
429
-        $id         = $this->_getIdForCache($sql, $start, $limit);
430
-        $cacheData  = $Cache_Lite->get($id);
431
-        if ($cacheData === false) {
432
-            $result = $this->db->query($sql, $limit, $start);
433
-            if (!$result) {
434
-                $ret = 0;
435
-                $Cache_Lite->save($ret);
436
-
437
-                return $ret;
438
-            }
439
-            if ($groupby == false) {
440
-                list($count) = $this->db->fetchRow($result);
441
-                $Cache_Lite->save($count);
442
-
443
-                return $count;
444
-            } else {
445
-                $ret = array();
446
-                while (list($id, $count) = $this->db->fetchRow($result)) {
447
-                    $ret[$id] = $count;
448
-                }
449
-                $Cache_Lite->save($ret);
450
-
451
-                return $ret;
452
-            }
453
-        } else {
454
-            return $cacheData;
455
-        }
456
-    }
457
-
458
-    /**
459
-     * Retourne le total d'un champ
460
-     *
461
-     * @param  string $field    Le champ dont on veut calculer le total
462
-     * @param  object $criteria {@link CriteriaElement} to match
463
-     * @return integer le total
464
-     */
465
-    public function getSum($field, $criteria = null)
466
-    {
467
-        $limit = $start = 0;
468
-        require_once __DIR__ . '/lite.php';
469
-
470
-        $sql = 'SELECT Sum(' . $field . ') as cpt FROM ' . $this->table;
471
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
472
-            $sql .= ' ' . $criteria->renderWhere();
473
-            if ($criteria->groupby != '') {
474
-                $sql .= $criteria->getGroupby();
475
-            }
476
-            $limit = $criteria->getLimit();
477
-            $start = $criteria->getStart();
478
-        }
479
-        $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
480
-        $id         = $this->_getIdForCache($sql, $start, $limit);
481
-        $cacheData  = $Cache_Lite->get($id);
482
-        if ($cacheData === false) {
483
-            $result = $this->db->query($sql, $limit, $start);
484
-            if (!$result) {
485
-                $ret = 0;
486
-                $Cache_Lite->save($ret);
487
-
488
-                return $ret;
489
-            }
490
-            $row   = $this->db->fetchArray($result);
491
-            $count = $row['cpt'];
492
-            $Cache_Lite->save($count);
493
-
494
-            return $count;
495
-        } else {
496
-            return $cacheData;
497
-        }
498
-    }
499
-
500
-    /**
501
-     * delete an object from the database
502
-     *
503
-     * @param  XoopsObject $obj reference to the object to delete
504
-     * @param  bool        $force
505
-     * @return bool   FALSE if failed.
506
-     */
507
-    public function delete(XoopsObject $obj, $force = false)
508
-    {
509
-        if (is_array($this->keyName)) {
510
-            $clause = array();
511
-            $vnb    = count($this->keyName);
512
-            for ($i = 0; $i < $vnb; ++$i) {
513
-                $clause[] = $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
514
-            }
515
-            $whereclause = implode(' AND ', $clause);
516
-        } else {
517
-            $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
518
-        }
519
-        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
520
-        if (false != $force) {
521
-            $result = $this->db->queryF($sql);
522
-        } else {
523
-            $result = $this->db->query($sql);
524
-        }
525
-        // Clear cache
526
-        $this->forceCacheClean();
527
-
528
-        if (!$result) {
529
-            return false;
530
-        }
531
-
532
-        return true;
533
-    }
534
-
535
-    /**
536
-     * Quickly insert a record like this $myobject_handler->quickInsert('field1' => field1value, 'field2' => $field2value)
537
-     *
538
-     * @param  array $vars  Array containing the fields name and value
539
-     * @param  bool  $force whether to force the query execution despite security settings
540
-     * @return bool  @link insert's value
541
-     */
542
-    public function quickInsert($vars = null, $force = true)
543
-    {
544
-        $object = $this->create(true);
545
-        $object->setVars($vars);
546
-        $retval =& $this->insert($object, $force);
547
-        unset($object);
548
-
549
-        // Clear cache
550
-        $this->forceCacheClean();
551
-
552
-        return $retval;
553
-    }
554
-
555
-    /**
556
-     * insert a new object in the database
557
-     *
558
-     * @param  XoopsObject $obj         reference to the object
559
-     * @param  bool        $force       whether to force the query execution despite security settings
560
-     * @param  bool        $checkObject check if the object is dirty and clean the attributes
561
-     * @param bool         $ignoreInsert
562
-     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
563
-     */
564
-
565
-    public function insert(XoopsObject $obj, $force = false, $checkObject = true, $ignoreInsert = false)
566
-    {
567
-        if ($checkObject != false) {
568
-            if (!is_object($obj)) {
569
-                trigger_error('Error, not object');
570
-
571
-                return false;
572
-            }
573
-            /**
574
-             * @TODO: Change to if (!(class_exists($this->className) && $obj instanceof $this->className)) when going fully PHP5
575
-             */
576
-            if (!is_a($obj, $this->className)) {
577
-                $obj->setErrors(get_class($obj) . ' Differs from ' . $this->className);
578
-
579
-                return false;
580
-            }
581
-            if (!$obj->isDirty()) {
582
-                $obj->setErrors('Not dirty'); //will usually not be outputted as errors are not displayed when the method returns true, but it can be helpful when troubleshooting code - Mith
583
-
584
-                return true;
585
-            }
586
-        }
587
-        if (!$obj->cleanVars()) {
588
-            foreach ($obj->getErrors() as $oneerror) {
589
-                trigger_error($oneerror);
590
-            }
591
-
592
-            return false;
593
-        }
594
-        foreach ($obj->cleanVars as $k => $v) {
595
-            if ($obj->vars[$k]['data_type'] == XOBJ_DTYPE_INT) {
596
-                $cleanvars[$k] = (int)$v;
597
-            } elseif (is_array($v)) {
598
-                $cleanvars[$k] = $this->db->quoteString(implode(',', $v));
599
-            } else {
600
-                $cleanvars[$k] = $this->db->quoteString($v);
601
-            }
602
-        }
603
-        if (isset($cleanvars['dohtml'])) {        // Modification Herv� to be able to use dohtml
604
-            unset($cleanvars['dohtml']);
605
-        }
606
-        if ($obj->isNew()) {
607
-            if (!is_array($this->keyName)) {
608
-                if ($cleanvars[$this->keyName] < 1) {
609
-                    $cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
610
-                }
611
-            }
612
-            $ignore = '';
613
-            if ($ignoreInsert) {
614
-                $ignore = 'IGNORE';
615
-            }
616
-            $sql = "INSERT $ignore INTO " . $this->table . ' (' . implode(',', array_keys($cleanvars)) . ') VALUES (' . implode(',', array_values($cleanvars)) . ')';
617
-        } else {
618
-            $sql = 'UPDATE ' . $this->table . ' SET';
619
-            foreach ($cleanvars as $key => $value) {
620
-                if ((!is_array($this->keyName) && $key == $this->keyName) || (is_array($this->keyName) && in_array($key, $this->keyName))) {
621
-                    continue;
622
-                }
623
-                if (isset($notfirst)) {
624
-                    $sql .= ',';
625
-                }
626
-                $sql .= ' ' . $key . ' = ' . $value;
627
-                $notfirst = true;
628
-            }
629
-            if (is_array($this->keyName)) {
630
-                $whereclause = '';
631
-                $vnb         = count($this->keyName);
632
-                for ($i = 0; $i < $vnb; ++$i) {
633
-                    if ($i > 0) {
634
-                        $whereclause .= ' AND ';
635
-                    }
636
-                    $whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
637
-                }
638
-            } else {
639
-                $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
640
-            }
641
-            $sql .= ' WHERE ' . $whereclause;
642
-        }
643
-
644
-        if (false != $force) {
645
-            $result = $this->db->queryF($sql);
646
-        } else {
647
-            $result = $this->db->query($sql);
648
-        }
649
-
650
-        // Clear cache
651
-        $this->forceCacheClean();
652
-
653
-        if (!$result) {
654
-            return false;
655
-        }
656
-        if ($obj->isNew() && !is_array($this->keyName)) {
657
-            $obj->assignVar($this->keyName, $this->db->getInsertId());
658
-        }
659
-
660
-        return true;
661
-    }
662
-
663
-    /**
664
-     * Change a value for objects with a certain criteria
665
-     *
666
-     * @param string $fieldname  Name of the field
667
-     * @param string $fieldvalue Value to write
668
-     * @param object $criteria   {@link CriteriaElement}
669
-     *
670
-     * @param bool   $force
671
-     * @return bool
672
-     */
673
-    public function updateAll($fieldname, $fieldvalue, $criteria = null, $force = false)
674
-    {
675
-        $set_clause = $fieldname . ' = ';
676
-        if (is_numeric($fieldvalue)) {
677
-            $set_clause .= $fieldvalue;
678
-        } elseif (is_array($fieldvalue)) {
679
-            $set_clause .= $this->db->quoteString(implode(',', $fieldvalue));
680
-        } else {
681
-            $set_clause .= $this->db->quoteString($fieldvalue);
682
-        }
683
-        $sql = 'UPDATE ' . $this->table . ' SET ' . $set_clause;
684
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
685
-            $sql .= ' ' . $criteria->renderWhere();
686
-        }
687
-        if ($force) {
688
-            $result = $this->db->queryF($sql);
689
-        } else {
690
-            $result = $this->db->query($sql);
691
-        }
692
-
693
-        // Clear cache
694
-        $this->forceCacheClean();
695
-
696
-        if (!$result) {
697
-            return false;
698
-        }
699
-
700
-        return true;
701
-    }
702
-
703
-    //  check if target object is attempting to use duplicated info
704
-    public function isDuplicated(&$obj, $field = '', $error = '')
705
-    {
706
-        if (empty($field)) {
707
-            return false;
708
-        }
709
-        $criteria = new CriteriaCompo();
710
-        $criteria->add(new Criteria($field, $obj->getVar($field)));
711
-        //  one more condition if target object exisits in database
712
-        if (!$obj->isNew()) {
713
-            $criteria->add(new Criteria($this->_key, $obj->getVar($this->_key), '!='));
714
-        }
715
-        if ($this->getCount($criteria)) {
716
-            $obj->setErrors($error);
717
-
718
-            return true;
719
-        }
720
-
721
-        return false;
722
-    }
723
-
724
-    /**
725
-     * delete all objects meeting the conditions
726
-     *
727
-     * @param  object $criteria {@link CriteriaElement} with conditions to meet
728
-     * @return bool
729
-     */
730
-    public function deleteAll($criteria = null)
731
-    {
732
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
733
-            $sql = 'DELETE FROM ' . $this->table;
734
-            $sql .= ' ' . $criteria->renderWhere();
735
-            if (!$this->db->queryF($sql)) {
736
-                return false;
737
-            }
738
-            $rows = $this->db->getAffectedRows();
739
-
740
-            // Clear cache
741
-            $this->forceCacheClean();
742
-
743
-            return $rows > 0 ? $rows : true;
744
-        }
745
-
746
-        return false;
747
-    }
748
-
749
-    /**
750
-     * Compare two objects and returns, in an array, the differences
751
-     *
752
-     * @param  XoopsObject $old_object The first object to compare
753
-     * @param  XoopsObject $new_object The new object
754
-     * @return array       differences  key = fieldname, value = array('old_value', 'new_value')
755
-     */
756
-    public function compareObjects($old_object, $new_object)
757
-    {
758
-        $ret       = array();
759
-        $vars_name = array_keys($old_object->getVars());
760
-        foreach ($vars_name as $one_var) {
761
-            if ($old_object->getVar($one_var, 'f') == $new_object->getVar($one_var, 'f')) {
762
-            } else {
763
-                $ret[$one_var] = array($old_object->getVar($one_var), $new_object->getVar($one_var));
764
-            }
765
-        }
766
-
767
-        return $ret;
768
-    }
769
-
770
-    /**
771
-     * Get distincted values of a field in the table
772
-     *
773
-     * @param  string $field    Field's name
774
-     * @param  object $criteria {@link CriteriaElement} conditions to be met
775
-     * @param  string $format   Format in wich we want the datas
776
-     * @return array  containing the distinct values
777
-     */
778
-    public function getDistincts($field, $criteria = null, $format = 's')
779
-    {
780
-        require_once __DIR__ . '/lite.php';
781
-        $limit = $start = 0;
782
-        $sql   = 'SELECT ' . $this->keyName . ', ' . $field . ' FROM ' . $this->table;
783
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
784
-            $sql .= ' ' . $criteria->renderWhere();
785
-            $limit = $criteria->getLimit();
786
-            $start = $criteria->getStart();
787
-        }
788
-        $sql .= ' GROUP BY ' . $field . ' ORDER BY ' . $field;
789
-
790
-        $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
791
-        $id         = $this->_getIdForCache($sql, $start, $limit);
792
-        $cacheData  = $Cache_Lite->get($id);
793
-        if ($cacheData === false) {
794
-            $result = $this->db->query($sql, $limit, $start);
795
-            $ret    = array();
796
-            $obj    = new $this->className();
797
-            while ($myrow = $this->db->fetchArray($result)) {
798
-                $obj->setVar($field, $myrow[$field]);
799
-                $ret[$myrow[$this->keyName]] = $obj->getVar($field, $format);
800
-            }
801
-            $Cache_Lite->save($ret);
802
-
803
-            return $ret;
804
-        } else {
805
-            return $cacheData;
806
-        }
807
-    }
808
-
809
-    /**
810
-     * A generic shortcut to getObjects
811
-     *
812
-     * @author Herve Thouzard - Instant Zero
813
-     *
814
-     * @param  integer $start   Starting position
815
-     * @param  integer $limit   Maximum count of elements to return
816
-     * @param  string  $sort    Field to use for the sort
817
-     * @param  string  $order   Sort order
818
-     * @param  boolean $idAsKey Do we have to return an array whoses keys are the record's ID ?
819
-     * @return array   Array of current objects
820
-     */
821
-    public function getItems($start = 0, $limit = 0, $sort = '', $order = 'ASC', $idAsKey = true)
822
-    {
823
-        if (trim($order) == '') {
824
-            if (isset($this->identifierName) && trim($this->identifierName) != '') {
825
-                $order = $this->identifierName;
826
-            } else {
827
-                $order = $this->keyName;
828
-            }
829
-        }
830
-        $items   = array();
831
-        $critere = new Criteria($this->keyName, 0, '<>');
832
-        $critere->setLimit($limit);
833
-        $critere->setStart($start);
834
-        $critere->setSort($sort);
835
-        $critere->setOrder($order);
836
-        $items = $this->getObjects($critere, $idAsKey);
837
-
838
-        return $items;
839
-    }
840
-
841
-    /**
842
-     * Forces the cache to be cleaned
843
-     */
844
-    public function forceCacheClean()
845
-    {
846
-        require_once __DIR__ . '/lite.php';
847
-        $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
848
-        $Cache_Lite->clean();
849
-    }
81
+	public    $table;
82
+	public    $keyName;
83
+	public    $className;
84
+	public    $identifierName;
85
+	protected $cacheOptions = array();
86
+	/**#@-*/
87
+
88
+	/**
89
+	 * Constructor - called from child classes
90
+	 * @param object $db           {@link XoopsDatabase} object
91
+	 * @param string $tablename    Name of database table
92
+	 * @param string $classname    Name of Class, this handler is managing
93
+	 * @param string $keyname      Name of the property, holding the key
94
+	 * @param string $idenfierName Name of the property, holding the label
95
+	 * @param array  $cacheOptions Optional, options for the cache
96
+	 *
97
+	 */
98
+	public function __construct(&$db, $tablename, $classname, $keyname, $idenfierName = '', $cacheOptions = null)
99
+	{
100
+		parent::__construct($db);
101
+		$this->table     = $db->prefix($tablename);
102
+		$this->keyName   = $keyname;
103
+		$this->className = $classname;
104
+		if (trim($idenfierName) != '') {
105
+			$this->identifierName = $idenfierName;
106
+		}
107
+		// To diable cache, add this line after the first one : 'caching' => false,
108
+		if (is_null($cacheOptions)) {
109
+			$this->setCachingOptions(array('cacheDir' => REFERENCES_CACHE_PATH, 'lifeTime' => null, 'automaticSerialization' => true, 'fileNameProtection' => false));
110
+		} else {
111
+			$this->setCachingOptions($cacheOptions);
112
+		}
113
+	}
114
+
115
+	public function setCachingOptions($cacheOptions)
116
+	{
117
+		$this->cacheOptions = $cacheOptions;
118
+	}
119
+
120
+	/**
121
+	 * Generates a unique ID for a Sql Query
122
+	 *
123
+	 * @param  string  $query The SQL query for which we want a unidque ID
124
+	 * @param  integer $start Which record to start at
125
+	 * @param  integer $limit Max number of objects to fetch
126
+	 * @return string  An MD5 of the query
127
+	 */
128
+	protected function _getIdForCache($query, $start, $limit)
129
+	{
130
+		$id = md5($query . '-' . (string)$start . '-' . (string)$limit);
131
+
132
+		return $id;
133
+	}
134
+
135
+	/**
136
+	 * create a new object
137
+	 *
138
+	 * @param bool $isNew Flag the new objects as "new"?
139
+	 *
140
+	 * @return object
141
+	 */
142
+	public function &create($isNew = true)
143
+	{
144
+		$obj = new $this->className();
145
+		if ($isNew === true) {
146
+			$obj->setNew();
147
+		}
148
+
149
+		return $obj;
150
+	}
151
+
152
+	/**
153
+	 * retrieve an object
154
+	 *
155
+	 * @param  mixed $id        ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
156
+	 * @param  bool  $as_object whether to return an object or an array
157
+	 * @return mixed reference to the object, FALSE if failed
158
+	 */
159
+	public function &get($id, $as_object = true)
160
+	{
161
+		if (is_array($this->keyName)) {
162
+			$criteria = new CriteriaCompo();
163
+			$vnb      = count($this->keyName);
164
+			for ($i = 0; $i < $vnb; ++$i) {
165
+				$criteria->add(new Criteria($this->keyName[$i], (int)$id[$i]));
166
+			}
167
+		} else {
168
+			$criteria = new Criteria($this->keyName, (int)$id);
169
+		}
170
+		$criteria->setLimit(1);
171
+		$obj_array = $this->getObjects($criteria, false, $as_object);
172
+		if (count($obj_array) != 1) {
173
+			$ret = null;
174
+		} else {
175
+			$ret =& $obj_array[0];
176
+		}
177
+
178
+		return $ret;
179
+	}
180
+
181
+	/**
182
+	 * retrieve objects from the database
183
+	 *
184
+	 * @param null|CriteriaElement $criteria  {@link CriteriaElement} conditions to be met
185
+	 * @param bool                 $id_as_key use the ID as key for the array?
186
+	 * @param bool                 $as_object return an array of objects?
187
+	 *
188
+	 * @param string               $fields
189
+	 * @param bool                 $autoSort
190
+	 * @return array
191
+	 */
192
+	public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false, $as_object = true, $fields = '*', $autoSort = true)
193
+	{
194
+		require_once __DIR__ . '/lite.php';
195
+		$ret   = array();
196
+		$limit = $start = 0;
197
+		$sql   = 'SELECT ' . $fields . ' FROM ' . $this->table;
198
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
199
+			$sql .= ' ' . $criteria->renderWhere();
200
+			if ($criteria->groupby != '') {
201
+				$sql .= $criteria->getGroupby();
202
+			}
203
+			if ($criteria->getSort() != '') {
204
+				$sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
205
+			} elseif ($this->identifierName != '' && $autoSort) {
206
+				$sql .= ' ORDER BY ' . $this->identifierName;
207
+			}
208
+			$limit = $criteria->getLimit();
209
+			$start = $criteria->getStart();
210
+		}
211
+		$Cache_Lite = new references_Cache_Lite($this->cacheOptions);
212
+		$id         = $this->_getIdForCache($sql, $start, $limit);
213
+		$cacheData  = $Cache_Lite->get($id);
214
+		if ($cacheData === false) {
215
+			$result = $this->db->query($sql, $limit, $start);
216
+			if (!$result) {
217
+				return $ret;
218
+			}
219
+			$ret = $this->convertResultSet($result, $id_as_key, $as_object, $fields);
220
+			$Cache_Lite->save($ret);
221
+
222
+			return $ret;
223
+		} else {
224
+			return $cacheData;
225
+		}
226
+	}
227
+
228
+	/**
229
+	 * Convert a database resultset to a returnable array
230
+	 *
231
+	 * @param object  $result    database resultset
232
+	 * @param boolean $id_as_key - should NOT be used with joint keys
233
+	 * @param boolean $as_object
234
+	 * @param string  $fields    Requested fields from the query
235
+	 *
236
+	 * @return array
237
+	 */
238
+	protected function convertResultSet($result, $id_as_key = false, $as_object = true, $fields = '*')
239
+	{
240
+		$ret = array();
241
+		while ($myrow = $this->db->fetchArray($result)) {
242
+			$obj =& $this->create(false);
243
+			$obj->assignVars($myrow);
244
+			if (!$id_as_key) {
245
+				if ($as_object) {
246
+					$ret[] =& $obj;
247
+				} else {
248
+					$row     = array();
249
+					$vars    = $obj->getVars();
250
+					$tbl_tmp = array_keys($vars);
251
+					foreach ($tbl_tmp as $i) {
252
+						$row[$i] = $obj->getVar($i);
253
+					}
254
+					$ret[] = $row;
255
+				}
256
+			} else {
257
+				if ($as_object) {
258
+					if ($fields === '*') {
259
+						$ret[$myrow[$this->keyName]] =& $obj;
260
+					} else {
261
+						$ret[] =& $obj;
262
+					}
263
+				} else {
264
+					$row     = array();
265
+					$vars    = $obj->getVars();
266
+					$tbl_tmp = array_keys($vars);
267
+					foreach ($tbl_tmp as $i) {
268
+						$row[$i] = $obj->getVar($i);
269
+					}
270
+					$ret[$myrow[$this->keyName]] = $row;
271
+				}
272
+			}
273
+			unset($obj);
274
+		}
275
+
276
+		return $ret;
277
+	}
278
+
279
+	/**
280
+	 * get IDs of objects matching a condition
281
+	 *
282
+	 * @param  object $criteria {@link CriteriaElement} to match
283
+	 * @return array  of object IDs
284
+	 */
285
+	public function getIds($criteria = null)
286
+	{
287
+		require_once __DIR__ . '/lite.php';
288
+		$limit = $start = 0;
289
+
290
+		$Cache_Lite = new references_Cache_Lite($this->cacheOptions);
291
+		$sql        = 'SELECT ' . $this->keyName . ' FROM ' . $this->table;
292
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
293
+			$sql .= ' ' . $criteria->renderWhere();
294
+			if ($criteria->groupby != '') {
295
+				$sql .= $criteria->getGroupby();
296
+			}
297
+			if ($criteria->getSort() != '') {
298
+				$sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
299
+			} elseif ($this->identifierName != '') {
300
+				$sql .= ' ORDER BY ' . $this->identifierName;
301
+			}
302
+			$limit = $criteria->getLimit();
303
+			$start = $criteria->getStart();
304
+		}
305
+
306
+		$id        = $this->_getIdForCache($sql, $start, $limit);
307
+		$cacheData = $Cache_Lite->get($id);
308
+		if ($cacheData === false) {
309
+			$result = $this->db->query($sql, $limit, $start);
310
+			$ret    = array();
311
+			while ($myrow = $this->db->fetchArray($result)) {
312
+				$ret[] = $myrow[$this->keyName];
313
+			}
314
+			$Cache_Lite->save($ret);
315
+
316
+			return $ret;
317
+		} else {
318
+			return $cacheData;
319
+		}
320
+	}
321
+
322
+	/**
323
+	 * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS
324
+	 *
325
+	 * @param object $criteria {@link CriteriaElement} conditions to be met
326
+	 * @return array
327
+	 */
328
+	public function getList($criteria = null)
329
+	{
330
+		require_once __DIR__ . '/lite.php';
331
+		$limit      = $start = 0;
332
+		$Cache_Lite = new references_Cache_Lite($this->cacheOptions);
333
+
334
+		$ret = array();
335
+
336
+		$sql = 'SELECT ' . $this->keyName;
337
+		if (!empty($this->identifierName)) {
338
+			$sql .= ', ' . $this->identifierName;
339
+		}
340
+		$sql .= ' FROM ' . $this->table;
341
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
342
+			$sql .= ' ' . $criteria->renderWhere();
343
+			if ($criteria->groupby != '') {
344
+				$sql .= $criteria->getGroupby();
345
+			}
346
+			if ($criteria->getSort() != '') {
347
+				$sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
348
+			} elseif ($this->identifierName != '') {
349
+				$sql .= ' ORDER BY ' . $this->identifierName;
350
+			}
351
+			$limit = $criteria->getLimit();
352
+			$start = $criteria->getStart();
353
+		}
354
+
355
+		$id        = $this->_getIdForCache($sql, $start, $limit);
356
+		$cacheData = $Cache_Lite->get($id);
357
+		if ($cacheData === false) {
358
+			$result = $this->db->query($sql, $limit, $start);
359
+			if (!$result) {
360
+				$Cache_Lite->save($ret);
361
+
362
+				return $ret;
363
+			}
364
+
365
+			$myts = MyTextSanitizer::getInstance();
366
+			while ($myrow = $this->db->fetchArray($result)) {
367
+				//identifiers should be textboxes, so sanitize them like that
368
+				$ret[$myrow[$this->keyName]] = empty($this->identifierName) ? 1 : $myts->htmlSpecialChars($myrow[$this->identifierName]);
369
+			}
370
+			$Cache_Lite->save($ret);
371
+
372
+			return $ret;
373
+		} else {
374
+			return $cacheData;
375
+		}
376
+	}
377
+
378
+	/**
379
+	 * Retourne des éléments selon leur ID
380
+	 *
381
+	 * @param array $ids Les ID des éléments à retrouver
382
+	 * @param null  $additionnal
383
+	 * @return array Tableau d'objets
384
+	 */
385
+	public function getItemsFromIds($ids, $additionnal = null)
386
+	{
387
+		$ret = array();
388
+		if (is_array($ids) && count($ids) > 0) {
389
+			$criteria = new CriteriaCompo();
390
+			$criteria->add(new Criteria($this->keyName, '(' . implode(',', $ids) . ')', 'IN'));
391
+			if (!is_null($additionnal)) {
392
+				$criteria->add($additionnal);
393
+			}
394
+			$ret = $this->getObjects($criteria, true);
395
+		}
396
+
397
+		return $ret;
398
+	}
399
+
400
+	/**
401
+	 * count objects matching a condition
402
+	 *
403
+	 * @param  object $criteria {@link CriteriaElement} to match
404
+	 * @return int    count of objects
405
+	 */
406
+	public function getCount($criteria = null)
407
+	{
408
+		$field   = '';
409
+		$groupby = false;
410
+		$limit   = $start = 0;
411
+		require_once __DIR__ . '/lite.php';
412
+
413
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
414
+			if ($criteria->groupby != '') {
415
+				$groupby = true;
416
+				$field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
417
+			}
418
+		}
419
+		$sql = 'SELECT ' . $field . 'COUNT(*) FROM ' . $this->table;
420
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
421
+			$sql .= ' ' . $criteria->renderWhere();
422
+			if ($criteria->groupby != '') {
423
+				$sql .= $criteria->getGroupby();
424
+			}
425
+			$limit = $criteria->getLimit();
426
+			$start = $criteria->getStart();
427
+		}
428
+		$Cache_Lite = new references_Cache_Lite($this->cacheOptions);
429
+		$id         = $this->_getIdForCache($sql, $start, $limit);
430
+		$cacheData  = $Cache_Lite->get($id);
431
+		if ($cacheData === false) {
432
+			$result = $this->db->query($sql, $limit, $start);
433
+			if (!$result) {
434
+				$ret = 0;
435
+				$Cache_Lite->save($ret);
436
+
437
+				return $ret;
438
+			}
439
+			if ($groupby == false) {
440
+				list($count) = $this->db->fetchRow($result);
441
+				$Cache_Lite->save($count);
442
+
443
+				return $count;
444
+			} else {
445
+				$ret = array();
446
+				while (list($id, $count) = $this->db->fetchRow($result)) {
447
+					$ret[$id] = $count;
448
+				}
449
+				$Cache_Lite->save($ret);
450
+
451
+				return $ret;
452
+			}
453
+		} else {
454
+			return $cacheData;
455
+		}
456
+	}
457
+
458
+	/**
459
+	 * Retourne le total d'un champ
460
+	 *
461
+	 * @param  string $field    Le champ dont on veut calculer le total
462
+	 * @param  object $criteria {@link CriteriaElement} to match
463
+	 * @return integer le total
464
+	 */
465
+	public function getSum($field, $criteria = null)
466
+	{
467
+		$limit = $start = 0;
468
+		require_once __DIR__ . '/lite.php';
469
+
470
+		$sql = 'SELECT Sum(' . $field . ') as cpt FROM ' . $this->table;
471
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
472
+			$sql .= ' ' . $criteria->renderWhere();
473
+			if ($criteria->groupby != '') {
474
+				$sql .= $criteria->getGroupby();
475
+			}
476
+			$limit = $criteria->getLimit();
477
+			$start = $criteria->getStart();
478
+		}
479
+		$Cache_Lite = new references_Cache_Lite($this->cacheOptions);
480
+		$id         = $this->_getIdForCache($sql, $start, $limit);
481
+		$cacheData  = $Cache_Lite->get($id);
482
+		if ($cacheData === false) {
483
+			$result = $this->db->query($sql, $limit, $start);
484
+			if (!$result) {
485
+				$ret = 0;
486
+				$Cache_Lite->save($ret);
487
+
488
+				return $ret;
489
+			}
490
+			$row   = $this->db->fetchArray($result);
491
+			$count = $row['cpt'];
492
+			$Cache_Lite->save($count);
493
+
494
+			return $count;
495
+		} else {
496
+			return $cacheData;
497
+		}
498
+	}
499
+
500
+	/**
501
+	 * delete an object from the database
502
+	 *
503
+	 * @param  XoopsObject $obj reference to the object to delete
504
+	 * @param  bool        $force
505
+	 * @return bool   FALSE if failed.
506
+	 */
507
+	public function delete(XoopsObject $obj, $force = false)
508
+	{
509
+		if (is_array($this->keyName)) {
510
+			$clause = array();
511
+			$vnb    = count($this->keyName);
512
+			for ($i = 0; $i < $vnb; ++$i) {
513
+				$clause[] = $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
514
+			}
515
+			$whereclause = implode(' AND ', $clause);
516
+		} else {
517
+			$whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
518
+		}
519
+		$sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
520
+		if (false != $force) {
521
+			$result = $this->db->queryF($sql);
522
+		} else {
523
+			$result = $this->db->query($sql);
524
+		}
525
+		// Clear cache
526
+		$this->forceCacheClean();
527
+
528
+		if (!$result) {
529
+			return false;
530
+		}
531
+
532
+		return true;
533
+	}
534
+
535
+	/**
536
+	 * Quickly insert a record like this $myobject_handler->quickInsert('field1' => field1value, 'field2' => $field2value)
537
+	 *
538
+	 * @param  array $vars  Array containing the fields name and value
539
+	 * @param  bool  $force whether to force the query execution despite security settings
540
+	 * @return bool  @link insert's value
541
+	 */
542
+	public function quickInsert($vars = null, $force = true)
543
+	{
544
+		$object = $this->create(true);
545
+		$object->setVars($vars);
546
+		$retval =& $this->insert($object, $force);
547
+		unset($object);
548
+
549
+		// Clear cache
550
+		$this->forceCacheClean();
551
+
552
+		return $retval;
553
+	}
554
+
555
+	/**
556
+	 * insert a new object in the database
557
+	 *
558
+	 * @param  XoopsObject $obj         reference to the object
559
+	 * @param  bool        $force       whether to force the query execution despite security settings
560
+	 * @param  bool        $checkObject check if the object is dirty and clean the attributes
561
+	 * @param bool         $ignoreInsert
562
+	 * @return bool FALSE if failed, TRUE if already present and unchanged or successful
563
+	 */
564
+
565
+	public function insert(XoopsObject $obj, $force = false, $checkObject = true, $ignoreInsert = false)
566
+	{
567
+		if ($checkObject != false) {
568
+			if (!is_object($obj)) {
569
+				trigger_error('Error, not object');
570
+
571
+				return false;
572
+			}
573
+			/**
574
+			 * @TODO: Change to if (!(class_exists($this->className) && $obj instanceof $this->className)) when going fully PHP5
575
+			 */
576
+			if (!is_a($obj, $this->className)) {
577
+				$obj->setErrors(get_class($obj) . ' Differs from ' . $this->className);
578
+
579
+				return false;
580
+			}
581
+			if (!$obj->isDirty()) {
582
+				$obj->setErrors('Not dirty'); //will usually not be outputted as errors are not displayed when the method returns true, but it can be helpful when troubleshooting code - Mith
583
+
584
+				return true;
585
+			}
586
+		}
587
+		if (!$obj->cleanVars()) {
588
+			foreach ($obj->getErrors() as $oneerror) {
589
+				trigger_error($oneerror);
590
+			}
591
+
592
+			return false;
593
+		}
594
+		foreach ($obj->cleanVars as $k => $v) {
595
+			if ($obj->vars[$k]['data_type'] == XOBJ_DTYPE_INT) {
596
+				$cleanvars[$k] = (int)$v;
597
+			} elseif (is_array($v)) {
598
+				$cleanvars[$k] = $this->db->quoteString(implode(',', $v));
599
+			} else {
600
+				$cleanvars[$k] = $this->db->quoteString($v);
601
+			}
602
+		}
603
+		if (isset($cleanvars['dohtml'])) {        // Modification Herv� to be able to use dohtml
604
+			unset($cleanvars['dohtml']);
605
+		}
606
+		if ($obj->isNew()) {
607
+			if (!is_array($this->keyName)) {
608
+				if ($cleanvars[$this->keyName] < 1) {
609
+					$cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
610
+				}
611
+			}
612
+			$ignore = '';
613
+			if ($ignoreInsert) {
614
+				$ignore = 'IGNORE';
615
+			}
616
+			$sql = "INSERT $ignore INTO " . $this->table . ' (' . implode(',', array_keys($cleanvars)) . ') VALUES (' . implode(',', array_values($cleanvars)) . ')';
617
+		} else {
618
+			$sql = 'UPDATE ' . $this->table . ' SET';
619
+			foreach ($cleanvars as $key => $value) {
620
+				if ((!is_array($this->keyName) && $key == $this->keyName) || (is_array($this->keyName) && in_array($key, $this->keyName))) {
621
+					continue;
622
+				}
623
+				if (isset($notfirst)) {
624
+					$sql .= ',';
625
+				}
626
+				$sql .= ' ' . $key . ' = ' . $value;
627
+				$notfirst = true;
628
+			}
629
+			if (is_array($this->keyName)) {
630
+				$whereclause = '';
631
+				$vnb         = count($this->keyName);
632
+				for ($i = 0; $i < $vnb; ++$i) {
633
+					if ($i > 0) {
634
+						$whereclause .= ' AND ';
635
+					}
636
+					$whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
637
+				}
638
+			} else {
639
+				$whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
640
+			}
641
+			$sql .= ' WHERE ' . $whereclause;
642
+		}
643
+
644
+		if (false != $force) {
645
+			$result = $this->db->queryF($sql);
646
+		} else {
647
+			$result = $this->db->query($sql);
648
+		}
649
+
650
+		// Clear cache
651
+		$this->forceCacheClean();
652
+
653
+		if (!$result) {
654
+			return false;
655
+		}
656
+		if ($obj->isNew() && !is_array($this->keyName)) {
657
+			$obj->assignVar($this->keyName, $this->db->getInsertId());
658
+		}
659
+
660
+		return true;
661
+	}
662
+
663
+	/**
664
+	 * Change a value for objects with a certain criteria
665
+	 *
666
+	 * @param string $fieldname  Name of the field
667
+	 * @param string $fieldvalue Value to write
668
+	 * @param object $criteria   {@link CriteriaElement}
669
+	 *
670
+	 * @param bool   $force
671
+	 * @return bool
672
+	 */
673
+	public function updateAll($fieldname, $fieldvalue, $criteria = null, $force = false)
674
+	{
675
+		$set_clause = $fieldname . ' = ';
676
+		if (is_numeric($fieldvalue)) {
677
+			$set_clause .= $fieldvalue;
678
+		} elseif (is_array($fieldvalue)) {
679
+			$set_clause .= $this->db->quoteString(implode(',', $fieldvalue));
680
+		} else {
681
+			$set_clause .= $this->db->quoteString($fieldvalue);
682
+		}
683
+		$sql = 'UPDATE ' . $this->table . ' SET ' . $set_clause;
684
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
685
+			$sql .= ' ' . $criteria->renderWhere();
686
+		}
687
+		if ($force) {
688
+			$result = $this->db->queryF($sql);
689
+		} else {
690
+			$result = $this->db->query($sql);
691
+		}
692
+
693
+		// Clear cache
694
+		$this->forceCacheClean();
695
+
696
+		if (!$result) {
697
+			return false;
698
+		}
699
+
700
+		return true;
701
+	}
702
+
703
+	//  check if target object is attempting to use duplicated info
704
+	public function isDuplicated(&$obj, $field = '', $error = '')
705
+	{
706
+		if (empty($field)) {
707
+			return false;
708
+		}
709
+		$criteria = new CriteriaCompo();
710
+		$criteria->add(new Criteria($field, $obj->getVar($field)));
711
+		//  one more condition if target object exisits in database
712
+		if (!$obj->isNew()) {
713
+			$criteria->add(new Criteria($this->_key, $obj->getVar($this->_key), '!='));
714
+		}
715
+		if ($this->getCount($criteria)) {
716
+			$obj->setErrors($error);
717
+
718
+			return true;
719
+		}
720
+
721
+		return false;
722
+	}
723
+
724
+	/**
725
+	 * delete all objects meeting the conditions
726
+	 *
727
+	 * @param  object $criteria {@link CriteriaElement} with conditions to meet
728
+	 * @return bool
729
+	 */
730
+	public function deleteAll($criteria = null)
731
+	{
732
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
733
+			$sql = 'DELETE FROM ' . $this->table;
734
+			$sql .= ' ' . $criteria->renderWhere();
735
+			if (!$this->db->queryF($sql)) {
736
+				return false;
737
+			}
738
+			$rows = $this->db->getAffectedRows();
739
+
740
+			// Clear cache
741
+			$this->forceCacheClean();
742
+
743
+			return $rows > 0 ? $rows : true;
744
+		}
745
+
746
+		return false;
747
+	}
748
+
749
+	/**
750
+	 * Compare two objects and returns, in an array, the differences
751
+	 *
752
+	 * @param  XoopsObject $old_object The first object to compare
753
+	 * @param  XoopsObject $new_object The new object
754
+	 * @return array       differences  key = fieldname, value = array('old_value', 'new_value')
755
+	 */
756
+	public function compareObjects($old_object, $new_object)
757
+	{
758
+		$ret       = array();
759
+		$vars_name = array_keys($old_object->getVars());
760
+		foreach ($vars_name as $one_var) {
761
+			if ($old_object->getVar($one_var, 'f') == $new_object->getVar($one_var, 'f')) {
762
+			} else {
763
+				$ret[$one_var] = array($old_object->getVar($one_var), $new_object->getVar($one_var));
764
+			}
765
+		}
766
+
767
+		return $ret;
768
+	}
769
+
770
+	/**
771
+	 * Get distincted values of a field in the table
772
+	 *
773
+	 * @param  string $field    Field's name
774
+	 * @param  object $criteria {@link CriteriaElement} conditions to be met
775
+	 * @param  string $format   Format in wich we want the datas
776
+	 * @return array  containing the distinct values
777
+	 */
778
+	public function getDistincts($field, $criteria = null, $format = 's')
779
+	{
780
+		require_once __DIR__ . '/lite.php';
781
+		$limit = $start = 0;
782
+		$sql   = 'SELECT ' . $this->keyName . ', ' . $field . ' FROM ' . $this->table;
783
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
784
+			$sql .= ' ' . $criteria->renderWhere();
785
+			$limit = $criteria->getLimit();
786
+			$start = $criteria->getStart();
787
+		}
788
+		$sql .= ' GROUP BY ' . $field . ' ORDER BY ' . $field;
789
+
790
+		$Cache_Lite = new references_Cache_Lite($this->cacheOptions);
791
+		$id         = $this->_getIdForCache($sql, $start, $limit);
792
+		$cacheData  = $Cache_Lite->get($id);
793
+		if ($cacheData === false) {
794
+			$result = $this->db->query($sql, $limit, $start);
795
+			$ret    = array();
796
+			$obj    = new $this->className();
797
+			while ($myrow = $this->db->fetchArray($result)) {
798
+				$obj->setVar($field, $myrow[$field]);
799
+				$ret[$myrow[$this->keyName]] = $obj->getVar($field, $format);
800
+			}
801
+			$Cache_Lite->save($ret);
802
+
803
+			return $ret;
804
+		} else {
805
+			return $cacheData;
806
+		}
807
+	}
808
+
809
+	/**
810
+	 * A generic shortcut to getObjects
811
+	 *
812
+	 * @author Herve Thouzard - Instant Zero
813
+	 *
814
+	 * @param  integer $start   Starting position
815
+	 * @param  integer $limit   Maximum count of elements to return
816
+	 * @param  string  $sort    Field to use for the sort
817
+	 * @param  string  $order   Sort order
818
+	 * @param  boolean $idAsKey Do we have to return an array whoses keys are the record's ID ?
819
+	 * @return array   Array of current objects
820
+	 */
821
+	public function getItems($start = 0, $limit = 0, $sort = '', $order = 'ASC', $idAsKey = true)
822
+	{
823
+		if (trim($order) == '') {
824
+			if (isset($this->identifierName) && trim($this->identifierName) != '') {
825
+				$order = $this->identifierName;
826
+			} else {
827
+				$order = $this->keyName;
828
+			}
829
+		}
830
+		$items   = array();
831
+		$critere = new Criteria($this->keyName, 0, '<>');
832
+		$critere->setLimit($limit);
833
+		$critere->setStart($start);
834
+		$critere->setSort($sort);
835
+		$critere->setOrder($order);
836
+		$items = $this->getObjects($critere, $idAsKey);
837
+
838
+		return $items;
839
+	}
840
+
841
+	/**
842
+	 * Forces the cache to be cleaned
843
+	 */
844
+	public function forceCacheClean()
845
+	{
846
+		require_once __DIR__ . '/lite.php';
847
+		$Cache_Lite = new references_Cache_Lite($this->cacheOptions);
848
+		$Cache_Lite->clean();
849
+	}
850 850
 }
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
      */
128 128
     protected function _getIdForCache($query, $start, $limit)
129 129
     {
130
-        $id = md5($query . '-' . (string)$start . '-' . (string)$limit);
130
+        $id = md5($query.'-'.(string) $start.'-'.(string) $limit);
131 131
 
132 132
         return $id;
133 133
     }
@@ -162,17 +162,17 @@  discard block
 block discarded – undo
162 162
             $criteria = new CriteriaCompo();
163 163
             $vnb      = count($this->keyName);
164 164
             for ($i = 0; $i < $vnb; ++$i) {
165
-                $criteria->add(new Criteria($this->keyName[$i], (int)$id[$i]));
165
+                $criteria->add(new Criteria($this->keyName[$i], (int) $id[$i]));
166 166
             }
167 167
         } else {
168
-            $criteria = new Criteria($this->keyName, (int)$id);
168
+            $criteria = new Criteria($this->keyName, (int) $id);
169 169
         }
170 170
         $criteria->setLimit(1);
171 171
         $obj_array = $this->getObjects($criteria, false, $as_object);
172 172
         if (count($obj_array) != 1) {
173 173
             $ret = null;
174 174
         } else {
175
-            $ret =& $obj_array[0];
175
+            $ret = & $obj_array[0];
176 176
         }
177 177
 
178 178
         return $ret;
@@ -191,19 +191,19 @@  discard block
 block discarded – undo
191 191
      */
192 192
     public function &getObjects(CriteriaElement $criteria = null, $id_as_key = false, $as_object = true, $fields = '*', $autoSort = true)
193 193
     {
194
-        require_once __DIR__ . '/lite.php';
194
+        require_once __DIR__.'/lite.php';
195 195
         $ret   = array();
196 196
         $limit = $start = 0;
197
-        $sql   = 'SELECT ' . $fields . ' FROM ' . $this->table;
197
+        $sql   = 'SELECT '.$fields.' FROM '.$this->table;
198 198
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
199
-            $sql .= ' ' . $criteria->renderWhere();
199
+            $sql .= ' '.$criteria->renderWhere();
200 200
             if ($criteria->groupby != '') {
201 201
                 $sql .= $criteria->getGroupby();
202 202
             }
203 203
             if ($criteria->getSort() != '') {
204
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
204
+                $sql .= ' ORDER BY '.$criteria->getSort().' '.$criteria->getOrder();
205 205
             } elseif ($this->identifierName != '' && $autoSort) {
206
-                $sql .= ' ORDER BY ' . $this->identifierName;
206
+                $sql .= ' ORDER BY '.$this->identifierName;
207 207
             }
208 208
             $limit = $criteria->getLimit();
209 209
             $start = $criteria->getStart();
@@ -239,11 +239,11 @@  discard block
 block discarded – undo
239 239
     {
240 240
         $ret = array();
241 241
         while ($myrow = $this->db->fetchArray($result)) {
242
-            $obj =& $this->create(false);
242
+            $obj = & $this->create(false);
243 243
             $obj->assignVars($myrow);
244 244
             if (!$id_as_key) {
245 245
                 if ($as_object) {
246
-                    $ret[] =& $obj;
246
+                    $ret[] = & $obj;
247 247
                 } else {
248 248
                     $row     = array();
249 249
                     $vars    = $obj->getVars();
@@ -256,9 +256,9 @@  discard block
 block discarded – undo
256 256
             } else {
257 257
                 if ($as_object) {
258 258
                     if ($fields === '*') {
259
-                        $ret[$myrow[$this->keyName]] =& $obj;
259
+                        $ret[$myrow[$this->keyName]] = & $obj;
260 260
                     } else {
261
-                        $ret[] =& $obj;
261
+                        $ret[] = & $obj;
262 262
                     }
263 263
                 } else {
264 264
                     $row     = array();
@@ -284,20 +284,20 @@  discard block
 block discarded – undo
284 284
      */
285 285
     public function getIds($criteria = null)
286 286
     {
287
-        require_once __DIR__ . '/lite.php';
287
+        require_once __DIR__.'/lite.php';
288 288
         $limit = $start = 0;
289 289
 
290 290
         $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
291
-        $sql        = 'SELECT ' . $this->keyName . ' FROM ' . $this->table;
291
+        $sql        = 'SELECT '.$this->keyName.' FROM '.$this->table;
292 292
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
293
-            $sql .= ' ' . $criteria->renderWhere();
293
+            $sql .= ' '.$criteria->renderWhere();
294 294
             if ($criteria->groupby != '') {
295 295
                 $sql .= $criteria->getGroupby();
296 296
             }
297 297
             if ($criteria->getSort() != '') {
298
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
298
+                $sql .= ' ORDER BY '.$criteria->getSort().' '.$criteria->getOrder();
299 299
             } elseif ($this->identifierName != '') {
300
-                $sql .= ' ORDER BY ' . $this->identifierName;
300
+                $sql .= ' ORDER BY '.$this->identifierName;
301 301
             }
302 302
             $limit = $criteria->getLimit();
303 303
             $start = $criteria->getStart();
@@ -327,26 +327,26 @@  discard block
 block discarded – undo
327 327
      */
328 328
     public function getList($criteria = null)
329 329
     {
330
-        require_once __DIR__ . '/lite.php';
330
+        require_once __DIR__.'/lite.php';
331 331
         $limit      = $start = 0;
332 332
         $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
333 333
 
334 334
         $ret = array();
335 335
 
336
-        $sql = 'SELECT ' . $this->keyName;
336
+        $sql = 'SELECT '.$this->keyName;
337 337
         if (!empty($this->identifierName)) {
338
-            $sql .= ', ' . $this->identifierName;
338
+            $sql .= ', '.$this->identifierName;
339 339
         }
340
-        $sql .= ' FROM ' . $this->table;
340
+        $sql .= ' FROM '.$this->table;
341 341
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
342
-            $sql .= ' ' . $criteria->renderWhere();
342
+            $sql .= ' '.$criteria->renderWhere();
343 343
             if ($criteria->groupby != '') {
344 344
                 $sql .= $criteria->getGroupby();
345 345
             }
346 346
             if ($criteria->getSort() != '') {
347
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
347
+                $sql .= ' ORDER BY '.$criteria->getSort().' '.$criteria->getOrder();
348 348
             } elseif ($this->identifierName != '') {
349
-                $sql .= ' ORDER BY ' . $this->identifierName;
349
+                $sql .= ' ORDER BY '.$this->identifierName;
350 350
             }
351 351
             $limit = $criteria->getLimit();
352 352
             $start = $criteria->getStart();
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
         $ret = array();
388 388
         if (is_array($ids) && count($ids) > 0) {
389 389
             $criteria = new CriteriaCompo();
390
-            $criteria->add(new Criteria($this->keyName, '(' . implode(',', $ids) . ')', 'IN'));
390
+            $criteria->add(new Criteria($this->keyName, '('.implode(',', $ids).')', 'IN'));
391 391
             if (!is_null($additionnal)) {
392 392
                 $criteria->add($additionnal);
393 393
             }
@@ -408,17 +408,17 @@  discard block
 block discarded – undo
408 408
         $field   = '';
409 409
         $groupby = false;
410 410
         $limit   = $start = 0;
411
-        require_once __DIR__ . '/lite.php';
411
+        require_once __DIR__.'/lite.php';
412 412
 
413 413
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
414 414
             if ($criteria->groupby != '') {
415 415
                 $groupby = true;
416
-                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
416
+                $field   = $criteria->groupby.', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
417 417
             }
418 418
         }
419
-        $sql = 'SELECT ' . $field . 'COUNT(*) FROM ' . $this->table;
419
+        $sql = 'SELECT '.$field.'COUNT(*) FROM '.$this->table;
420 420
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
421
-            $sql .= ' ' . $criteria->renderWhere();
421
+            $sql .= ' '.$criteria->renderWhere();
422 422
             if ($criteria->groupby != '') {
423 423
                 $sql .= $criteria->getGroupby();
424 424
             }
@@ -465,11 +465,11 @@  discard block
 block discarded – undo
465 465
     public function getSum($field, $criteria = null)
466 466
     {
467 467
         $limit = $start = 0;
468
-        require_once __DIR__ . '/lite.php';
468
+        require_once __DIR__.'/lite.php';
469 469
 
470
-        $sql = 'SELECT Sum(' . $field . ') as cpt FROM ' . $this->table;
470
+        $sql = 'SELECT Sum('.$field.') as cpt FROM '.$this->table;
471 471
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
472
-            $sql .= ' ' . $criteria->renderWhere();
472
+            $sql .= ' '.$criteria->renderWhere();
473 473
             if ($criteria->groupby != '') {
474 474
                 $sql .= $criteria->getGroupby();
475 475
             }
@@ -510,13 +510,13 @@  discard block
 block discarded – undo
510 510
             $clause = array();
511 511
             $vnb    = count($this->keyName);
512 512
             for ($i = 0; $i < $vnb; ++$i) {
513
-                $clause[] = $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
513
+                $clause[] = $this->keyName[$i].' = '.$obj->getVar($this->keyName[$i]);
514 514
             }
515 515
             $whereclause = implode(' AND ', $clause);
516 516
         } else {
517
-            $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
517
+            $whereclause = $this->keyName.' = '.$obj->getVar($this->keyName);
518 518
         }
519
-        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
519
+        $sql = 'DELETE FROM '.$this->table.' WHERE '.$whereclause;
520 520
         if (false != $force) {
521 521
             $result = $this->db->queryF($sql);
522 522
         } else {
@@ -543,7 +543,7 @@  discard block
 block discarded – undo
543 543
     {
544 544
         $object = $this->create(true);
545 545
         $object->setVars($vars);
546
-        $retval =& $this->insert($object, $force);
546
+        $retval = & $this->insert($object, $force);
547 547
         unset($object);
548 548
 
549 549
         // Clear cache
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
              * @TODO: Change to if (!(class_exists($this->className) && $obj instanceof $this->className)) when going fully PHP5
575 575
              */
576 576
             if (!is_a($obj, $this->className)) {
577
-                $obj->setErrors(get_class($obj) . ' Differs from ' . $this->className);
577
+                $obj->setErrors(get_class($obj).' Differs from '.$this->className);
578 578
 
579 579
                 return false;
580 580
             }
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
         }
594 594
         foreach ($obj->cleanVars as $k => $v) {
595 595
             if ($obj->vars[$k]['data_type'] == XOBJ_DTYPE_INT) {
596
-                $cleanvars[$k] = (int)$v;
596
+                $cleanvars[$k] = (int) $v;
597 597
             } elseif (is_array($v)) {
598 598
                 $cleanvars[$k] = $this->db->quoteString(implode(',', $v));
599 599
             } else {
@@ -606,16 +606,16 @@  discard block
 block discarded – undo
606 606
         if ($obj->isNew()) {
607 607
             if (!is_array($this->keyName)) {
608 608
                 if ($cleanvars[$this->keyName] < 1) {
609
-                    $cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
609
+                    $cleanvars[$this->keyName] = $this->db->genId($this->table.'_'.$this->keyName.'_seq');
610 610
                 }
611 611
             }
612 612
             $ignore = '';
613 613
             if ($ignoreInsert) {
614 614
                 $ignore = 'IGNORE';
615 615
             }
616
-            $sql = "INSERT $ignore INTO " . $this->table . ' (' . implode(',', array_keys($cleanvars)) . ') VALUES (' . implode(',', array_values($cleanvars)) . ')';
616
+            $sql = "INSERT $ignore INTO ".$this->table.' ('.implode(',', array_keys($cleanvars)).') VALUES ('.implode(',', array_values($cleanvars)).')';
617 617
         } else {
618
-            $sql = 'UPDATE ' . $this->table . ' SET';
618
+            $sql = 'UPDATE '.$this->table.' SET';
619 619
             foreach ($cleanvars as $key => $value) {
620 620
                 if ((!is_array($this->keyName) && $key == $this->keyName) || (is_array($this->keyName) && in_array($key, $this->keyName))) {
621 621
                     continue;
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
                 if (isset($notfirst)) {
624 624
                     $sql .= ',';
625 625
                 }
626
-                $sql .= ' ' . $key . ' = ' . $value;
626
+                $sql .= ' '.$key.' = '.$value;
627 627
                 $notfirst = true;
628 628
             }
629 629
             if (is_array($this->keyName)) {
@@ -633,12 +633,12 @@  discard block
 block discarded – undo
633 633
                     if ($i > 0) {
634 634
                         $whereclause .= ' AND ';
635 635
                     }
636
-                    $whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
636
+                    $whereclause .= $this->keyName[$i].' = '.$obj->getVar($this->keyName[$i]);
637 637
                 }
638 638
             } else {
639
-                $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
639
+                $whereclause = $this->keyName.' = '.$obj->getVar($this->keyName);
640 640
             }
641
-            $sql .= ' WHERE ' . $whereclause;
641
+            $sql .= ' WHERE '.$whereclause;
642 642
         }
643 643
 
644 644
         if (false != $force) {
@@ -672,7 +672,7 @@  discard block
 block discarded – undo
672 672
      */
673 673
     public function updateAll($fieldname, $fieldvalue, $criteria = null, $force = false)
674 674
     {
675
-        $set_clause = $fieldname . ' = ';
675
+        $set_clause = $fieldname.' = ';
676 676
         if (is_numeric($fieldvalue)) {
677 677
             $set_clause .= $fieldvalue;
678 678
         } elseif (is_array($fieldvalue)) {
@@ -680,9 +680,9 @@  discard block
 block discarded – undo
680 680
         } else {
681 681
             $set_clause .= $this->db->quoteString($fieldvalue);
682 682
         }
683
-        $sql = 'UPDATE ' . $this->table . ' SET ' . $set_clause;
683
+        $sql = 'UPDATE '.$this->table.' SET '.$set_clause;
684 684
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
685
-            $sql .= ' ' . $criteria->renderWhere();
685
+            $sql .= ' '.$criteria->renderWhere();
686 686
         }
687 687
         if ($force) {
688 688
             $result = $this->db->queryF($sql);
@@ -730,8 +730,8 @@  discard block
 block discarded – undo
730 730
     public function deleteAll($criteria = null)
731 731
     {
732 732
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
733
-            $sql = 'DELETE FROM ' . $this->table;
734
-            $sql .= ' ' . $criteria->renderWhere();
733
+            $sql = 'DELETE FROM '.$this->table;
734
+            $sql .= ' '.$criteria->renderWhere();
735 735
             if (!$this->db->queryF($sql)) {
736 736
                 return false;
737 737
             }
@@ -777,15 +777,15 @@  discard block
 block discarded – undo
777 777
      */
778 778
     public function getDistincts($field, $criteria = null, $format = 's')
779 779
     {
780
-        require_once __DIR__ . '/lite.php';
780
+        require_once __DIR__.'/lite.php';
781 781
         $limit = $start = 0;
782
-        $sql   = 'SELECT ' . $this->keyName . ', ' . $field . ' FROM ' . $this->table;
782
+        $sql   = 'SELECT '.$this->keyName.', '.$field.' FROM '.$this->table;
783 783
         if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
784
-            $sql .= ' ' . $criteria->renderWhere();
784
+            $sql .= ' '.$criteria->renderWhere();
785 785
             $limit = $criteria->getLimit();
786 786
             $start = $criteria->getStart();
787 787
         }
788
-        $sql .= ' GROUP BY ' . $field . ' ORDER BY ' . $field;
788
+        $sql .= ' GROUP BY '.$field.' ORDER BY '.$field;
789 789
 
790 790
         $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
791 791
         $id         = $this->_getIdForCache($sql, $start, $limit);
@@ -843,7 +843,7 @@  discard block
 block discarded – undo
843 843
      */
844 844
     public function forceCacheClean()
845 845
     {
846
-        require_once __DIR__ . '/lite.php';
846
+        require_once __DIR__.'/lite.php';
847 847
         $Cache_Lite = new references_Cache_Lite($this->cacheOptions);
848 848
         $Cache_Lite->clean();
849 849
     }
Please login to merge, or discard this patch.