Completed
Push — tar-fix ( 591b33...b79eb2 )
by
unknown
66:32 queued 63:59
created

URL::RAWtoAR()   C

Complexity

Conditions 12
Paths 21

Size

Total Lines 78

Duplication

Lines 3
Ratio 3.85 %

Code Coverage

Tests 31
CRAP Score 19.9015

Importance

Changes 0
Metric Value
cc 12
nc 21
nop 2
dl 3
loc 78
ccs 31
cts 50
cp 0.62
crap 19.9015
rs 6.0533
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
class URL {
4
5
	/* replaces the URLs with the {ar*[/nls]} markers */
6 12
	public static function RAWtoAR($page, $nls="") {
7 12
		global $ARCurrent, $AR;
8 12
		$context = pobject::getContext();
9 12
		$me = $context["arCurrentObject"];
10 12
		if(!$me) {
11
			return $page;
12
		}
13
14 12
		$nls_match = "(/(?:".implode('|', array_keys($AR->nls->list))."))?";
15
		// FIXME: make the rest of the code also use the $nls_match2 expression
16
		// which doesn't match deel1/ as the nlsid 'de'
17 12
		$nls_match2 = "((".implode('|', array_keys($AR->nls->list)).")/)?";
18
19
		/* find and replace the current page */
20 12
		$find[] = "%\\Q".$me->make_url($me->path, "\\E{0}(".$nls_match.")\\Q")."\\E(user.edit.page.html|view.html)?%";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$find was never initialized. Although not strictly required by PHP, it is generally a good practice to add $find = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
21 12
		$repl[] = "{arCurrentPage\\1}";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$repl was never initialized. Although not strictly required by PHP, it is generally a good practice to add $repl = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
22 12
		$find[] = "%".preg_replace("%^https?://%", "https?\\Q://", $AR->host).$AR->dir->www."loader.php\\E(?:/-".$ARCurrent->session->id."-)?".$nls_match."\\Q".$me->path."\\E(user.edit.page.html|view.html)?%";
23 12
		$repl[] = "{arCurrentPage\\1}";
24 12
		$find[] = "%\\Q".$me->make_local_url($me->path, "\\E{0}(".$nls_match.")\\Q")."\\E(user.edit.page.html|view.html)?%";
25 12
		$repl[] = "{arCurrentPage\\1}";
26
		// change the site links
27 12
		$site = $me->currentsite();
28 12
		if ($site && $site !== '/') {
29 6
			$siteURL = $me->make_url($site, "");
30 6
			$rootURL = $me->make_url("/", "");
31
32
			/* use the rootURL to rebuild the site URL */
33 6
			$page = preg_replace_callback(
34 6
				"%\\Q$rootURL\\E".$nls_match2."\\Q".substr($site, 1)."\\E%",
35
				function ($matches) {
36
					return $matches[2] ? '{arSite/'.$matches[2].'}' : '{arSite}';
37 6
				},
38 6
				$page);
39
40
			/*
41
				a site has been configured so we can directly place
42
				the nls_match2 after the siteURL
43
			*/
44 6
			$page = preg_replace_callback(
45 6
				"%\\Q$siteURL\\E".$nls_match2."%",
46
				function ($matches) {
47
					return $matches[2] ? '{arSite/'.$matches[2].'}' : '{arSite}';
48 6
				},
49 6
				$page);
50 6
		}
51
52
		// change hardcoded links and images to use a placeholder for the root
53 12
		if ($me->store->get_config("root")) {
54
			$root = $me->store->get_config("root");
55 View Code Duplication
			if (substr($root, -3) == "/$nls") {
56
				$root = substr($root, 0, -3);
57
			}
58
			$find[] = "%(http[s]?://)?\\Q".$AR->host.$root."\\E".$nls_match."(/)%";
59
			$repl[] = "{arBase\\2}\\3";
60
61
			// This regexp triggers problems if there is no session
62
			// available (either because the user is not logged in, or the
63
			// site in configured with hideSessionFromUrl, so the check is
64
			// added to prevent random /ariadne/loader.php's to be replaced;
65
			if (!empty($ARCurrent->session->id) && strpos($root, "-" . $ARCurrent->session->id . "-") !== false) {
66
				$find[] = "%(http[s]?://)?\\Q".$root."\\E".$nls_match."(?)%";
67
				$repl[] = "{arBase\\2}\\3";
68
			}
69
		}
70
71
		// change hand pasted sources, which may or may not include session id's
72 12
		$find[] = "%(https?://)?\\Q".$AR->host.$AR->dir->www."loader.php\\E(/-".$ARCurrent->session->id."-)?(".$nls_match.")?/%";
73 12
		$repl[] = "{arBase\\3}/";
74 12
		if ($ARCurrent->session && $ARCurrent->session->id) {
75
			// check for other session id's:
76
			$find[] = "%/-[^-]{4}-%";
77
			$repl[] = "{arSession}";
78
			//$find[] = "%/-".$ARCurrent->session->id."-%";
79
			//$repl[] = "{arSession}";
80
		}
81
82 12
		return preg_replace($find, $repl, $page);
83
	}
84
85
	/* replaces the {ar*[/nls]} markers with valid URLs; if full is false, returns only the <body> content */
86 1
	public static function ARtoRAW($page) {
87 1
		global $ARCurrent, $AR;
88 1
		$context = pobject::getContext();
89 1
		$me = $context["arCurrentObject"];
90 1
		$find = array();
91 1
		$repl = array();
92
93 1
		if ($ARCurrent->session && $ARCurrent->session->id) {
94
			$session='/-'.$ARCurrent->session->id.'-';
95
		} else {
96 1
			$session='';
97
		}
98 1
		$site = $me->currentsite($me->path, true);
99 1
		$root = $me->store->get_config("root");
100 1
		if (substr($root, -3) == "/$me->nls") {
101
			$root = substr($root, 0, -3);
102
		}
103 1
		if ($site && $site !== '/') {
104
			$page = preg_replace_callback(
105
				"%\\{(?:arSite)(?:/([^}]+))?\\}\\Q\\E%",
106
				function ($matches) use ($me, $site) {
107
					return $me->make_url($site, $matches[1]);
108
				},
109
				$page
110
			);
111
112
			$page = preg_replace_callback(
113
				"%\\{(?:arRoot|arBase)(?:/([^}]+))?\\}\\Q".$site."\\E%",
114
				function ($matches) use ($me,$site) {
115
					return $me->make_url($site, $matches[1]);
116
				},
117
				$page
118
			);
119
		}
120 1
		$find[] = "%\\{arBase(/(?:[^}]+))?\\}%";
121 1
		$repl[] = $AR->host.$root."\\1";
122
123 1
		$find[] = "%\\{arRoot(/(?:[^}]+))?\\}%";
124 1
		$repl[] = $AR->host.$me->store->get_config("root")."\\1";
125
126 1
		$page = preg_replace_callback(
127 1
			"%\\{arCurrentPage(?:/([^}]+))?\\}%",
128 1
			function($matches) use ($me) {
129
				return $me->make_local_url('', $matches[1]);
130 1
			},
131
			$page
132 1
		);
133
134 1
		$find[] = "%\\{arSession\\}%";
135 1
		$repl[] = $session;
136
137 1
		if (class_exists('edit', false) && edit::getEditMode()) {
138
			$find[] = "%ar:editable=([^ ]+)%";
139
			$repl[] = "contentEditable=\\1";
140
		}
141
142 1
		$page = preg_replace($find, $repl, $page);
143
144
		// FIXME: Maybe do not process arCall when ESI is enabled?
145 1
		$page = URL::processArCall($page, $full);
0 ignored issues
show
Bug introduced by
The variable $full does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
146
147 1
		return $page;
148
	}
149
150 1
	protected static function processArCall($page, $full=false) {
0 ignored issues
show
Unused Code introduced by
The parameter $full is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
151 1
		global $ARCurrent, $AR;
152 1
		$context = pobject::getContext();
153 1
		$me = $context["arCurrentObject"];
154
155
		// parse {arCall:/path/to/object/template.phtml?a=1&b=2}
156
//		$regExp = '|\{arCall:(/(.*/)*)([^?]+)[?]([^}]*?)}|i';
157 1
		$regExp = '|\{arCall:(.*?)\}|i';
158
159 1
		while (preg_match($regExp, $page, $matches)) {
160 View Code Duplication
			if( !$settings ) {
0 ignored issues
show
Bug introduced by
The variable $settings does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
161
				if( !$ARCurrent->arEditorSettings) {
162
					$settings = $me->call("editor.ini");
163
				} else {
164
					$settings = $ARCurrent->arEditorSettings;
165
				}
166
			}
167
			ob_start();
168
				$parts	= explode("?", substr($matches[0], strlen('{arCall:'), -1), 2);
169
				$args	= $parts[1];
170
				$rest	= $parts[0];
171
				$template = "";
172
				if (substr($rest, -1) !== '/') {
173
					$template = basename($rest);
174
				}
175
				$path = $me->make_path( substr($rest, 0, -(strlen($template))) );
176
				if (is_array($settings['arCall'][$template])) {
177
					$cpaths = $settings['arCall'][$template]['paths'];
178
					if (is_array($cpaths)) {
179
						$mayCall = false;
180
						foreach ($cpaths as $cpath) {
181
							if (substr($cpath, -1) == '*') {
182
								$cpath = substr($cpath, 0, -1);
183
								if (substr($path, 0, strlen($cpath)) == $cpath) {
184
									$mayCall = true;
185
									break;
186
								}
187
							} else
188
							if ($path === $cpath) {
189
								$mayCall = true;
190
								break;
191
							}
192
						}
193
						if (!$mayCall) {
194
							error("no permission to call '$template' on '$path'");
195
						} else {
196
							$me->get($path, $template, $args);
197
						}
198
					} else {
199
						error("no paths were listed for '$template'");
200
					}
201
				} else {
202
					error("template '$template' is not in white list");
203
				}
204
				$output = ob_get_contents();
205
			ob_end_clean();
206
			$page = str_replace($matches[0], $output, $page);
207
		}
208
209 1
		return $page;
210
	}
211
}
212
213
class pinp_URL {
214
215
	public static function _RAWtoAR($page, $nls='') {
216
		return URL::RAWtoAR($page, $nls);
217
	}
218
219
	public static function _ARtoRAW($page) {
220
		return URL::ARtoRAW($page);
221
	}
222
}
223