PluginProbe
Redirection / 5.3.3
Redirection v5.3.3
5.10.0 5.9.0 5.8.1 5.8.0 3.7.2 3.7.3 4.0 4.0.1 4.1 4.1.1 4.2 4.2.1 4.2.2 4.2.3 4.3 4.3.1 4.3.2 4.3.3 4.4 4.4.1 4.4.2 4.5 4.5.1 4.6.2 4.7.1 All 130 releases
redirection / models / url / url-encode.php

url-encode.php in Redirection 5.3.3, at models/url/url-encode.php

113 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 class Red_Url_Encode {
4 /**
5 * URL
6 *
7 * @var string
8 */
9 private $url;
10
11 /**
12 * Is regex?
13 *
14 * @var boolean
15 */
16 private $is_regex;
17
18 /**
19 * Constructor
20 *
21 * @param string $url URL.
22 * @param boolean $is_regex Is Regex.
23 */
24 public function __construct( $url, $is_regex = false ) {
25 // Remove any newlines
26 $url = preg_replace( "/[\r\n\t].*?$/s", '', $url );
27
28 // Remove invalid characters
29 $url = preg_replace( '/[^\PC\s]/u', '', $url );
30
31 // Make sure spaces are quoted
32 $url = str_replace( ' ', '%20', $url );
33 $url = str_replace( '%24', '$', $url );
34
35 $this->url = $url;
36 $this->is_regex = $is_regex;
37 }
38
39 /**
40 * URL encode some things, but other things can be passed through
41 *
42 * @return string
43 */
44 public function get_as_target() {
45 $allowed = [
46 '%2F' => '/',
47 '%3F' => '?',
48 '%3A' => ':',
49 '%3D' => '=',
50 '%26' => '&',
51 '%25' => '%',
52 '+' => '%20',
53 '%24' => '$',
54 '%23' => '#',
55 ];
56
57 $url = rawurlencode( $this->url );
58 $url = $this->replace_encoding( $url, $allowed );
59
60 return $this->encode_regex( $url );
61 }
62
63 /**
64 * Encode a URL
65 *
66 * @return string
67 */
68 public function get_as_source() {
69 $allowed = [
70 '%2F' => '/',
71 '%3F' => '?',
72 '+' => '%20',
73 '.' => '\\.',
74 ];
75
76 $url = $this->replace_encoding( rawurlencode( $this->url ), $allowed );
77 return $this->encode_regex( $url );
78 }
79
80
81 /**
82 * Replace encoded characters in a URL
83 *
84 * @param string $str Source string.
85 * @param array $allowed Allowed encodings.
86 * @return string
87 */
88 private function replace_encoding( $str, $allowed ) {
89 foreach ( $allowed as $before => $after ) {
90 $str = str_replace( $before, $after, $str );
91 }
92
93 return $str;
94 }
95
96 /**
97 * Encode a regex URL
98 *
99 * @param string $url URL.
100 * @return string
101 */
102 private function encode_regex( $url ) {
103 if ( $this->is_regex ) {
104 // No leading slash
105 $url = ltrim( $url, '/' );
106
107 // If pattern has a ^ at the start then ensure we don't have a slash immediatley after
108 $url = preg_replace( '@^\^/@', '^', $url );
109 }
110
111 return $url;
112 }
113 }