forum_seo_post()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 11
rs 10
c 1
b 0
f 0
1
<?php declare(strict_types=1);
2
3
use XoopsModules\Newbb\{
4
    Helper,
5
    TopicHandler
6
};
7
8
/** @var Helper $helper */
9
/** @var TopicHandler $topicsHandler */
10
define('REAL_MODULE_NAME', 'modules/newbb');  //this is the Real Module directory
11
define('SEO_MODULE_NAME', 'modules/newbb');  //this is SEO Name for rewrite Hack
12
//ob_start('seo_urls');
13
/**
14
 * @param string $s
15
 *
16
 * @return null|string
17
 */
18
function seo_urls(string $s): ?string
19
{
20
    $XPS_URL     = str_replace('/', '\/', quotemeta((string) XOOPS_URL));
21
    $module_name = str_replace('/', '\/', quotemeta(SEO_MODULE_NAME));
22
23
    $search = [
24
        // Search URLs of modules' directry.
25
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/' . $module_name . '\/(index.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
26
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/' . $module_name . '\/(viewpost.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
27
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/' . $module_name . '\/(rss.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
28
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/' . $module_name . '\/(viewforum.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
29
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/' . $module_name . '\/(viewtopic.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
30
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/' . $module_name . '\/(newtopic.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
31
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/' . $module_name . '\/(.*)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
32
    ];
33
34
    $s = preg_replace_callback($search, 'replace_links', $s);
35
36
    return $s;
37
}
38
39
/**
40
 * @param array $matches
41
 * @return string
42
 */
43
function replace_links(array $matches): string
44
{
45
    switch ($matches[5]) {
46
        case 'index.php':
47
            $add_to_url = '';
48
            $req_string = $matches[6];
49
            if (!empty($matches[6])) {
50
                //                replacing cat=x
51
                if (preg_match('/cat=(\d+)/', (string) $matches[6], $mvars)) {
52
                    $add_to_url = 'c-' . $mvars[1] . '/' . forum_seo_cat((int)$mvars[1]) . '';
53
                    $req_string = preg_replace('/cat=\d+/', '', (string) $matches[6]);
54
                } else {
55
                    return $matches['0'];
56
                }
57
            }
58
            break;
59
        case 'viewpost.php':
60
            $add_to_url = '';
61
            $req_string = $matches[6];
62
            if (!empty($matches[6])) {
63
                //                replacing status=x
64
                if (preg_match('/status=([a-z]+)/', (string) $matches[6], $mvars)) {
65
                    $add_to_url = 'viewpost.php' . $matches[6];
66
                    $req_string = preg_replace('/status=([a-z])+/', '', (string) $matches[6]);
67
                } else {
68
                    return $matches['0'];
69
                }
70
            } else {
71
                $add_to_url = 'viewpost.php' . $matches[6];
72
            }
73
            break;
74
        case 'rss.php':
75
            $add_to_url = '';
76
            $req_string = $matches[6];
77
            if (!empty($matches[6])) {
78
                //                replacing c=x
79
                if (preg_match('/c=(\d+)/', (string) $matches[6], $mvars)) {
80
                    $add_to_url = 'rc-';
81
                    if ($mvars[1] > 0) {
82
                        $add_to_url .= $mvars[1] . '/' . forum_seo_cat((int)$mvars[1]) . '';
83
                    } else {
84
                        $add_to_url .= $mvars[1] . '/rss.html';
85
                    }
86
                    $req_string = preg_replace('/c=\d+/', '', (string) $matches[6]);
87
                } elseif (preg_match('/f=(\d+)/', (string) $matches[6], $mvars)) {
88
                    $add_to_url = 'rf-';
89
                    if ($mvars[1] > 0) {
90
                        $add_to_url .= $mvars[1] . '/' . forum_seo_forum((int)$mvars[1]) . '';
91
                    } else {
92
                        $add_to_url .= $mvars[1] . '/rss.html';
93
                    }
94
                    $req_string = preg_replace('/f=\d+/', '', (string) $matches[6]);
95
                } else {
96
                    return $matches['0'];
97
                }
98
                //$add_to_url .= 'rss-feed.html';
99
            }
100
            break;
101
        case 'viewforum.php':
102
            $add_to_url = '';
103
            $req_string = $matches[6];
104
            if (!empty($matches[6])) {
105
                //                replacing forum=x
106
                if (preg_match('/forum=(\d+)/', (string) $matches[6], $mvars)) {
107
                    $add_to_url = 'f-' . $mvars[1] . '/' . forum_seo_forum((int)$mvars[1]) . '';
108
                    $req_string = preg_replace('/forum=\d+/', '', (string) $matches[6]);
109
                } else {
110
                    return $matches['0'];
111
                }
112
            }
113
            break;
114
        case 'viewtopic.php':
115
            $add_to_url = '';
116
            $req_string = $matches[6];
117
            if (!empty($matches[6])) {
118
                //                replacing topic_id=x
119
                if (preg_match('/topic_id=(\d+)/', (string) $matches[6], $mvars)) {
120
                    $add_to_url = 't-' . $mvars[1] . '/' . forum_seo_topic((int)$mvars[1]) . '';
121
                    $req_string = preg_replace('/topic_id=\d+/', '', (string) $matches[6]);
122
                } //replacing post_id=x
123
                elseif (preg_match('/post_id=(\d+)/', (string) $matches[6], $mvars)) {
124
                    $add_to_url = 'p-' . $mvars[1] . '/' . forum_seo_post((int)$mvars[1]) . '';
125
                    $req_string = preg_replace('/post_id=\d+/', '', (string) $matches[6]);
126
                } else {
127
                    return $matches['0'];
128
                }
129
            }
130
            break;
131
        case 'print.php':
132
            $add_to_url = '';
133
            $req_string = $matches[6];
134
            if (!empty($matches[6])) {
135
                //                replacing topic_id=x
136
                if (preg_match('/topic_id=(\d+)/', (string) $matches[6], $mvars)) {
137
                    $add_to_url = 'pr-' . $mvars[1] . '/' . forum_seo_topic((int)$mvars[1]) . '';
138
                    $req_string = preg_replace('/topic_id=\d+/', '', (string) $matches[6]);
139
                } //replacing post_id=x
140
                elseif (preg_match('/post_id=(\d+)/', (string) $matches[6], $mvars)) {
141
                    $add_to_url = 'pr-' . $mvars[1] . '/' . forum_seo_post((int)$mvars[1]) . '';
142
                    $req_string = preg_replace('/post_id=\d+/', '', (string) $matches[6]);
143
                } else {
144
                    return $matches['0'];
145
                }
146
            }
147
            break;
148
        case 'makepdf.php':
149
            $add_to_url = '';
150
            $req_string = $matches[6];
151
            if (!empty($matches[6])) {
152
                //                replacing topic_id=x
153
                if (preg_match('/topic_id=(\d+)/', (string) $matches[6], $mvars)) {
154
                    $add_to_url = 'pdf-' . $mvars[1] . '/' . forum_seo_topic((int)$mvars[1]) . '';
155
                    $req_string = preg_replace('/topic_id=\d+/', '', (string) $matches[6]);
156
                } //replacing post_id=x
157
                elseif (preg_match('/post_id=(\d+)/', (string) $matches[6], $mvars)) {
158
                    $add_to_url = 'pdf-' . $mvars[1] . '/' . forum_seo_post((int)$mvars[1]) . '';
159
                    $req_string = preg_replace('/post_id=\d+/', '', (string) $matches[6]);
160
                } else {
161
                    return $matches['0'];
162
                }
163
            }
164
            break;
165
        default:
166
            $req_string = $matches[6];
167
            $add_to_url = $matches[5];
168
            //if ($add_to_url === '') $add_to_url ='index.php';
169
            break;
170
    }
171
    if ('?' === $req_string) {
172
        $req_string = '';
173
    }
174
    $ret = '<' . $matches[1] . $matches[2] . $matches[3] . '=' . $matches[4] . XOOPS_URL . '/' . SEO_MODULE_NAME . '/' . $add_to_url . $req_string . $matches[7] . $matches[8] . '>';
175
176
    //$ret = '<'.$matches[1].$matches[2].$matches[3].'='.$matches[4].XOOPS_URL.'/'.REAL_MODULE_NAME.'/'.$add_to_url.$req_string.$matches[7].$matches[8].'>';
177
    return $ret;
178
}
179
180
/**
181
 * @param int $_cat_id
182
 * @return bool|mixed
183
 */
184
function forum_seo_cat(int $_cat_id)
185
{
186
    xoops_load('XoopsCache');
187
    $key = 'newbb_seo_cat';
188
    $ret = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
189
    $ret = \XoopsCache::read($key);
190
    if ($ret) {
191
        $ret = @$ret[$_cat_id];
192
        if ($ret) {
193
            return $ret;
194
        }
195
    }
196
    $sql  = 'SELECT cat_id, cat_title FROM ' . $GLOBALS['xoopsDB']->prefix('newbb_categories');
197
    $result = $GLOBALS['xoopsDB']->query($sql);
198
    if (!$GLOBALS['xoopsDB']->isResultSet($result)) {
199
       \trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), E_USER_ERROR);
200
    }
201
    $_ret   = [];
202
    while (false !== ($res = $GLOBALS['xoopsDB']->fetchArray($result))) {
203
        $_ret[$res['cat_id']] = forum_seo_title($res['cat_title']);
204
    }
205
    XoopsCache::write($key, $_ret);
206
    $ret = \XoopsCache::read($key);
207
    $ret = $ret[$_cat_id];
208
209
    return $ret;
210
}
211
212
/**
213
 * @param int $_cat_id
214
 * @return bool|mixed
215
 */
216
function forum_seo_forum(int $_cat_id)
217
{
218
    xoops_load('XoopsCache');
219
    $key = 'newbb_seo_forum';
220
    $ret = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
221
    $ret = \XoopsCache::read($key);
222
    if ($ret) {
223
        $ret = @$ret[$_cat_id];
224
        if ($ret) {
225
            return $ret;
226
        }
227
    }
228
    $sql  = 'SELECT forum_id, forum_name    FROM ' . $GLOBALS['xoopsDB']->prefix('newbb_forums');
229
    $result = $GLOBALS['xoopsDB']->query($sql);
230
    if (!$GLOBALS['xoopsDB']->isResultSet($result)) {
231
        \trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), E_USER_ERROR);
232
    }
233
    $_ret   = [];
234
    while (false !== ($res = $GLOBALS['xoopsDB']->fetchArray($result))) {
235
        $_ret[$res['forum_id']] = forum_seo_title($res['forum_name']);
236
    }
237
    XoopsCache::write($key, $_ret);
238
    $ret = \XoopsCache::read($key);
239
    $ret = $ret[$_cat_id];
240
241
    return $ret;
242
}
243
244
/**
245
 * @param int $_cat_id
246
 * @return array|string|string[]|null
247
 */
248
function forum_seo_topic(int $_cat_id)
249
{
250
    $sql  = 'SELECT    topic_title    FROM ' . $GLOBALS['xoopsDB']->prefix('newbb_topics') . ' WHERE topic_id = ' . $_cat_id;
251
    $result = $GLOBALS['xoopsDB']->query($sql);
252
    if (!$GLOBALS['xoopsDB']->isResultSet($result)) {
253
        \trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), E_USER_ERROR);
254
    }
255
    $res    = $GLOBALS['xoopsDB']->fetchArray($result);
256
    $ret    = forum_seo_title($res['topic_title']);
257
258
    $moduleDirName = basename(__DIR__);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirName is dead and can be removed.
Loading history...
259
    /** @var TopicHandler $topicsHandler */
260
    $topicsHandler = Helper::getInstance()->getHandler('Topic');
261
    $criteria      = new \CriteriaCompo(new \Criteria('topic_id', (string)$_cat_id, '='));
262
    $fields        = ['topic_title'];
263
    $ret0          = $topicsHandler->getAll($criteria, $fields, false);
0 ignored issues
show
Unused Code introduced by
The assignment to $ret0 is dead and can be removed.
Loading history...
264
265
    return $ret;
266
}
267
268
/**
269
 * @param int $_cat_id
270
 * @return array|string|string[]|null
271
 */
272
function forum_seo_post(int $_cat_id)
273
{
274
    $sql  = 'SELECT    subject    FROM ' . $GLOBALS['xoopsDB']->prefix('newbb_posts') . ' WHERE post_id = ' . $_cat_id;
275
    $result = $GLOBALS['xoopsDB']->query($sql);
276
    if (!$GLOBALS['xoopsDB']->isResultSet($result)) {
277
        \trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), E_USER_ERROR);
278
    }
279
    $res    = $GLOBALS['xoopsDB']->fetchArray($result);
280
    $ret    = forum_seo_title($res['subject']);
281
282
    return $ret;
283
}
284
285
/**
286
 * @param string $title
287
 * @param bool   $withExt
288
 *
289
 * @return null|string
290
 */
291
function forum_seo_title(string $title = '', bool $withExt = true): ?string
292
{
293
    /**
294
     * if XOOPS ML is present, let's sanitize the title with the current language
295
     */
296
    $myts = \MyTextSanitizer::getInstance();
297
    if (method_exists($myts, 'formatForML')) {
298
        $title = $myts->formatForML($title);
299
    }
300
301
    // Convert string to lowercase
302
    // Coding of the string to avoid 500 errors in case of unexpected characters
303
    $title = rawurlencode(mb_strtolower((string) $title));
304
305
    // Transformation of punctuations
306
    //                 Tab     Space      !        "        #        %        &        '        (        )        ,        /        :        ;        <        =        >        ?        @        [        \        ]        ^        {        |        }        ~       .
307
    $pattern = [
308
        '/%09/',
309
        '/%20/',
310
        '/%21/',
311
        '/%22/',
312
        '/%23/',
313
        '/%25/',
314
        '/%26/',
315
        '/%27/',
316
        '/%28/',
317
        '/%29/',
318
        '/%2C/',
319
        '/%2F/',
320
        '/%3A/',
321
        '/%3B/',
322
        '/%3C/',
323
        '/%3D/',
324
        '/%3E/',
325
        '/%3F/',
326
        '/%40/',
327
        '/%5B/',
328
        '/%5C/',
329
        '/%5D/',
330
        '/%5E/',
331
        '/%7B/',
332
        '/%7C/',
333
        '/%7D/',
334
        '/%7E/',
335
        '/\./',
336
        '/%2A/',
337
    ];
338
    $rep_pat = [
339
        '-',
340
        '-',
341
        '',
342
        '',
343
        '',
344
        '-100',
345
        '',
346
        '-',
347
        '',
348
        '',
349
        '',
350
        '-',
351
        '',
352
        '',
353
        '',
354
        '-',
355
        '',
356
        '',
357
        '-at-',
358
        '',
359
        '-',
360
        '',
361
        '-',
362
        '',
363
        '-',
364
        '',
365
        '-',
366
        '',
367
        '',
368
    ];
369
    $title   = preg_replace($pattern, $rep_pat, $title);
370
371
    // Transformation of accented characters
372
    //                  è         é        ê         ë         ç         à         â         ä        î         ï        ù         ü         û         ô        ö
373
    $pattern = [
374
        '/%B0/',
375
        '/%E8/',
376
        '/%E9/',
377
        '/%EA/',
378
        '/%EB/',
379
        '/%E7/',
380
        '/%E0/',
381
        '/%E2/',
382
        '/%E4/',
383
        '/%EE/',
384
        '/%EF/',
385
        '/%F9/',
386
        '/%FC/',
387
        '/%FB/',
388
        '/%F4/',
389
        '/%F6/',
390
        '/%E3%BC/',
391
        '/%E3%96/',
392
        '/%E3%84/',
393
        '/%E3%9C/',
394
        '/%E3%FF/',
395
        '/%E3%B6/',
396
        '/%E3%A4/',
397
        '/%E3%9F/',
398
    ];
399
    $rep_pat = [
400
        '-',
401
        'e',
402
        'e',
403
        'e',
404
        'e',
405
        'c',
406
        'a',
407
        'a',
408
        'a',
409
        'i',
410
        'i',
411
        'u',
412
        'u',
413
        'u',
414
        'o',
415
        'o',
416
        'ue',
417
        'oe',
418
        'ae',
419
        'ue',
420
        'ss',
421
        'oe',
422
        'ae',
423
        'ss',
424
    ];
425
    $title   = preg_replace($pattern, $rep_pat, $title);
426
427
    /*$string = str_replace(' ', '-', $title);
428
    $string = iconv('utf-8', 'ascii//translit', $string);
429
    $string = preg_replace('#[^a-z0-9\-\.]#si', '', $string);
430
    $title  = str_replace('\/','', $string);  */
431
432
    if (($title === null ? 0 : count($title)) > 0) {
0 ignored issues
show
Bug introduced by
$title of type string is incompatible with the type Countable|array expected by parameter $value of count(). ( Ignorable by Annotation )

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

432
    if (($title === null ? 0 : count(/** @scrutinizer ignore-type */ $title)) > 0) {
Loading history...
433
        if ($withExt) {
434
            $title .= '.html';
435
        }
436
437
        return $title;
438
    }
439
440
    return '';
441
}
442