Passed
Push — master ( 188361...fd3319 )
by Michael
03:02
created

replaceLinks()   B

Complexity

Conditions 8
Paths 12

Size

Total Lines 39
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 26
c 0
b 0
f 0
dl 0
loc 39
rs 8.4444
cc 8
nc 12
nop 1
1
<?php
2
3
declare(strict_types=1);
4
/*
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
 */
13
14
/**
15
 * @copyright    XOOPS Project (https://xoops.org)
16
 * @license      GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
17
 * @author       XOOPS Development Team
18
 * @author       Pascal Le Boustouller: original author ([email protected])
19
 * @author       Luc Bizet (www.frxoops.org)
20
 * @author       jlm69 (www.jlmzone.com)
21
 * @author       mamba (www.xoops.org)
22
 */
23
/////////////////////////////////////
24
// AdsLight UrlRewrite By Nikita   //
25
// http://www.aideordi.com         //
26
/////////////////////////////////////
27
28
define('REAL_MODULE_NAME', 'adslight');
29
define('SEO_MODULE_NAME', 'annonces');
30
31
ob_start('seo_urls');
32
33
/**
34
 * @param $s
35
 *
36
 * @return string|string[]|null
37
 */
38
function seo_urls($s)
39
{
40
    $XPS_URL = str_replace('/', '\/', quotemeta(XOOPS_URL));
41
    $s       = adslight_absolutize($s); // Fix URLs and HTML.
42
43
    $module_name = REAL_MODULE_NAME;
44
45
    $search = [
46
        // Search URLs of modules' directry.
47
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/modules\/' . $module_name . '\/(viewcats.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
48
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/modules\/' . $module_name . '\/(viewads.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
49
        '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})' . $XPS_URL . '\/modules\/' . $module_name . '\/(index.php)([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
50
        //    '/<(a|meta)([^>]*)(href|url)=([\'\"]{0,1})'.$XPS_URL.'\/modules\/'.$module_name.'\/()([^>\'\"]*)([\'\"]{1})([^>]*)>/i',
51
    ];
52
53
    return preg_replace_callback($search, 'replaceLinks', $s);
54
}
55
56
/**
57
 * @param $matches
58
 * @return string
59
 */
60
function replaceLinks($matches): string
61
{
62
    $req_string = [];
63
    $add_to_url = '';
64
    switch ($matches[5]) {
65
        case 'viewcats.php':
66
            //            $add_to_url = '';
67
            $req_string = $matches[6];
68
            if (!empty($matches[6])) {
69
                //              replacing cid=x
70
                if (preg_match('/cid=(\d+)/', $matches[6], $mvars)) {
71
                    $add_to_url = 'c' . $mvars[1] . '/' . adslight_seo_cat($mvars[1]) . '.html';
72
                    $req_string = preg_replace('/cid=\d+/', '', $matches[6]);
73
                } else {
74
                    return $matches['0'];
75
                }
76
            }
77
            break;
78
        case 'viewads.php':
79
            //            $add_to_url = '';
80
            $req_string = $matches[6];
81
            if (!empty($matches[6])) {
82
                //              replacing lid=x
83
                if (preg_match('/lid=(\d+)/', $matches[6], $mvars)) {
84
                    $add_to_url = 'p' . $mvars[1] . '/' . adslight_seo_titre($mvars[1]) . '.html';
85
                    $req_string = preg_replace('/lid=\d+/', '', $matches[6]);
86
                } else {
87
                    return $matches['0'];
88
                }
89
            }
90
            break;
91
        default:
92
            break;
93
    }
94
    if ('?' === $req_string) {
95
        $req_string = '';
96
    }
97
98
    return '<' . $matches[1] . $matches[2] . $matches[3] . '=' . $matches[4] . XOOPS_URL . '/' . SEO_MODULE_NAME . '/' . $add_to_url . $req_string . $matches[7] . $matches[8] . '>';
99
}
100
101
/**
102
 * @param $cid
103
 *
104
 * @return string|array<string>|null
105
 */
106
function adslight_seo_cat($cid)
107
{
108
    /** @var \XoopsMySQLDatabase $xoopsDB */
109
    $xoopsDB = \XoopsDatabaseFactory::getDatabaseConnection();
110
    $sql     = ' SELECT title FROM ' . $xoopsDB->prefix('adslight_categories') . ' WHERE cid = ' . $cid . ' ';
111
    $result  = $xoopsDB->query($sql);
112
    $res     = $xoopsDB->fetchArray($result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchArray() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

112
    $res     = $xoopsDB->fetchArray(/** @scrutinizer ignore-type */ $result);
Loading history...
113
114
    return adslight_seo_title($res['title']);
115
}
116
117
/**
118
 * @param $lid
119
 *
120
 * @return string|array<string>|null
121
 */
122
function adslight_seo_titre($lid)
123
{
124
    /** @var \XoopsMySQLDatabase $xoopsDB */
125
    $xoopsDB = \XoopsDatabaseFactory::getDatabaseConnection();
126
    $sql     = ' SELECT title FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid = ' . $lid . ' ';
127
    $result  = $xoopsDB->query($sql);
128
    $res     = $xoopsDB->fetchArray($result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type boolean; however, parameter $result of XoopsMySQLDatabase::fetchArray() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

128
    $res     = $xoopsDB->fetchArray(/** @scrutinizer ignore-type */ $result);
Loading history...
129
130
    return adslight_seo_title($res['title']);
131
}
132
133
/**
134
 * @param string $title
135
 * @param bool   $withExt
136
 *
137
 * @return string|array<string>|null
138
 */
139
function adslight_seo_title($title = '', $withExt = false)
140
{
141
    /**
142
     * if XOOPS ML is present, let's sanitize the title with the current language
143
     */
144
    $myts = \MyTextSanitizer::getInstance();
145
    if (method_exists($myts, 'formatForML')) {
146
        $title = $myts->formatForML($title);
147
    }
148
149
    // Transformation de la chaine en minuscule
150
    // String encoding to avoid 500 errors in case of unforeseen characters
151
    $title = rawurlencode(mb_strtolower($title));
152
153
    // Transformation des ponctuations
154
    //                 Tab     Space      !        "        #        %        &        '        (        )        ,        /        :        ;        <        =        >        ?        @        [        \        ]        ^        {        |        }        ~       .                 +
155
    $pattern = [
156
        '/%09/', // Tab
157
        '/%20/', // Space
158
        '/%21/', // !
159
        '/%22/', // "
160
        '/%23/', // #
161
        '/%25/', // %
162
        '/%26/', // &
163
        '/%27/', // '
164
        '/%28/', // (
165
        '/%29/', // )
166
        '/%2C/', // ,
167
        '/%2F/', // /
168
        '/%3A/', // :
169
        '/%3B/', // ;
170
        '/%3C/', // <
171
        '/%3D/', // =
172
        '/%3E/', // >
173
        '/%3F/', // ?
174
        '/%40/', // @
175
        '/%5B/', // [
176
        '/%5C/', // \
177
        '/%5D/', // ]
178
        '/%5E/', // ^
179
        '/%7B/', // {
180
        '/%7C/', // |
181
        '/%7D/', // }
182
        '/%7E/', // ~
183
        '/\./', // .
184
        '/%2A/',
185
        '/%2B/',
186
        '/quot/',
187
    ];
188
    $rep_pat = [
189
        '-',
190
        '-',
191
        '',
192
        '',
193
        '',
194
        '-100',
195
        '',
196
        '-',
197
        '',
198
        '',
199
        '',
200
        '-',
201
        '',
202
        '',
203
        '',
204
        '-',
205
        '',
206
        '',
207
        '-at-',
208
        '',
209
        '-',
210
        '',
211
        '-',
212
        '',
213
        '-',
214
        '',
215
        '-',
216
        '',
217
        '',
218
        '+',
219
        '',
220
    ];
221
    $title   = preg_replace($pattern, $rep_pat, $title);
222
223
    // Transformation of characters with accents
224
    //                  °        è        é        ê        ë        ç        à        â        ä        î        ï        ù        ü        û        ô        ö
225
    $pattern = [
226
        '/%B0/',        // °
227
        '/%E8/',        // è
228
        '/%E9/',        // é
229
        '/%EA/',        // ê
230
        '/%EB/',        // ë
231
        '/%E7/',        // ç
232
        '/%E0/',        // à
233
        '/%E2/',        // â
234
        '/%E4/',        // ä
235
        '/%EE/',        // î
236
        '/%EF/',        // ï
237
        '/%F9/',        // ù
238
        '/%FC/',        // ü
239
        '/%FB/',        // û
240
        '/%F4/',        // ô
241
        '/%F6/',        // ö
242
        '/%E3%A8/',
243
        '/%E3%A9/',
244
        '/%E3%A0/',
245
        '/%E3%AA/',
246
        '/%E3%A2/',
247
        '/a%80%9C/',
248
        '/a%80%9D/',
249
        '/%E3%A7/',
250
    ];
251
    $rep_pat = [
252
        '-',
253
        'e',
254
        'e',
255
        'e',
256
        'e',
257
        'c',
258
        'a',
259
        'a',
260
        'a',
261
        'i',
262
        'i',
263
        'u',
264
        'u',
265
        'u',
266
        'o',
267
        'o',
268
        'e',
269
        'e',
270
        'a',
271
        'e',
272
        'a',
273
        '-',
274
        '-',
275
        'c',
276
    ];
277
    $title   = preg_replace($pattern, $rep_pat, $title);
278
279
    if (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

279
    if (count(/** @scrutinizer ignore-type */ $title) > 0) {
Loading history...
280
        if ($withExt) {
281
            $title .= '.html';
282
        }
283
284
        return $title;
285
    }
286
287
    return '';
288
}
289
290
/**
291
 * @param $s
292
 *
293
 * @return string|string[]|null
294
 */
295
function adslight_absolutize($s)
296
{
297
    if (preg_match('/\/$/', $_SERVER['REQUEST_URI'])) {
298
        $req_dir = preg_replace('/\/$/', '', $_SERVER['REQUEST_URI']);
299
        $req_php = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $req_php is dead and can be removed.
Loading history...
300
    } else {
301
        $req_dir = dirname($_SERVER['REQUEST_URI']);
302
        $req_php = preg_replace('/.*(\/[a-zA-Z0-9_\-]+)\.php.*/', '\\1.php', $_SERVER['REQUEST_URI']);
303
    }
304
    $req_dir = '\\' === $req_dir || '/' === $req_dir ? '' : $req_dir;
305
    $dir_arr = explode('/', $req_dir);
306
    $m       = count($dir_arr) - 1;
307
    $d1      = @str_replace('/' . $dir_arr[$m], '', $req_dir);
308
    $d2      = @str_replace('/' . $dir_arr[$m - 1], '', $d1);
309
    $d3      = @str_replace('/' . $dir_arr[$m - 2], '', $d2);
310
    $d4      = @str_replace('/' . $dir_arr[$m - 3], '', $d3);
311
    $d5      = @str_replace('/' . $dir_arr[$m - 4], '', $d4);
0 ignored issues
show
Unused Code introduced by
The assignment to $d5 is dead and can be removed.
Loading history...
312
    $host    = 'http://' . $_SERVER['HTTP_HOST'];
313
    $in      = [
314
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([^\"\' >]+)([^>]*)>/i',
315
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([\"\']{1})\.\.\/\.\.\/\.\.\/([^\"\']*)([\"\']{1})([^>]*)>/i',
316
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([\"\']{1})\.\.\/\.\.\/([^\"\']*)([\"\']{1})([^>]*)>/i',
317
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([\"\']{1})\.\.\/([^\"\']*)([\"\']{1})([^>]*)>/i',
318
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([\"\']{1})\/([^\"\']*)([\"\']{1})([^>]*)>/i',
319
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([\"\']{1})\?([^\"\']*)([\"\']{1})([^>]*)>/i'//This dir
320
        ,
321
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([\"\']{1})([^#]{1}[^\/\"\'>]*)([\"\']{1})([^>]*)>/i',
322
        '/<([^>\?\&]*)(href|src|action|background|window\.location)=([\"\']{1})(?:\.\/)?([^\"\'\/:]*\/*)?([^\"\'\/:]*\/*)?([^\"\'\/:]*\/*)?([a-zA-Z0-9_\-]+)\.([^\"\'>]*)([\"\']{1})([^>]*)>/i',
323
        '/[^"\'a-zA-Z_0-9](window\.open|url)\(([\"\']{0,1})(?:\.\/)?([^\"\'\/]*)\.([^\"\'\/]+)([\"\']*)([^\)]*)/i',
324
        '/<meta([^>]*)url=([a-zA-Z0-9_\-]+)\.([^\"\'>]*)([\"\']{1})([^>]*)>/i',
325
    ];
326
    $out     = [
327
        '<\\1\\2="\\3"\\4>',
328
        '<\\1\\2=\\3' . $host . $d3 . '/\\4\\5\\6>',
329
        '<\\1\\2=\\3' . $host . $d2 . '/\\4\\5\\6>',
330
        '<\\1\\2=\\3' . $host . $d1 . '/\\4\\5\\6>',
331
        '<\\1\\2=\\3' . $host . '/\\4\\5\\6>',
332
        '<\\1\\2=\\3' . $host . $_SERVER['SCRIPT_NAME'] . '?\\4\\5\\6>'//This dir.
333
        ,
334
        '<\\1\\2=\\3' . $host . $req_dir . '/\\4\\5\\6\\7>',
335
        '<\\1\\2=\\3' . $host . $req_dir . '/\\4\\5\\6\\7.\\8\\9\\10>',
336
        '$1($2' . $host . $req_dir . '/$3.$4$5$6',
337
        '<meta$1url=' . $host . $req_dir . '/$2.$3$4$5>',
338
    ];
339
340
    return preg_replace($in, $out, $s);
341
}
342