Completed
Push — master ( 6452b0...d576ea )
by Michael
05:58 queued 03:02
created

include/functions.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
// 
3
//  ------------------------------------------------------------------------ //
4
//                XOOPS - PHP Content Management System                      //
5
//                  Copyright (c) 2000-2016 XOOPS.org                        //
6
//                       <http://xoops.org/>                             //
7
//  ------------------------------------------------------------------------ //
8
//  This program is free software; you can redistribute it and/or modify     //
9
//  it under the terms of the GNU General Public License as published by     //
10
//  the Free Software Foundation; either version 2 of the License, or        //
11
//  (at your option) any later version.                                      //
12
//                                                                           //
13
//  You may not change or alter any portion of this comment or credits       //
14
//  of supporting developers from this source code or any supporting         //
15
//  source code which is considered copyrighted (c) material of the          //
16
//  original comment or credit authors.                                      //
17
//                                                                           //
18
//  This program is distributed in the hope that it will be useful,          //
19
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
20
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
21
//  GNU General Public License for more details.                             //
22
//                                                                           //
23
//  You should have received a copy of the GNU General Public License        //
24
//  along with this program; if not, write to the Free Software              //
25
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
26
//  ------------------------------------------------------------------------ //
27
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
28
29
/**
30
 * Returns a module's option
31
 *
32
 * Return's a module's option (for the news module)
33
 *
34
 * @package       News
35
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
36
 * @copyright (c) Hervé Thouzard
37
 *
38
 * @param string $option module option's name
39
 *
40
 * @param string $repmodule
41
 *
42
 * @return bool
43
 */
44
use WideImage\WideImage;
45
46
/**
47
 * @param        $option
48
 * @param string $repmodule
49
 * @return bool|mixed
50
 */
51
function news_getmoduleoption($option, $repmodule = 'news')
52
{
53
    global $xoopsModuleConfig, $xoopsModule;
54
    static $tbloptions = array();
55
    if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
56
        return $tbloptions[$option];
57
    }
58
59
    $retval = false;
60
    if (isset($xoopsModuleConfig) && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
61
        if (isset($xoopsModuleConfig[$option])) {
62
            $retval = $xoopsModuleConfig[$option];
63
        }
64
    } else {
65
        $module_handler = xoops_getHandler('module');
66
        $module         = $module_handler->getByDirname($repmodule);
67
        $config_handler = xoops_getHandler('config');
68
        if ($module) {
69
            $moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
70
            if (isset($moduleConfig[$option])) {
71
                $retval = $moduleConfig[$option];
72
            }
73
        }
74
    }
75
    $tbloptions[$option] = $retval;
76
77
    return $retval;
78
}
79
80
/**
81
 * Updates rating data in item table for a given item
82
 *
83
 * @package       News
84
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
85
 * @copyright (c) Hervé Thouzard
86
 * @param $storyid
87
 */
88
function news_updaterating($storyid)
89
{
90
    global $xoopsDB;
91
    $query       = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid;
92
    $voteresult  = $xoopsDB->query($query);
93
    $votesDB     = $xoopsDB->getRowsNum($voteresult);
94
    $totalrating = 0;
95
    while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
96
        $totalrating += $rating;
97
    }
98
    $finalrating = $totalrating / $votesDB;
99
    $finalrating = number_format($finalrating, 4);
100
    $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE storyid = %u', $xoopsDB->prefix('news_stories'), $finalrating, $votesDB, $storyid);
101
    $xoopsDB->queryF($sql);
102
}
103
104
/**
105
 * Internal function for permissions
106
 *
107
 * Returns a list of all the permitted topics Ids for the current user
108
 *
109
 * @param string $permtype
110
 *
111
 * @return array $topics    Permitted topics Ids
112
 *
113
 * @package       News
114
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
115
 * @copyright (c) Hervé Thouzard
116
 */
117
function news_MygetItemIds($permtype = 'news_view')
118
{
119
    global $xoopsUser;
120
    static $tblperms = array();
121
    if (is_array($tblperms) && array_key_exists($permtype, $tblperms)) {
122
        return $tblperms[$permtype];
123
    }
124
125
    $module_handler      = xoops_getHandler('module');
126
    $newsModule          = $module_handler->getByDirname('news');
127
    $groups              = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
128
    $gperm_handler       = xoops_getHandler('groupperm');
129
    $topics              = $gperm_handler->getItemIds($permtype, $groups, $newsModule->getVar('mid'));
130
    $tblperms[$permtype] = $topics;
131
132
    return $topics;
133
}
134
135
/**
136
 * @param $document
137
 *
138
 * @return mixed
139
 */
140
function news_html2text($document)
141
{
142
    // PHP Manual:: function preg_replace
143
    // $document should contain an HTML document.
144
    // This will remove HTML tags, javascript sections
145
    // and white space. It will also convert some
146
    // common HTML entities to their text equivalent.
147
148
    $search = array(
149
        "'<script[^>]*?>.*?</script>'si", // Strip out javascript
150
        "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
151
        "'([\r\n])[\s]+'", // Strip out white space
152
        "'&(quot|#34);'i", // Replace HTML entities
153
        "'&(amp|#38);'i",
154
        "'&(lt|#60);'i",
155
        "'&(gt|#62);'i",
156
        "'&(nbsp|#160);'i",
157
        "'&(iexcl|#161);'i",
158
        "'&(cent|#162);'i",
159
        "'&(pound|#163);'i",
160
        "'&(copy|#169);'i",
161
        "'&#(\d+);'e"); // evaluate as php
162
163
    $replace = array(
164
        '',
165
        '',
166
        "\\1",
167
        "\"",
168
        '&',
169
        '<',
170
        '>',
171
        ' ',
172
        chr(161),
173
        chr(162),
174
        chr(163),
175
        chr(169),
176
        "chr(\\1)");
177
178
    $text = preg_replace($search, $replace, $document);
179
180
    return $text;
181
}
182
183
/**
184
 * Is Xoops 2.3.x ?
185
 *
186
 * @return boolean need to say it ?
187
 */
188
function news_isX23()
189
{
190
    $x23 = false;
191
    $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
192
    if (substr($xv, 2, 1) >= '3') {
193
        $x23 = true;
194
    }
195
196
    return $x23;
197
}
198
199
/**
200
 * Retreive an editor according to the module's option "form_options"
201
 *
202
 * @package       News
203
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
204
 * @copyright (c) Hervé Thouzard
205
 * @param        $caption
206
 * @param        $name
207
 * @param string $value
208
 * @param string $width
209
 * @param string $height
210
 * @param string $supplemental
211
 * @return bool|XoopsFormDhtmlTextArea|XoopsFormEditor|XoopsFormFckeditor|XoopsFormHtmlarea|XoopsFormTextArea|XoopsFormTinyeditorTextArea
0 ignored issues
show
Should the return type not be XoopsFormEditor|XoopsFor...oopsFormWysiwygTextArea?

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

Loading history...
212
 */
213
function &news_getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
214
{
215
    $editor_option            = strtolower(news_getmoduleoption('form_options'));
216
    $editor                   = false;
217
    $editor_configs           = array();
218
    $editor_configs['name']   = $name;
219
    $editor_configs['value']  = $value;
220
    $editor_configs['rows']   = 35;
221
    $editor_configs['cols']   = 60;
222
    $editor_configs['width']  = '100%';
223
    $editor_configs['height'] = '350px';
224
    $editor_configs['editor'] = $editor_option;
225
226
    if (news_isX23()) {
227
        $editor = new XoopsFormEditor($caption, $name, $editor_configs);
228
229
        return $editor;
230
    }
231
232
    // Only for Xoops 2.0.x
233
    switch ($editor_option) {
234 View Code Duplication
        case 'fckeditor':
235
            if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
236
                require_once(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php');
237
                $editor = new XoopsFormFckeditor($caption, $name, $value);
238
            }
239
            break;
240
241 View Code Duplication
        case 'htmlarea':
242
            if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
243
                require_once(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php');
244
                $editor = new XoopsFormHtmlarea($caption, $name, $value);
245
            }
246
            break;
247
248
        case 'dhtmltextarea':
249
        case 'dhtml':
250
            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
251
            break;
252
253
        case 'textarea':
254
            $editor = new XoopsFormTextArea($caption, $name, $value);
255
            break;
256
257
        case 'tinyeditor':
258
        case 'tinymce':
259
            if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
260
                require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
261
                $editor = new XoopsFormTinyeditorTextArea(array('caption' => $caption, 'name' => $name, 'value' => $value, 'width' => '100%', 'height' => '400px'));
262
            }
263
            break;
264
265 View Code Duplication
        case 'koivi':
266
            if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
267
                require_once(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php');
268
                $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
269
            }
270
            break;
271
    }
272
273
    return $editor;
274
}
275
276
/**
277
 * Internal function
278
 *
279
 * @package       News
280
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
281
 * @copyright (c) Hervé Thouzard
282
 * @param $text
283
 * @return mixed
284
 */
285
function DublinQuotes($text)
286
{
287
    return str_replace("\"", ' ', $text);
288
}
289
290
/**
291
 * Creates all the meta datas :
292
 * - For Mozilla/Netscape and Opera the site navigation's bar
293
 * - The Dublin's Core Metadata
294
 * - The link for Firefox 2 micro summaries
295
 * - The meta keywords
296
 * - The meta description
297
 *
298
 * @package       News
299
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
300
 * @copyright (c) Hervé Thouzard
301
 * @param null $story
302
 */
303
function news_CreateMetaDatas($story = null)
304
{
305
    global $xoopsConfig, $xoTheme, $xoopsTpl;
306
    $content = '';
307
    $myts    = MyTextSanitizer::getInstance();
308
    include_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
309
310
    /**
311
     * Firefox and Opera Navigation's Bar
312
     */
313
    if (news_getmoduleoption('sitenavbar')) {
314
        $content .= sprintf("<link rel=\"Home\" title=\"%s\" href=\"%s/\" />\n", $xoopsConfig['sitename'], XOOPS_URL);
315
        $content .= sprintf("<link rel=\"Contents\" href=\"%s\" />\n", XOOPS_URL . '/modules/news/index.php');
316
        $content .= sprintf("<link rel=\"Search\" href=\"%s\" />\n", XOOPS_URL . '/search.php');
317
        $content .= sprintf("<link rel=\"Glossary\" href=\"%s\" />\n", XOOPS_URL . '/modules/news/archive.php');
318
        $content .= sprintf("<link rel=\"%s\" href=\"%s\" />\n", $myts->htmlSpecialChars(_NW_SUBMITNEWS), XOOPS_URL . '/modules/news/submit.php');
319
        $content .= sprintf("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"%s\" href=\"%s/\" />\n", $xoopsConfig['sitename'], XOOPS_URL . '/backend.php');
320
321
        // Create chapters
322
        include_once XOOPS_ROOT_PATH . '/class/tree.php';
323
        include_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
324
        $xt         = new NewsTopic();
325
        $allTopics  = $xt->getAllTopics(news_getmoduleoption('restrictindex'));
326
        $topic_tree = new XoopsObjectTree($allTopics, 'topic_id', 'topic_pid');
327
        $topics_arr = $topic_tree->getAllChild(0);
328
        foreach ($topics_arr as $onetopic) {
329
            $content .= sprintf("<link rel=\"Chapter\" title=\"%s\" href=\"%s\" />\n", $onetopic->topic_title(), XOOPS_URL . '/modules/news/index.php?storytopic=' . $onetopic->topic_id());
330
        }
331
    }
332
333
    /**
334
     * Meta Keywords and Description
335
     * If you have set this module's option to 'yes' and if the information was entered, then they are rendered in the page else they are computed
336
     */
337
    $meta_keywords = '';
338
    if (isset($story) && is_object($story)) {
339 View Code Duplication
        if (xoops_trim($story->keywords()) != '') {
340
            $meta_keywords = $story->keywords();
341
        } else {
342
            $meta_keywords = news_createmeta_keywords($story->hometext() . ' ' . $story->bodytext());
343
        }
344
        if (xoops_trim($story->description()) != '') {
345
            $meta_description = strip_tags($story->description);
346
        } else {
347
            $meta_description = strip_tags($story->title);
348
        }
349
        if (isset($xoTheme) && is_object($xoTheme)) {
350
            $xoTheme->addMeta('meta', 'keywords', $meta_keywords);
351
            $xoTheme->addMeta('meta', 'description', $meta_description);
352
        } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) { // Compatibility for old Xoops versions
353
            $xoopsTpl->assign('xoops_meta_keywords', $meta_keywords);
354
            $xoopsTpl->assign('xoops_meta_description', $meta_description);
355
        }
356
    }
357
358
    /**
359
     * Dublin Core's meta datas
360
     */
361
    if (news_getmoduleoption('dublincore') && isset($story) && is_object($story)) {
362
        $config_handler        = xoops_getHandler('config');
363
        $xoopsConfigMetaFooter = $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
364
        $content .= '<meta name="DC.Title" content="' . DublinQuotes($story->title()) . "\" />\n";
365
        $content .= '<meta name="DC.Creator" content="' . DublinQuotes($story->uname()) . "\" />\n";
366
        $content .= '<meta name="DC.Subject" content="' . DublinQuotes($meta_keywords) . "\" />\n";
367
        $content .= '<meta name="DC.Description" content="' . DublinQuotes($story->title()) . "\" />\n";
368
        $content .= '<meta name="DC.Publisher" content="' . DublinQuotes($xoopsConfig['sitename']) . "\" />\n";
369
        $content .= '<meta name="DC.Date.created" scheme="W3CDTF" content="' . date('Y-m-d', $story->created) . "\" />\n";
370
        $content .= '<meta name="DC.Date.issued" scheme="W3CDTF" content="' . date('Y-m-d', $story->published) . "\" />\n";
371
        $content .= '<meta name="DC.Identifier" content="' . XOOPS_URL . '/modules/news/article.php?storyid=' . $story->storyid() . "\" />\n";
372
        $content .= '<meta name="DC.Source" content="' . XOOPS_URL . "\" />\n";
373
        $content .= '<meta name="DC.Language" content="' . _LANGCODE . "\" />\n";
374
        $content .= '<meta name="DC.Relation.isReferencedBy" content="' . XOOPS_URL . '/modules/news/index.php?storytopic=' . $story->topicid() . "\" />\n";
375
        if (isset($xoopsConfigMetaFooter['meta_copyright'])) {
376
            $content .= '<meta name="DC.Rights" content="' . DublinQuotes($xoopsConfigMetaFooter['meta_copyright']) . "\" />\n";
377
        }
378
    }
379
380
    /**
381
     * Firefox 2 micro summaries
382
     */
383
    if (news_getmoduleoption('firefox_microsummaries')) {
384
        $content .= sprintf("<link rel=\"microsummary\" href=\"%s\" />\n", XOOPS_URL . '/modules/news/micro_summary.php');
385
    }
386
387
    if (isset($xoopsTpl) && is_object($xoopsTpl)) {
388
        $xoopsTpl->assign('xoops_module_header', $content);
389
    }
390
}
391
392
/**
393
 * Create the meta keywords based on the content
394
 *
395
 * @package       News
396
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
397
 * @copyright (c) Hervé Thouzard
398
 * @param $content
399
 * @return string
400
 */
401
function news_createmeta_keywords($content)
402
{
403
    include XOOPS_ROOT_PATH . '/modules/news/config.php';
404
    include_once XOOPS_ROOT_PATH . '/modules/news/class/blacklist.php';
405
    include_once XOOPS_ROOT_PATH . '/modules/news/class/registryfile.php';
406
407
    if (!$cfg['meta_keywords_auto_generate']) {
408
        return '';
409
    }
410
    $registry = new news_registryfile('news_metagen_options.txt');
411
    //    $tcontent = '';
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
412
    $tcontent = $registry->getfile();
413 View Code Duplication
    if (xoops_trim($tcontent) != '') {
414
        list($keywordscount, $keywordsorder) = explode(',', $tcontent);
415
    } else {
416
        $keywordscount = $cfg['meta_keywords_count'];
417
        $keywordsorder = $cfg['meta_keywords_order'];
418
    }
419
420
    $tmp = array();
421
    // Search for the "Minimum keyword length"
422
    if (isset($_SESSION['news_keywords_limit'])) {
423
        $limit = $_SESSION['news_keywords_limit'];
424
    } else {
425
        $config_handler                  = xoops_getHandler('config');
426
        $xoopsConfigSearch               = $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
427
        $limit                           = $xoopsConfigSearch['keyword_min'];
428
        $_SESSION['news_keywords_limit'] = $limit;
429
    }
430
    $myts            = MyTextSanitizer::getInstance();
431
    $content         = str_replace('<br />', ' ', $content);
432
    $content         = $myts->undoHtmlSpecialChars($content);
433
    $content         = strip_tags($content);
434
    $content         = strtolower($content);
435
    $search_pattern  = array('&nbsp;', "\t", "\r\n", "\r", "\n", ',', '.', "'", ';', ':', ')', '(', '"', '?', '!', '{', '}', '[', ']', '<', '>', '/', '+', '-', '_', '\\', '*');
436
    $replace_pattern = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
437
    $content         = str_replace($search_pattern, $replace_pattern, $content);
438
    $keywords        = explode(' ', $content);
439
    switch ($keywordsorder) {
440
        case 0: // Ordre d'apparition dans le texte
441
            $keywords = array_unique($keywords);
442
            break;
443
        case 1: // Ordre de fréquence des mots
444
            $keywords = array_count_values($keywords);
445
            asort($keywords);
446
            $keywords = array_keys($keywords);
447
            break;
448
        case 2: // Ordre inverse de la fréquence des mots
449
            $keywords = array_count_values($keywords);
450
            arsort($keywords);
451
            $keywords = array_keys($keywords);
452
            break;
453
    }
454
    // Remove black listed words
455
    $metablack = new news_blacklist();
456
    $words     = $metablack->getAllKeywords();
457
    $keywords  = $metablack->remove_blacklisted($keywords);
458
459
    foreach ($keywords as $keyword) {
460
        if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
461
            $tmp[] = $keyword;
462
        }
463
    }
464
    $tmp = array_slice($tmp, 0, $keywordscount);
465
    if (count($tmp) > 0) {
466
        return implode(',', $tmp);
467
    } else {
468
        if (!isset($config_handler) || !is_object($config_handler)) {
469
            $config_handler = xoops_getHandler('config');
470
        }
471
        $xoopsConfigMetaFooter = $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
472
        if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
473
            return $xoopsConfigMetaFooter['meta_keywords'];
474
        } else {
475
            return '';
476
        }
477
    }
478
}
479
480
/**
481
 * Remove module's cache
482
 *
483
 * @package       News
484
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
485
 * @copyright (c) Hervé Thouzard
486
 */
487
function news_updateCache()
488
{
489
    global $xoopsModule;
490
    $folder  = $xoopsModule->getVar('dirname');
491
    $tpllist = array();
492
    include_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
493
    include_once XOOPS_ROOT_PATH . '/class/template.php';
494
    $tplfile_handler = xoops_getHandler('tplfile');
495
    $tpllist         = $tplfile_handler->find(null, null, null, $folder);
496
    $xoopsTpl        = new XoopsTpl();
497
    xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
498
499
    // Remove cache for each page.
500
    foreach ($tpllist as $onetemplate) {
501
        if ($onetemplate->getVar('tpl_type') === 'module') {
502
            // 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
503
            $files_del = array();
504
            $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
505
            if (count($files_del) > 0) {
506
                foreach ($files_del as $one_file) {
507
                    unlink($one_file);
508
                }
509
            }
510
        }
511
    }
512
}
513
514
/**
515
 * Verify that a mysql table exists
516
 *
517
 * @package       News
518
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
519
 * @copyright (c) Hervé Thouzard
520
 * @param $tablename
521
 * @return bool
522
 */
523
function news_TableExists($tablename)
524
{
525
    global $xoopsDB;
526
    $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
527
528
    return ($xoopsDB->getRowsNum($result) > 0);
529
}
530
531
/**
532
 * Verify that a field exists inside a mysql table
533
 *
534
 * @package       News
535
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
536
 * @copyright (c) Hervé Thouzard
537
 * @param $fieldname
538
 * @param $table
539
 * @return bool
540
 */
541
function news_FieldExists($fieldname, $table)
542
{
543
    global $xoopsDB;
544
    $result = $xoopsDB->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
545
546
    return ($xoopsDB->getRowsNum($result) > 0);
547
}
548
549
/**
550
 * Add a field to a mysql table
551
 *
552
 * @package       News
553
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
554
 * @copyright (c) Hervé Thouzard
555
 * @param $field
556
 * @param $table
557
 * @return
558
 */
559
function news_AddField($field, $table)
560
{
561
    global $xoopsDB;
562
    $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
563
564
    return $result;
565
}
566
567
/**
568
 * Verify that the current user is a member of the Admin group
569
 */
570
function news_is_admin_group()
571
{
572
    global $xoopsUser, $xoopsModule;
573
    if (is_object($xoopsUser)) {
574
        if (in_array('1', $xoopsUser->getGroups())) {
575
            return true;
576
        } else {
577
            if ($xoopsUser->isAdmin($xoopsModule->mid())) {
578
                return true;
579
            } else {
580
                return false;
581
            }
582
        }
583
    } else {
584
        return false;
585
    }
586
}
587
588
/**
589
 * Verify if the current "user" is a bot or not
590
 *
591
 * If you have a problem with this function, insert the folowing code just before the line if (isset($_SESSION['news_cache_bot'])) { :
592
 * return false;
593
 *
594
 * @package       News
595
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
596
 * @copyright (c) Hervé Thouzard
597
 */
598
function news_isbot()
599
{
600
    if (isset($_SESSION['news_cache_bot'])) {
601
        return $_SESSION['news_cache_bot'];
602
    } else {
603
        // Add here every bot you know separated by a pipe | (not matter with the upper or lower cases)
604
        // If you want to see the result for yourself, add your navigator's user agent at the end (mozilla for example)
605
        $botlist      = 'AbachoBOT|Arachnoidea|ASPSeek|Atomz|cosmos|crawl25-public.alexa.com|CrawlerBoy Pinpoint.com|Crawler|DeepIndex|EchO!|exabot|Excalibur Internet Spider|FAST-WebCrawler|Fluffy the spider|GAIS Robot/1.0B2|GaisLab data gatherer|Google|Googlebot-Image|googlebot|Gulliver|ia_archiver|Infoseek|Links2Go|Lycos_Spider_(modspider)|Lycos_Spider_(T-Rex)|MantraAgent|Mata Hari|Mercator|MicrosoftPrototypeCrawler|[email protected]|MSNBOT|NEC Research Agent|NetMechanic|Nokia-WAPToolkit|nttdirectory_robot|Openfind|Oracle Ultra Search|PicoSearch|Pompos|Scooter|Slider_Search_v1-de|Slurp|Slurp.so|SlySearch|Spider|Spinne|SurferF3|Surfnomore Spider|suzuran|teomaagent1|TurnitinBot|Ultraseek|VoilaBot|vspider|W3C_Validator|Web Link Validator|WebTrends|WebZIP|whatUseek_winona|WISEbot|Xenu Link Sleuth|ZyBorg';
606
        $botlist      = strtoupper($botlist);
607
        $currentagent = strtoupper(xoops_getenv('HTTP_USER_AGENT'));
608
        $retval       = false;
609
        $botarray     = explode('|', $botlist);
610
        foreach ($botarray as $onebot) {
611
            if (false !== strpos($currentagent, $onebot)) {
612
                $retval = true;
613
                break;
614
            }
615
        }
616
    }
617
    $_SESSION['news_cache_bot'] = $retval;
618
619
    return $retval;
620
}
621
622
/**
623
 * Create an infotip
624
 *
625
 * @package       News
626
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
627
 * @copyright (c) Hervé Thouzard
628
 * @param $text
629
 * @return null
630
 */
631
function news_make_infotips($text)
632
{
633
    $infotips = news_getmoduleoption('infotips');
634
    if ($infotips > 0) {
635
        $myts = MyTextSanitizer::getInstance();
636
637
        return $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
638
    }
639
640
    return null;
641
}
642
643
/**
644
 * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
645
 *           <amos dot robinson at gmail dot com>
646
 * @param $string
647
 * @return string
648
 */
649
function news_close_tags($string)
650
{
651
    // match opened tags
652
    if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
653
        $start_tags = $start_tags[1];
654
        // match closed tags
655
        if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
656
            $complete_tags = array();
657
            $end_tags      = $end_tags[1];
658
659
            foreach ($start_tags as $key => $val) {
660
                $posb = array_search($val, $end_tags);
661
                if (is_int($posb)) {
662
                    unset($end_tags[$posb]);
663
                } else {
664
                    $complete_tags[] = $val;
665
                }
666
            }
667
        } else {
668
            $complete_tags = $start_tags;
669
        }
670
671
        $complete_tags = array_reverse($complete_tags);
672
        for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
673
            $string .= '</' . $complete_tags[$i] . '>';
674
        }
675
    }
676
677
    return $string;
678
}
679
680
/**
681
 * Smarty truncate_tagsafe modifier plugin
682
 *
683
 * Type:     modifier<br>
684
 * Name:     truncate_tagsafe<br>
685
 * Purpose:  Truncate a string to a certain length if necessary,
686
 *           optionally splitting in the middle of a word, and
687
 *           appending the $etc string or inserting $etc into the middle.
688
 *           Makes sure no tags are left half-open or half-closed
689
 *           (e.g. "Banana in a <a...")
690
 *
691
 * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
692
 *           <amos dot robinson at gmail dot com>
693
 *
694
 * @param string
695
 * @param integer
696
 * @param string
697
 * @param boolean
698
 * @param boolean
699
 *
700
 * @return string
701
 */
702
function news_truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
703
{
704
    if ($length == 0) {
705
        return '';
706
    }
707
    if (strlen($string) > $length) {
708
        $length -= strlen($etc);
709
        if (!$break_words) {
710
            $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
711
            $string = preg_replace('/<[^>]*$/', '', $string);
712
            $string = news_close_tags($string);
713
        }
714
715
        return $string . $etc;
716
    } else {
717
        return $string;
718
    }
719
}
720
721
/**
722
 * Resize a Picture to some given dimensions (using the wideImage library)
723
 *
724
 * @param string  $src_path      Picture's source
725
 * @param string  $dst_path      Picture's destination
726
 * @param integer $param_width   Maximum picture's width
727
 * @param integer $param_height  Maximum picture's height
728
 * @param boolean $keep_original Do we have to keep the original picture ?
729
 * @param string  $fit           Resize mode (see the wideImage library for more information)
730
 *
731
 * @return bool
732
 */
733
function news_resizePicture($src_path, $dst_path, $param_width, $param_height, $keep_original = false, $fit = 'inside')
734
{
735
//    require_once XOOPS_PATH . '/vendor/wideimage/WideImage.php';
736
    $resize            = true;
737
    $pictureDimensions = getimagesize($src_path);
738
    if (is_array($pictureDimensions)) {
739
        $pictureWidth  = $pictureDimensions[0];
740
        $pictureHeight = $pictureDimensions[1];
741
        if ($pictureWidth < $param_width && $pictureHeight < $param_height) {
742
            $resize = false;
743
        }
744
    }
745
746
    $img = WideImage::load($src_path);
747
    if ($resize) {
748
        $result = $img->resize($param_width, $param_height, $fit);
749
        $result->saveToFile($dst_path);
750
    } else {
751
        @copy($src_path, $dst_path);
752
    }
753
    if (!$keep_original) {
754
        @unlink($src_path);
755
    }
756
757
    return true;
758
}
759