Completed
Pull Request — master (#117)
by Robbert
09:05
created

ariadne_object::getConfig()   D

Complexity

Conditions 15
Paths 189

Size

Total Lines 75
Code Lines 47

Duplication

Lines 14
Ratio 18.67 %

Code Coverage

Tests 39
CRAP Score 22.0862

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 15
eloc 47
nc 189
nop 0
dl 14
loc 75
rs 4.9279
c 1
b 0
f 0
ccs 39
cts 57
cp 0.6842
crap 22.0862

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 38 and the first side effect is on line 36.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
    /******************************************************************
3
     pobject.phtml                                         Muze Ariadne
4
     ------------------------------------------------------------------
5
     Author: Muze ([email protected])
6
     Date: 31 october 2002
7
8
     Copyright 2002 Muze
9
10
     This file is part of Ariadne.
11
12
     Ariadne is free software; you can redistribute it and/or modify
13
     it under the terms of the GNU General Public License as published
14
     by the Free Software Foundation; either version 2 of the License,
15
     or (at your option) any later version.
16
17
     Ariadne is distributed in the hope that it will be useful,
18
     but WITHOUT ANY WARRANTY; without even the implied warranty of
19
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
     GNU General Public License for more details.
21
22
     You should have received a copy of the GNU General Public License
23
     along with Ariadne; if not, write to the Free Software
24
     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
25
     02111-1307  USA
26
27
    -------------------------------------------------------------------
28
29
     Class inheritance: 	pobject
30
     Description:
31
32
       This is the class definition file of the pobject class.
33
34
    ******************************************************************/
35
36
debug("pobject: Load","object");
37
38
abstract class ariadne_object extends object { // ariadne_object class definition
39
40
	public $store;
41
	public $path;
42
	public $data;
43
44 184
	public function init($store, $path, $data) {
45 184
		$this->store=$store;
46 184
		$this->path=$path;
47 184
		$this->data=$data;
48 184
		if ( !isset($this->data->config) ) {
49 28
			$this->data->config = new object();
50 14
		}
51 184
	}
52
53 184
	public function call($arCallFunction="view.html", $arCallArgs=array()) {
54
	/***********************************************************************
55
	  call tries to find the template ($arCallFunction) for the current
56
	  object. If it is not defined there, call will search the superclasses
57
	  until either it or the template 'default.phtml' is found.
58
59
	  $arCallFunction must be the name of a class or object template.
60
	    it can be prepended with "{classname}::". classname must be either
61
	    a valid ariadne class (derived from pobject). call()
62
	    will then try to find the template starting at the given classname.
63
		e.g.:
64
		call("pobject::view.html") will show the view.html template of
65
	      pobject, with the data of the current object.
66
67
	  variables available to templates:
68
	  local: arCallFunction, arCallArgs, arCallTemplate, data
69
	  global: AR, ARConfig, ARCurrent, ARBeenHere, ARnls
70
	***********************************************************************/
71 184
	global $AR, $ARConfig, $ARCurrent, $ARBeenHere, $ARnls;
72
73 184
		if ( $arCallFunction instanceof \Closure ) {
74 4
			$arCallFunctionName = 'Closure';
75 6
		} else {
76 184
			$arCallFunctionName = (string) $arCallFunction;
77
		}
78 184
		debug("pobject: ".$this->path.": call($arCallFunctionName, ".debug_serialize($arCallArgs).")","object","all","IN");
79
80
		// default to view.html
81 184
		if (!$arCallFunction) {
82 10
			$arCallFunction="view.html";
83
		}
84
		// clear previous results
85 184
		unset($ARCurrent->arResult);
86
87
		// callstack is needed for getvar()
88 184
		$ARCurrent->arCallStack[]=&$arCallArgs;
89
		// keep track of the context (php or pinp) in which the called template runs. call always sets it php, CheckConfig sets it to pinp if necessary.
90 184
		$this->pushContext( array(
91 184
			"arSuperContext" => array(),
92 184
			"arCurrentObject" => $this,
93 184
			"scope" => "php",
94 92
			"arCallFunction" => $arCallFunction
95 92
		) );
96
97
		// convert the deprecated urlencoded arguments to an array
98 184
		if (isset($arCallArgs) && is_string($arCallArgs)) {
99 184
			$ARCurrent->arTemp=$arCallArgs;
100 184
			$arCallArgs=array();
101 184
			parse_str($ARCurrent->arTemp, $arCallArgs);
102 92
		}
103
		// import the arguments in the current scope, but don't overwrite existing
104
		// variables.
105 184
		if (isset($arCallArgs) && is_array($arCallArgs)) {
106 184
			extract($arCallArgs,EXTR_SKIP);
107 92
		}
108
		// now find the initial nls selection (CheckConfig is needed for per
109
		// tree selected defaults)
110 184
		if ($ARCurrent->nls) {
111
			$this->reqnls=$ARCurrent->nls;
0 ignored issues
show
Bug introduced by
The property reqnls does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
112 184
		} else if (isset($ARConfig->cache[$this->path]) && $ARConfig->cache[$this->path]->nls->default) {
113 100
			$this->reqnls = $ARConfig->cache[$this->path]->nls->default;
114 50
		} else {
115 184
			$this->reqnls=$AR->nls->default;
116
		}
117 184
		if (isset($this->data->nls->list[$this->reqnls]) || !isset($this->data->nls)) {
118
			// the requested language is available
119 184
			$this->nls=$this->reqnls;
0 ignored issues
show
Bug introduced by
The property nls does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
120 184
			$nls=&$this->nls;
121 92
		} else {
122
			// the requested language is not available, use default of the
123
			// current object instead.
124
			$this->nls=$this->data->nls->default;
125 2
			$nls=&$this->nls;
126
		}
127 184
		if ($nls && isset($this->data->$nls)) {
128
			// now set the data and nlsdata pointers
129 132
			$this->nlsdata=$this->data->$nls;
0 ignored issues
show
Bug introduced by
The property nlsdata does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
130 132
			$nlsdata=&$this->nlsdata;
131 132
			$data=&$this->data;
132 66
		} else {
133
			// this object doesn't support nls data
134 184
			$this->nlsdata=$this->data;
135 184
			$nlsdata=&$this->data;
136 184
			$data=&$this->data;
137 2
		}
138 184
		if (isset($this->data->custom['none'])) {
139 6
			$customdata=$this->data->custom['none'];
140 4
		}
141 184
		if (isset($this->data->custom[$nls])) {
142
			$customnlsdata=$this->data->custom[$nls];
143
		}
144
145 184
		$arCallFunctionOrig = $arCallFunction;
146 184
		if (strpos($arCallFunctionName,"::")!==false) {
147
			// template of a specific class defined via call("class::template");
148 24
			list($arType, $arCallFunction)=explode("::",$arCallFunctionName);
149 24
			$temp = explode(":", $arType );
150 24
			if( count($temp) > 1 ) {
151
				$libname = $temp[0];
152
				$arType = $temp[1];
153 12
				$arCallFunction = $libname.":".$arCallFunction;
154
			}
155 12
		} else {
156 184
			$arType=$this->type;
0 ignored issues
show
Bug introduced by
The property type does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
157
		}
158
159 184
		if ( $arCallFunction instanceof \Closure ) {
160 4
			$context = $this->getContext(ARCALLINGCONTEXT);
161 4
			if ( $context["scope"] != "pinp" ) {
162
				$arResult = $arCallFunction($this );
163
			} else {
164 4
				if ( $this->CheckSilent('read') ) {
165 4
					$arResult = $arCallFunction($this);
166 2
				}
167
			}
168 2
		} else {
169 184
			if ($arCallFunction[0] === "#") {
170 10
				$ARCurrent->arCallClassTemplate = true;
171
				$arCallFunction = substr($arCallFunction, 1);
172
			} else {
173 184
				$ARCurrent->arCallClassTemplate = false;
174
			}
175
176 184
			if( $arCallFunction == "system.get.phtml" && ( $context = $this->getContext(ARCALLINGCONTEXT) ) && $context["scope"] != "pinp" ) {
177 34
				$arResult = $this;
178 16
			} else {
179 184
				$libtemplate = strpos($arCallFunction,":");
180 184
				$codedir = $this->store->get_config("code");
181
182
				// if it is a subtype object, disk templates do not exists,
183 184
				$subcpos = strpos($arType, '.');
184 184
				if ($subcpos !== false ) {
185
					// subtype, skip looking for templates
186 24
					$arSuper = substr($arType, 0, $subcpos);
187 24
					if(!isset($AR->superClass[$arType])){
188 4
						$AR->superClass[$arType]=$arSuper;
189 2
					}
190 24
					$arType=$arSuper;
191 12
				}
192
193 184
				while ($arType !== "ariadne_object") {
194
195
					// search for the template, stop at the root class ('ariadne_object')
196
					// (this should not happen, as pobject must have a 'default.phtml')
197 184
					$arCallTemplate=$codedir."templates/".$arType."/".$arCallFunction;
198 184
					if ($libtemplate === false && file_exists($arCallTemplate)) {
199
						//debug('found '.$arCallTemplate, 'all');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
200
						// template found
201 184
						$arCallFunction = $arCallFunctionOrig;
202 184
						include($arCallTemplate);
203 184
						break;
204 184
					} else if (file_exists($codedir."templates/".$arType."/default.phtml")) {
205
						//debug('found default.phtml', 'all');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
206
						// template not found, but we did find a 'default.phtml'
207 8
						include($this->store->get_config("code")."templates/".$arType."/default.phtml");
208 10
						break;
209 12
					} else {
210 184
						if (!($arSuper=$AR->superClass[$arType])) {
211
							// no template found, no default.phtml found, try superclass.
212
213 8
							if (!class_exists($arType, false)) {
214
								// the given class was not yet loaded, so do that now
215
								$this->store->newobject('','',$arType,new object);
216
							}
217 10
							$arSuper=get_parent_class($arType);
218
219 20
							$AR->superClass[$arType]=$arSuper;
220 4
						}
221 184
						$arType=$arSuper;
222 2
					}
223 92
				}
224
			}
225 2
		}
226 184
		array_pop($ARCurrent->arCallStack);
227 184
		$this->popContext();
228 184
		debug("pobject: call: end","all","all","OUT");
229 184
		if (isset($ARCurrent->arResult)) {
230
			// pinp templates can return results via putvar("arResult",$result);
231 20
			$arResult=$ARCurrent->arResult;
232 20
			unset($ARCurrent->arResult);
233 10
		}
234 184
		if (isset($arResult)) {
235
			// only do a return if we really have something to return
236 184
			return $arResult;
237
		}
238 24
	}
239
240 2
	public function ls($path="", $function="list.html", $args="") {
241 2
		$path=$this->store->make_path($this->path, $path);
242 2
		return $this->store->call($function, $args, $this->store->ls($path));
243 2
	}
244
245 56
	public function get($path, $function="view.html", $args="") {
246 56
		$path=$this->store->make_path($this->path, $path);
247 56
		return $this->store->call($function, $args, $this->store->get($path));
248 2
	}
249
250 6
	public function parents($path, $function="list.html", $args="", $top="") {
251
		/* FIXME: $this->store->parents is too slow when a lot of objects are in ariadne (2million+) */
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "$this->store->parents is too slow when a lot of objects are in ariadne (2million+) */"
Loading history...
252
		/* but this fix should be done in the store, not here */
253 4
		if (!$top) {
254 6
			$top = $this->currentsection();
255 2
		} else {
256 6
			$top = $this->store->make_path($this->path, $top);
257
		}
258
259 4
		$path=$this->store->make_path($this->path, $path);
260
261 4
		if ($path != $this->path ) {
262 4
			$target = current($this->get($path,"system.get.phtml"));
263 2
		} else {
264 4
			$target = $this;
265
		}
266
267 4
		$parents = array();
268 4
		if (strpos($target->path, $top) === 0) {
269 4
			$parents[] = $target;
270 4
			while ($target && $target->path != $top) {
271 4
				$target = current($target->get($target->parent, "system.get.phtml"));
272 4
				$parents[] = $target;
273 4
			}
274 2
		}
275 4
		$parents = array_reverse($parents);
276 4
		$result = array();
277 6
		foreach ($parents as $parent) {
278 4
			if ( $parent ) { // might not have read access to this object
279 4
				$result[] = $parent->call($function, $args);
280 2
			}
281 2
		}
282
283 4
		return $result;
284
	}
285
286 4
	public function find($path, $criteria, $function="list.html", $args="", $limit=100, $offset=0) {
287 4
		$path = $this->store->make_path($this->path, $path);
288 4
		$objects = $this->store->find($path, $criteria, $limit, $offset);
289 4
		if (!$this->store->error) {
290 4
			$result = $this->store->call($function, $args, $objects);
291 2 View Code Duplication
		} else {
292
			$this->error = ar::error( ''.$this->store->error, 1110, $this->store->error );
0 ignored issues
show
Bug introduced by
The property error does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
293
			$result = false;
294 2
		}
295 4
		return $result;
296
	}
297
298
	public function count_find($path='', $query='') {
299
		$path=$this->store->make_path($this->path, $path);
300
		if (method_exists($this->store, 'count_find')) {
301
			$result = $this->store->count_find($path, $query, 0);
302
		} else {
303
			$result = $this->store->count($this->store->find($path, $query, 0));
304
		}
305
		return $result;
306
	}
307
308
	public function count_ls($path) {
309
		return $this->store->count($this->store->ls($path));
310
	}
311
312 2
	private function saveMergeWorkflowResult($properties, $wf_result) {
313
		foreach ($wf_result as $wf_prop_name => $wf_prop) {
314
			foreach ($wf_prop as $wf_prop_index => $wf_prop_record) {
315
				if (!isset($wf_prop_record)) {
316
					unset($properties[$wf_prop_name][$wf_prop_index]);
317
				} else {
318
					$record = array();
319 View Code Duplication
					foreach ($wf_prop_record as $wf_prop_field => $wf_prop_value) {
320
						switch (gettype($wf_prop_value)) {
321 2
							case "integer":
322
							case "boolean":
323
							case "double":
324
								$value = $wf_prop_value;
325
								break;
326
							default:
327
								$value = $wf_prop_value;
328
								// backwards compatibility, store will do the escaping from now on
329
								// will be removed in the future
330
								if (substr($wf_prop_value, 0, 1) === "'" && substr($wf_prop_value, -1) === "'"
331
										&& "'".AddSlashes(StripSlashes(substr($wf_prop_value, 1, -1)))."'" == $wf_prop_value) {
332
									$value = stripSlashes(substr($wf_prop_value,1,-1));
333
									// todo add deprecated warning
334
								}
335
336 2
						}
337
						$record[$wf_prop_field] = $value;
338
					}
339
					$properties[$wf_prop_name][] = $record;
340
				}
341
			}
342
		}
343
344
		return $properties;
345
	}
346
347
	/*
348
		saves custom data
349
		returns properties for custom data
350
	*/
351 49
	private function saveCustomData($configcache, $properties) {
352 49
		$custom = $this->getdata("custom", "none");
353 48
		@parse_str($custom);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
354 48
		if (isset($custom) && is_array($custom)) {
355
			foreach($custom as $nls=>$entries){
356
				if (isset($entries) && is_array($entries)) {
357
					foreach ( $entries as $customkey => $customval ){
358
						$this->data->custom[$nls][$customkey] = $customval;
359
					}
360
				}
361
			}
362
		}
363
		// the above works because either $custom comes from the form entry, and parse_str returns an
364
		// array with the name $custom, or $custom comes from the object and is an array and as such
365
		// parse_str fails miserably thus keeping the array $custom intact.
366
367 48
		if (isset($this->data->custom) && is_array($this->data->custom)) {
368
			foreach($this->data->custom as $nls => $cdata) {
369
				foreach($cdata as $name => $value){
370
					// one index, this order (name, value, nls) ?
371
					if ($configcache->custom[$name]['containsHTML']) {
372
						$this->_load('mod_url.php');
373
						$value = URL::RAWtoAR($value, $nls);
374
						$this->data->custom[$nls][$name] = $value;
375
					}
376
					if ($configcache->custom[$name]['property']) {
377
						if (isset($value) && is_array($value)) {
378
							foreach($value as $valkey => $valvalue ) {
379
								$properties["custom"][] = [
380
									"name"  => $name,
381
									"value" => $valvalue,
382
									"nls"   => $nls,
383
								];
384
							}
385
						} else {
386
							$properties["custom"][] = [
387
								"name"  => $name,
388
								"value" => $value,
389
								"nls"   => $nls,
390
							];
391
392
						}
393
					}
394
				}
395
			}
396
		}
397 48
		return $properties;
398
	}
399
400 49
	public function save($properties="", $vtype="") {
401
	/***********************************************************************
402
	  save the current object.
403
	  if this is a new object ($this->arIsNewObject) the path is checked and
404
	  the object is saved under the new path.
405
	***********************************************************************/
406 48
	global $AR, $ARnls, $ARCurrent;
407 48
		debug("pobject: save([properties], $vtype)","object");
408 48
		debug("pobject: save: path=".$this->path,"object");
409 48
		$configcache=$this->loadConfig();
410 49
		$needsUnlock = false;
411 48
		$arIsNewObject = false;
412 48
		$result = false;
413 48
		$this->error = '';
414 48
		if ($this->arIsNewObject) { // save a new object
0 ignored issues
show
Bug introduced by
The property arIsNewObject does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
415 24
			debug("pobject: save: new object","all");
416 24
			$this->path = $this->make_path();
417 24
			$arNewParent=$this->make_path("..");
418 24
			$arNewFilename=basename($this->path);
419 24
			$arIsNewObject = true;
420 24
			if (preg_match("|^[a-z0-9_\{\}\.\:-]+$|i",$arNewFilename)) { // no "/" allowed, these will void the 'add' grant check.
421 24
				if (!$this->exists($this->path)) { //arNewFilename)) {
422 24
					if ($this->exists($arNewParent)) {
423 24
						if (!$config = $this->data->config) {
424 12
							$config=new object();
425
						}
426 12
					} else {
427 12
						$this->error = ar::error( sprintf($ARnls["err:noparent"],$arNewParent), 1102);
428
					}
429 12
				} else {
430 12
					$this->error = ar::error( sprintf($ARnls["err:alreadyexists"],$arNewFilename), 1103);
431
				}
432 12
			} else {
433 12
				$this->error = ar::error( sprintf($ARnls["err:fileillegalchars"],$arNewFilename), 1104);
434
			}
435 12
		} else { // existing object
436 48
			debug("pobject: save: existing object","all");
437 48
			if ($this->exists($this->path)) { // prevent 'funny stuff'
438 48
				if (!$this->lock()) {
439
					$this->error = ar::error( $ARnls["err:objectalreadylocked"], 1105);
440
				} else {
441 48
					$needsUnlock = true;
442 48
					$config = $this->data->config;
443
				}
444 24
			} else {
445
				$this->error = ar::error($ARnls["err:corruptpathnosave"], 1106);
446
			}
447
		}
448
		// pre checks done
449
		// return now on error
450 48
		if ($this->error) {
451
			return $result;;
452
		}
453
454
455 48
		if ($ARCurrent->arCallStack) {
456 48
			$arCallArgs = end($ARCurrent->arCallStack);
457 24
		} else {
458 20
			$arCallArgs = array();
459
		}
460
461 48
		$context = $this->getContext();
462
463 48
		$wf_object = $this->store->newobject($this->path, $this->parent, $this->type, $this->data, $this->id, $this->lastchanged, $this->vtype, 0, $this->priority);
0 ignored issues
show
Bug introduced by
The property parent does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property lastchanged does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property vtype does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The property priority does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
464 48
		if ( $arIsNewObject) {
465 24
			$wf_object->arIsNewObject=$arIsNewObject;
466 12
		}
467
468
		/* save custom data */
469 48
		$properties = $this->saveCustomData($configcache, $properties);
470
471
		// this makes sure the event handlers are run on $wf_object, so that $this->data changes don't change the data of the object to be saved
472 48
		$this->pushContext(array('scope' => 'php', 'arCurrentObject' => $wf_object));
473
474 48
		$eventData = new object();
475 48
		$eventData->arCallArgs = $arCallArgs;
0 ignored issues
show
Bug introduced by
The property arCallArgs does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
476 48
		$eventData->arCallFunction	= $context['arCallFunction'];
0 ignored issues
show
Bug introduced by
The property arCallFunction does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
477 48
		$eventData->arIsNewObject = $arIsNewObject;
0 ignored issues
show
Bug introduced by
The property arIsNewObject does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
478 48
		$eventData->arProperties = $properties;
0 ignored issues
show
Bug introduced by
The property arProperties does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
479 48
		$eventData = ar_events::fire( 'onbeforesave', $eventData );
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
480
481
		// pop the wf_object, not needed later, the extra scope might hinder other code
482 48
		$this->popContext();
483
484 48
		if ( !$eventData ) {
485
			return false; // prevent saving of the object.
486
		}
487
488
		// arguments can be altered by event handlers, only usefull when a workflow template is also defined
489 48
		$arCallArgs = $eventData->arCallArgs;
490
491
		// the properties from the eventData are the new property list
492
		// no need to merge them with $properties, just manipulate the properties array directly
493
		// in the event data. unlike the user.workflow.pre.html template
494 48
		if (isset( $eventData->arProperties ) && is_array( $eventData->arProperties ) ) {
495 48
			$properties = $eventData->arProperties;
496 24
		} else {
497 44
			$properties = array();
498
		}
499
500
		// pass the current properties list to the workflow template
501
		// for backwards compatibility and workflow templates that just
502
		// returned only their own properties, merge them afterwards
503
		// don't do this for the eventData arProperties!
504 48
		$arCallArgs['properties'] = $properties;
505 48
		$wf_result = $wf_object->call("user.workflow.pre.html", $arCallArgs);
506
		/* merge workflow properties */
507 48
		if (isset($wf_result) && is_array($wf_result) ){
508
			$properties = $this->saveMergeWorkflowResult($properties,$wf_result);
509
		}
510
511 48
		$this->error = $wf_object->error;
512 48
		$this->priority = $wf_object->priority;
513 48
		$this->data = $wf_object->data;
514 48
		$this->data->config = $config;
0 ignored issues
show
Bug introduced by
The variable $config 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...
515 48
		$this->data->mtime=time();
516 48
		if($arIsNewObject) {
517 24
			$this->data->ctime=$this->data->mtime;
518 12
		}
519
520 48
		$this->data->muser=$AR->user->data->login;
521 48
		if( !$this->data->config->owner ) {
522 24
			if( !$this->data->config->owner_name) {
523 24
				$this->data->config->owner_name=$AR->user->data->name;
524 12
			}
525 24
			$this->data->config->owner=$AR->user->data->login;
526 24
			$properties["owner"][0]["value"]=$this->data->config->owner;
527 12
		}
528 48
		$properties["time"][0]["ctime"]=$this->data->ctime;
529 48
		$properties["time"][0]["mtime"]=$this->data->mtime;
530 48
		$properties["time"][0]["muser"]=$this->data->muser;
531
532
533 48
		if (!$this->error) {
534 48
			if ($this->path=$this->store->save($this->path, $this->type, $this->data, $properties, $vtype, $this->priority)) {
535 48
				unset($this->arIsNewObject);
536 48
				$this->id=$this->exists($this->path);
537 48
				$result=$this->path;
538
539 48
				$config=$this->data->config; // need to set it again, to copy owner config data
540
541 48
				$wf_object = $this->store->newobject($this->path, $this->parent, $this->type, $this->data, $this->id, $this->lastchanged, $this->vtype, 0, $this->priority);
542 48
				$arCallArgs = $eventData->arCallArgs; // returned from onbeforesave event
543 48
				$arCallArgs['properties'] = $properties;
544
545 48
				if ($arIsNewObject) {
546 24
					$wf_object->arIsNewObject = $arIsNewObject;
547 12
				}
548 48
				$wf_result = $wf_object->call("user.workflow.post.html", $arCallArgs);
549 48
				$this->error = $wf_object->error;
550 48
				$this->priority = $wf_object->priority;
551 48
				$this->data = $wf_object->data;
552 48
				$this->data->config = $config;
553
				/* merge workflow properties */
554
555 48
				if (isset($wf_result) && is_array($wf_result) ){
556
					$properties = $this->saveMergeWorkflowResult($properties,$wf_result);
557
558
					if (!$this->store->save($this->path, $this->type, $this->data, $properties, $this->vtype, $this->priority)) {
559
						$this->error = ar::error( ''.$this->store->error, 1108, $this->store->error);
560
						$result = false;
561
					}
562 1
				}
563
				// all save actions have been done, fire onsave.
564 48
				$this->data->config = $config;
565
566
				//$this->ClearCache($this->path, true, false);
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
567 48
				$eventData->arProperties = $properties;
568 48
				$this->pushContext(array('scope' => 'php', 'arCurrentObject' => $this));
569 48
				ar_events::fire( 'onsave', $eventData ); // nothing to prevent here, so ignore return value
570 48
				$this->popContext();
571 24 View Code Duplication
			} else {
572
				$this->error = ar::error( ''.$this->store->error, 1107, $this->store->error);
573
				$result = false;
574
			}
575 24
		}
576 48
		if( $needsUnlock == true ){
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
577 48
			$this->unlock();
578 24
		}
579
580 48
		if ($this->data->nls->list[$this->nls]) {
581 48
			$mynlsdata=$this->data->{$this->nls};
582 24
		} else if ($this->data->nls->default) {
583
			$mynlsdata=$this->data->{$this->data->nls->default};
584
		} else {
585
			$mynlsdata=$this->data;
586
		}
587
588 48
		unset($this->nlsdata);
589 48
		$this->nlsdata=$mynlsdata;
590
591 48
		debug("pobject: save: end","all");
592 48
		return $result;
593
	}
594
595
	public function link($to) {
596
		return $this->store->link($this->path, $this->make_path($to));
597
	}
598
599
	public function delete() {
600
	global $ARCurrent;
601
		$result	= false;
602
		$this->error = '';
603
		if ($ARCurrent->arCallStack) {
604
			$arCallArgs = end($ARCurrent->arCallStack);
605
		} else {
606
			$arCallArgs = array();
607
		}
608
		$context = $this->getContext();
609
610
		$eventData = new object();
611
		$eventData->arCallArgs = $arCallArgs;
0 ignored issues
show
Bug introduced by
The property arCallArgs does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
612
		$eventData->arCallFunction = $context['arCallFunction'];
0 ignored issues
show
Bug introduced by
The property arCallFunction does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
613
		$eventData = ar_events::fire( 'onbeforedelete', $eventData );
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
614
		if ( !$eventData ) {
615
			return false;
616
		}
617
		$this->call("user.workflow.delete.pre.html", $eventData->arCallArgs);
618
		if (!$this->error) {
619
			if ($this->store->delete($this->path)) {
620
				$result = true;
621
				$this->call("user.workflow.delete.post.html", $eventData->arCallArgs);
622
				ar_events::fire( 'ondelete', $eventData );
623
			} else {
624
				$this->error = ar::error( ''.$this->store->error, 1107, $this->store->error);
625
			}
626
		}
627
		return $result;
628
	}
629
630 56
	public function exists($path) {
631 56
		$path=$this->make_path($path);
632 56
		return $this->store->exists($path);
633
	}
634
635 72
	public function make_path($path="") {
636
		switch($path){
637 72
			case '':
638 72
			case '.':
639 68
			case $this->path:
640 72
				return $this->path;
641
				break;
642 60
			case '..':
643 24
				return $this->parent;
644
				break;
645 30
			default:
646 60
				return $this->store->make_path($this->path, $path);
647 30
		}
648
	}
649
650
	public function make_ariadne_url($path="") {
651
		global $AR;
652
		$path = $this->make_path($path);
653
		return $AR->host . $AR->root . $this->store->get_config('rootoptions') . $path;
654
	}
655
656
657 52
	public function make_url($path="", $nls=false, $session=true, $https=null, $keephost=null) {
658 52
		global $ARConfig, $AR, $ARCurrent;
659
660 52
		$rootoptions=$this->store->get_config('rootoptions');
661 52
		if (!$session || ($nls !== false)) {
662 52
			$rootoptions = "";
663 52
			if ($session && isset($ARCurrent->session->id) && !$AR->hideSessionIDfromURL) {
664
				$rootoptions .= "/-".$ARCurrent->session->id."-";
665
			}
666 52
			if ($nls) {
667 48
				$rootoptions_nonls = $rootoptions;
668 48
				$rootoptions .= '/'.$nls;
669 24
			}
670 26
		}
671 52
		$path=$this->make_path($path);
672
673
		// now run CheckConfig and get the parentsite of the path found
674 52
		if (!$temp_config=$ARConfig->cache[$path]) {
675 4
			$temp_path = $path;
676 4
			while (!($temp_site = $this->currentsite($temp_path)) && $temp_path!='/') {
677
				$temp_path = $this->make_path($temp_path.'../');
678
			}
679 4
			$temp_config=$ARConfig->cache[$temp_site];
680 2
		}
681
682 52
		if ( !isset($keephost) && (
683 52
			(!$nls && $this->compare_hosts($AR->host, $temp_config->root["value"])) ||
684 52
			($nls && ($this->compare_hosts($AR->host, $temp_config->root['list']['nls'][$nls])))
685 26
		)) {
686
			$keephost = false;
687
		}
688
689 52
		if (!$keephost) {
690 52
			if ($nls) {
691 48
				$url=$temp_config->root["list"]["nls"][$nls];
692 48
				if (isset($url) && is_array($url)) {
693
					$url = current( $url );
694
				}
695 48
				if ($url) {
696 View Code Duplication
					if (substr($url, -1)=='/') {
697
						$url=substr($url, 0, -1);
698
					}
699
					$url .= $rootoptions_nonls;
0 ignored issues
show
Bug introduced by
The variable $rootoptions_nonls 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...
700
				}
701 24
			}
702 52
			if (!$url) {
0 ignored issues
show
Bug introduced by
The variable $url 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...
703 52
				$checkNLS = $nls;
704 52
				if (!$checkNLS) {
705 28
					$checkNLS = $this->nls;
706 14
				}
707 52
				$urlList = $temp_config->root['list']['nls'][$checkNLS];
708 52
				if (isset($urlList) && is_array($urlList)) {
709
					$url = reset($urlList) . $rootoptions;
710
				} else {
711 52
					$url = $temp_config->root["value"].$rootoptions;
712
				}
713 26
			}
714 52
			$url.=substr($path, strlen($temp_config->root["path"])-1);
715
716 52
			if (is_bool($https)) {
717
				if ($https) {
718
					if ($AR->https) {
719
						$url = preg_replace('/^http:/', 'https:', $url);
720
					}
721
				} else {
722 26
					$url = preg_replace('/^https:/', 'http:', $url);
723
				}
724
			}
725 26
		} else {
726 48
			$checkNLS = $nls;
727 48
			if (!$checkNLS) {
728
				$checkNLS = $this->nls;
729
			}
730 48
			$urlCheck = $temp_config->root['list']['nls'][$checkNLS];
731 48
			if (!is_array($urlCheck)) {
732 48
				$urlCheck = $temp_config->root["value"];
733 24
			}
734 48
			$requestedHost = ldGetRequestedHost();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $requestedHost is correct as ldGetRequestedHost() seems to always returns null.
Loading history...
735 48
			if ($this->compare_hosts($requestedHost, $urlCheck)) {
736
				$url = $requestedHost . $rootoptions;
737
				$url .= substr($path, strlen($temp_config->root["path"])-1);
738
			} else {
739
				//$url=$AR->host.$AR->root.$rootoptions.$path;
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
740 48
				$url = $protocol . $requestedHost . $AR->root . $rootoptions . $path;
0 ignored issues
show
Bug introduced by
The variable $protocol 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...
741
			}
742
		}
743 52
		return $url;
744
	}
745
746 52
	protected function compare_hosts($url1, $url2) {
747
		// Check if hosts are equal, so that http://www.muze.nl and //www.muze.nl also match.
748
		// using preg_replace instead of parse_url() because the latter doesn't parse '//www.muze.nl' correctly.
749 52
		if (isset($url2) ) {
750 52
			if ( !is_array($url2) ){
751 52
				$url2 = array($url2);
752 26
			}
753 26
		} else {
754 48
			$url2 = array();
755
		}
756
757 52
		$prepurl1 = preg_replace('|^[a-z:]*//|i', '', $url1);
758
759 52
		foreach($url2 as $url) {
760
			if (
761 52
					$url == $url1 ||
762 52
					$prepurl1 == preg_replace('|^[a-z:]*//|i', '', $url2)
763 26
				) {
764 26
				return true;
765
			}
766 26
		}
767 52
		return false;
768
	}
769
770 48
	public function make_local_url($path="", $nls=false, $session=true, $https=null) {
771 48
		global $ARCurrent, $ARConfig;
772 48
		$site = false;
773 48
		$path = $this->make_path($path);
774 48
		$checkpath = $path;
775
776 48
		$redirects = $ARCurrent->shortcut_redirect;
777 48
		if (isset($redirects) && is_array($redirects)) {
778
			$newpath = $checkpath;
779
			$c_redirects = count($redirects);
780
			$c_redirects_done = 0;
781 View Code Duplication
			while (count($redirects) && ($redir = array_pop($redirects)) && $redir['keepurl'] && substr($newpath, 0, strlen($redir['dest'])) == $redir['dest']) {
782
				$c_redirects_done++;
783
				$newpath = $redir['src'].substr($newpath, strlen($redir['dest']));
784
			}
785
786
			if ($c_redirects_done == $c_redirects) {
787
				$checkpath = $redir['src'];
0 ignored issues
show
Bug introduced by
The variable $redir 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...
788
			}
789
		}
790
791
		do {
792 48
			if (!$config=$ARConfig->cache[$checkpath]) {
793
				$config=($ARConfig->cache[$checkpath]) ? $ARConfig->cache[$checkpath] : $this->loadConfig($checkpath);
794
			}
795 48
			if ($config) {
796 48
				$checkNLS = $nls;
797 48
				if (!$checkNLS) {
798
					$checkNLS = $this->nls;
799
				}
800 48
				$urlCheck = $config->root['list']['nls'][$checkNLS];
801 48
				if (!is_array($urlCheck)) {
802 48
					$urlCheck = $config->root["value"];
803 24
				}
804 48
				$requestedHost = ldGetRequestedHost();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $requestedHost is correct as ldGetRequestedHost() seems to always returns null.
Loading history...
805
806 48
				if ($this->compare_hosts($requestedHost, $urlCheck)) {
807
					$site=$config->site;
808
				}
809 24
			}
810 48
			$prevpath=$checkpath;
811 48
			$checkpath=$this->make_path($checkpath."../");
812 48
		} while ($prevpath!=$checkpath && !$site);
813 48
		if (!$site) {
814 48
			$site='/';
815 24
		}
816 48
		$site_url=$this->make_url($site, $nls, $session, $https, true);
817 48
		if ($newpath) { // $newpath is the destination of a shortcut redirection, with keepurl on
818
			$rest=substr($newpath, strlen($site));
0 ignored issues
show
Bug introduced by
The variable $newpath 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...
819
		} else {
820 48
			$rest=substr($path, strlen($site));
821
		}
822 48
		return $site_url.$rest;
823
	}
824
825
	public function AR_implements($implements) {
826
		$type = current(explode(".",$this->type));
827
		return $this->store->AR_implements($type, $implements);
828
	}
829
830 View Code Duplication
	public function getlocks() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
831
		global $AR;
832
		if ($this->store->mod_lock) {
833
			$result=$this->store->mod_lock->getlocks($AR->user->data->login);
834
		} else {
835
			$result="";
836
		}
837
		return $result;
838
	}
839
840 48 View Code Duplication
	public function lock($mode="O", $time=0) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
841 48
	global $AR;
842 48
		if ($this->store->mod_lock) {
843 48
			$result=$this->store->mod_lock->lock($AR->user->data->login,$this->path,$mode,$time);
844 24
		} else {
845
			$result=true; // no lock module, so lock is 'set'
846
		}
847 48
		return $result;
848
	}
849
850 48 View Code Duplication
	public function unlock() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
851 48
	global $AR;
852 48
		if ($this->store->mod_lock) {
853 48
			$result=$this->store->mod_lock->unlock($AR->user->data->login,$this->path);
854 24
		} else {
855
			$result=true;
856
		}
857 48
		return $result;
858
	}
859
860
	public function touch($id=0, $timestamp=-1) {
861
		if (!$id) {
862
			$id = $this->id;
863
		}
864
		$result = $this->store->touch($id, $timestamp);
865 View Code Duplication
		if ($this->store->error) {
866
			$this->error = ar::error( ''.$this->store->error, 1107, $this->store->error);
867
		}
868
		return $result;
869
	}
870
871
	public function mogrify($id=0, $type, $vtype=null) {
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
872
		if (!$id) {
873
			$id = $this->id;
874
		}
875
		if (!$vtype) {
876
			$vtype = $type;
877
		}
878
		if (strpos($vtype, '.')!==false) {
879
			$vtype = substr($vtype, 0, strpos($vtype, '.'));
880
		}
881
		$result = $this->store->mogrify($id, $type, $vtype);
882 View Code Duplication
		if ($this->store->error) {
883
			$this->error = ar::error( ''.$this->store->error, 1107, $this->store->error);
884
		}
885
		return $result;
886
	}
887
888
	public function can_mogrify() {
889
		if ($this->path == "/system/users/admin/") {
890
			return false;
891
		}
892
		return true;
893
	}
894
895
	public function load_properties($scope='') {
896
		return $this->store->load_properties($this->id,'',$scope);
897
	}
898
899
	public function _load_properties($scope='') {
900
		return $this->store->load_properties($this->id,'',$scope);
901
	}
902
903
	public function load_property($property, $scope='') {
904
		return $this->store->load_property($this->id,$property,$scope);
905
	}
906
907
	public function _load_property($property, $scope='') {
908
		return $this->store->load_property($this->id,$property,$scope);
909
	}
910
911 4
	public function GetValidGrants($path="") {
912
	/********************************************************************
913
914
	  This function finds all grants in effect on this object for the
915
	  logged in user! $AR->user must already be set.
916
917
	  Grants are checked in the following way:
918
	  1) First all parents of this object are checked for grants for this
919
	     specific user. The 'nearest' grants are valid, and the path of
920
	     parent that set these grants will be the upper limit for the
921
	     checking of group grants.
922
	  2) Now all groups of which the user is a member are checked for
923
	     grants. Likewise, all parents are checked for group grants, upto
924
	     but not including the upperlimit as set in 1. All group grants
925
	     found are merged into one grants list.
926
	  3) If there are gropup grants, this means that there are group
927
	     grants set in a parent nearer to this object than the user grants
928
	     and therefore the groupgrants must be merged with the
929
	     usergrants.
930
931
	  this results in:
932
	  1	/		user: read edit		group: none
933
	  2	/dir/					group: read
934
	  3	/dir2/		user: none		group: read
935
	  4	/dir/dir3/				group2: edit
936
	  case 1: the user takes precedence over the group, grants are 'read edit'
937
	  case 2: groupgrants are merged with usergrants, as its grants are set
938
	          in a 'nearer' parent (itself). grants are 'read edit'.
939
	  case 3: user takes precedence again. grants are 'none'.
940
	  case 4: All group grants are merged with the usergrants.
941
	          Therefore the grants are 'none read edit'.
942
	********************************************************************/
943
944 4
	global $AR;
945
946 4
		if ($AR->user) { 	// login and retrieval of user object
947 4
			if (!$path) {
948 4
				$path=$this->path;
949 2
			}
950 4
			if (!$AR->user->grants[$path]) {
951 4
				$grants=array();
952 4
				$userpath=$AR->user->FindGrants($path, $grants);
953
				// if not already done, find all groups of which the user is a member
954 4
				if (!is_array($AR->user->externalgroupmemberships) || count($AR->user->externalgroupmemberships)==0) {
955 4
					$criteria["members"]["login"]["="]=$AR->user->data->login;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$criteria was never initialized. Although not strictly required by PHP, it is generally a good practice to add $criteria = 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...
956 2
				} else {
957
					// Use the group memberships of external databases (e.g. LDAP)
958
					$criteria="members.login='".AddSlashes($AR->user->data->login)."'";
959
					foreach (array_keys($AR->user->externalgroupmemberships) as $group) {
960
						$criteria.=" or login.value='".AddSlashes($group)."'";
961
					}
962
				}
963 4
				if (!$AR->user->groups) {
964 4
					$groups=$this->find("/system/groups/",$criteria, "system.get.phtml");
965 4
					if (isset($groups) && is_array($groups)) {
966 4
						foreach($groups as $group ){
967 4
							if (is_object($group)) {
968 4
								$AR->user->groups[$group->path] = $group;
969 2
							}
970 2
						}
971 2
					}
972 4
					if (isset($AR->user->data->config->groups) && is_array($AR->user->data->config->groups)) {
973 4
						foreach ($AR->user->data->config->groups as $groupPath => $groupId) {
974 4
							if (!$AR->user->groups[$groupPath]) {
975 2
								$AR->user->groups[$groupPath] = current($this->get($groupPath, "system.get.phtml"));
976
							}
977 2
						}
978 2
					}
979 4
					if (!$AR->user->groups["/system/groups/public/"]) {
980
						if ($public=current($this->get("/system/groups/public/", "system.get.phtml"))) {
981
							$AR->user->groups[$public->path] = $public;
982
						}
983
					}
984 2
				}
985 4
				if ($AR->user->groups) {
986
					/* check for owner grants (set by system.get.config.phtml) */
987 4
					if (isset($AR->user->ownergrants) && is_array($AR->user->ownergrants)) {
988
						if (!$AR->user->groups["owner"]) {
989
							$AR->user->groups["owner"] = @current($this->get("/system/groups/owner/", "system.get.phtml"));
990
						}
991
						$AR->user->groups["owner"]->data->config->usergrants = $AR->user->ownergrants;
992
					}
993 4 View Code Duplication
					foreach($AR->user->groups as $group){
994 4
						$groupgrants=array();
995 4
						if (is_object($group)) {
996 4
							$group->FindGrants($path, $groupgrants, $userpath);
997 4
							if (isset($grants) && is_array($grants)) {
998 4
								foreach($groupgrants as $gkey => $gval ){
999
									if (isset($grants[$gkey]) && is_array($grants[$gkey]) && is_array($gval)) {
1000
										$grants[$gkey]=array_merge($gval, $grants[$gkey]);
1001
									} else
1002
									if ($gval && !is_array($gval)) {
1003
										$grants[$gkey] = $gval;
1004
									} else
1005
									if ($gval && !$grants[$gkey]) {
1006 2
										$grants[$gkey] = $gval;
1007
									}
1008 2
								}
1009 2
							} else {
1010 2
								$grants = $groupgrants;
1011
							}
1012 2
						}
1013 2
					}
1014 2
				}
1015 4
				if(isset($AR->sgGrants) && is_array($AR->sgGrants) ) {
1016
					ksort($AR->sgGrants);
1017
					$ppath = $this->make_path($path);
1018 View Code Duplication
					foreach( $AR->sgGrants as $sgpath => $sggrants) {
1019
						$sgpath = $this->make_path($sgpath);
1020
						if( substr($ppath, 0, strlen($sgpath)) == $sgpath ) { // sgpath is parent of ppath or equal to ppath
1021
							if (isset($grants) && is_array($grants)) {
1022
								foreach($sggrants as $gkey => $gval ){
1023
									if (isset($grants[$gkey]) && is_array($grants[$gkey]) && is_array($gval)) {
1024
										$grants[$gkey]=array_merge($gval, $grants[$gkey]);
1025
									} else
1026
									if ($gval && !is_array($gval)) {
1027
										$grants[$gkey] = $gval;
1028
									} else
1029
									if ($gval && !$grants[$gkey]) {
1030
										$grants[$gkey] = $gval;
1031
									}
1032
								}
1033
							} else {
1034
								$grants = $sggrants;
1035
							}
1036
						}
1037
					}
1038
				}
1039 4
				$AR->user->grants[$path]=$grants;
1040 2
			}
1041 4
			$grants=$AR->user->grants[$path];
1042
1043 2
		}
1044 4
		debug("pobject: GetValidGrants(user:".$AR->user->data->login."): end ( ".debug_serialize($grants)." )","all");
0 ignored issues
show
Bug introduced by
The variable $grants 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...
1045 4
		return $grants;
1046
	}
1047
1048
1049 184
	public function pushContext($context) {
1050 184
	global $AR;
1051 184
		if(!empty($AR->context)) {
1052 72
			$context = array_merge(end($AR->context), $context);
1053 36
		}
1054 184
		array_push($AR->context, $context);
1055 184
	}
1056
1057
	public function setContext($context, $level=0) {
1058
	global $AR;
1059
		$AR->context[count($AR->context)-(1+$level)]=$context;
1060
	}
1061
1062 184
	public function popContext() {
1063 184
	global $AR;
1064 184
		return array_pop($AR->context);
1065
	}
1066
1067 184
	public static function getContext($level=0) {
1068 184
	global $AR;
1069 184
		return $AR->context[count($AR->context)-(1+$level)];
1070
	}
1071
1072 72
	public function CheckAdmin($user) {
1073 72
	if ($user->data->login == "admin") {
1074 68
			return true;
1075
		}
1076 4
		if ($user->data->groups['/system/groups/admin/']) {
1077
			return true;
1078
		}
1079 4
		return false;
1080
	}
1081
1082 60
	public function CheckLogin($grant, $modifier=ARTHISTYPE) {
1083 60
	global $AR,$ARnls,$ARConfig,$ARCurrent,$ARConfigChecked;
1084 60
		if (!$this->store->is_supported("grants")) {
1085
			debug("pobject: store doesn't support grants");
1086
			return true;
1087
		}
1088 60
		if ($modifier==ARTHISTYPE) {
1089 60
			$modifier=$this->type;
1090 30
		}
1091
1092
		/* load config cache */
1093 60
		if (!isset($ARConfig->cache[$this->path])) {
1094
			// since this is usually run before CheckConfig, make sure
1095
			// it doesn't set cache time
1096
			$realConfigChecked = $ARConfigChecked;
1097
			$ARConfigChecked = true;
1098
			$this->loadConfig();
1099
			$ARConfigChecked = $realConfigChecked;
1100
		}
1101
1102 60
		$isadmin = $this->CheckAdmin($AR->user);
1103
1104 60
		if (!$isadmin && !$AR->user->grants[$this->path]) {
1105
			$grants = $this->GetValidGrants();
1106
		} else {
1107 60
			$grants = $AR->user->grants[$this->path];
1108
		}
1109
1110 60
		if ($AR->user->data->login!="public") {
1111
			// Don't remove this or MSIE users won't get uptodate pages...
1112 60
			ldSetClientCache(false);
1113 30
		}
1114
1115 60
		if ( 	( !$grants[$grant]
1116 60
					|| ( $modifier && is_array($grants[$grant]) && !$grants[$grant][$modifier] )
1117 60
				) && !$isadmin ) {
1118
			// do login
1119
			$arLoginMessage = $ARnls["accessdenied"];
1120
			ldAccessDenied($this->path, $arLoginMessage);
1121
			$result=false;
1122
		} else {
1123 60
			$result=($grants || $isadmin);
1124
		}
1125
1126 60
		$ARCurrent->arLoginSilent=1;
1127 60
		return $result;
1128
	}
1129
1130
1131 4
	public function CheckPublic($grant, $modifier=ARTHISTYPE) {
1132 4
	global $AR;
1133
1134 4
		$result=false;
1135 4
		if (!$AR->public) {
1136 4
			$this->pushContext(array('scope' => 'php', 'arCurrentObject' => $this));
1137 4
				$AR->public=current($this->get("/system/users/public/", "system.get.phtml"));
1138 4
			$this->popContext();
1139 2
		}
1140 4
		if ($AR->public) {
1141 4
			$AR->private=$AR->user;
1142 4
			$AR->user=$AR->public;
1143 4
			$result=$this->CheckSilent($grant, $modifier);
1144 4
			$AR->user=$AR->private;
1145 2
		}
1146 4
		return $result;
1147
	}
1148
1149 44
	public function CheckSilent($grant, $modifier=ARTHISTYPE, $path=".") {
1150 44
	global $AR, $ARConfig;
1151 44
		$path = $this->make_path($path);
1152 44
		if ($modifier==ARTHISTYPE) {
1153 44
			$modifier=$this->type;
1154 22
		}
1155
1156
		/* load config cache */
1157 44
		if (!$ARConfig->cache[$path]) {
1158 8
			$this->loadConfig($path);
1159 4
		}
1160 44
		if ($this->CheckAdmin($AR->user)) {
1161 40
			$result=1;
1162 24
		} else if ($grants=$AR->user->grants[$path]) {
1163
			$result=$grants[$grant];
1164
		} else {
1165 4
			$grants=$this->GetValidGrants();
1166 4
			$result=$grants[$grant];
1167
		}
1168 44
		if ($modifier && is_array($result)) {
1169
			$result=$result[$modifier];
1170
		}
1171 44
		return $result;
1172
	}
1173
1174
	public function CheckNewFile($newfilename) {
1175
	global $ARnls;
1176
	/**********************************************************************
1177
1178
	  This function performs all the necessary checks on a path to see
1179
	whether it's a valid path for a new object. This consists of:
1180
	1) checking for invalid characters, valid chars are "a-zA-Z0-9./_-"
1181
	2) checking whether the path starts and ends with a "/".
1182
	3) checking whether the path doesn't exist already.
1183
	4) checking whether the parent exists.
1184
1185
	if all this checks out, it returns 1. If not, $this->error is set to
1186
	the correct error message.
1187
1188
	**********************************************************************/
1189
1190
		$this->error="";
1191
		if (preg_match("|^/[a-z0-9\./_-]*/$|i",$newfilename)) {
1192
			if (!$this->store->exists($newfilename)) {
1193
				$parent=$this->store->make_path($newfilename, "..");
1194
				if ($this->store->exists($parent)) {
1195
					$result=1;
1196
				} else {
1197
					$this->error = ar::error( sprintf($ARnls["err:filenameinvalidnoparent"],$newfilename,$parent), 1102);
1198
				}
1199
			} else {
1200
				$this->error = ar::error( sprintf($ARnls["err:chooseotherfilename"],$newfilename), 1103);
1201
			}
1202
		} else {
1203
			$this->error = ar::error( sprintf($ARnls["err:fileillegalchars"],$newfilename)." ".$ARnls["err:startendslash"], 1104);
1204
		}
1205
		return $result;
0 ignored issues
show
Bug introduced by
The variable $result 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...
1206
	}
1207
1208 View Code Duplication
	public function resetConfig($path='') {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1209
	global $ARConfig;
1210
		$path = $this->make_path($path);
1211
		if ($ARConfig->cache[$path]) {
1212
			$path = preg_quote($path,'/');
1213
			$keys = preg_grep('/^'.$path.'/',array_keys($ARConfig->cache));
1214
			foreach ($keys as $cachepath) {
1215
				unset($ARConfig->cache[$cachepath]);
1216
				unset($ARConfig->pinpcache[$cachepath]);
1217
			}
1218
		}
1219
	}
1220
1221 36 View Code Duplication
	public function clearChildConfigs($path='') {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1222 36
	global $ARConfig;
1223 36
		$path = $this->make_path($path);
1224 36
		if ($ARConfig->cache[$path]) {
1225 36
			$path = preg_quote($path,'/');
1226 36
			$keys = preg_grep('/^'.$path.'./',array_keys($ARConfig->cache));
1227 36
			foreach($keys as $cachepath) {
1228 4
				unset($ARConfig->cache[$cachepath]);
1229 4
				unset($ARConfig->pinpcache[$cachepath]);
1230 4
				unset($ARConfig->libraries[$cachepath]);
1231 18
			}
1232 18
		}
1233 36
	}
1234
1235 36
	protected function getConfig() {
1236 36
	global $ARConfig, $ARCurrent, $ARConfigChecked;
1237 36
		$this->pushContext(array('scope' => 'php', 'arCurrentObject' => $this));
1238
		// $context=$this->getContext(0);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
1239
		// debug("getConfig(".$this->path.") context: ".$context['scope'] );
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
1240
		// debug(print_r($ARConfig->nls, true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
1241 36
		if( !$ARConfig->cache[$this->parent] && $this->parent!=".." ) {
1242 4
			$parent = current($this->get($this->parent, "system.get.phtml"));
1243 4
			if ($parent) {
1244 4
				$parent->getConfig();
1245 2
			}
1246 2
		}
1247
1248 36
		$this->getConfigData();
1249
1250 36
		$ARConfig->pinpcache[$this->path] = $ARConfig->pinpcache[$this->parent];
1251
		// backwards compatibility when calling templates from config.ini
1252 36
		$prevArConfig = $ARCurrent->arConfig;
1253 36
		$ARCurrent->arConfig = $ARConfig->pinpcache[$this->path];
1254
1255 36
		$arCallArgs['arConfig'] = $ARConfig->pinpcache[$this->path];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$arCallArgs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $arCallArgs = 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...
1256
1257
		/* calling config.ini directly for each system.get.config.phtml call */
1258 36
		$loginSilent = $ARCurrent->arLoginSilent;
1259 36
		$ARCurrent->arLoginSilent = true;
1260
		// debug("getConfig:checkconfig start");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1261
1262 36
		$initialNLS = $ARCurrent->nls;
1263 36
		$initialConfigChecked = $ARConfigChecked;
1264
1265 36
		$ARConfig->cache[$this->path]->inConfigIni = true;
1266 36
		if ($ARConfig->cache[$this->path]->hasConfigIni && !$this->CheckConfig('config.ini', $arCallArgs)) {
0 ignored issues
show
Documentation introduced by
$arCallArgs is of type array<string,?,{"arConfig":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Bug Best Practice introduced by
The expression $this->CheckConfig('config.ini', $arCallArgs) of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
1267
			//debug("pobject::getConfig() loaded config.ini @ ".$this->path);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1268
			// debug("getConfig:checkconfig einde");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1269 4
			$arConfig = $ARCurrent->arResult;
1270 4
			if (!isset($arConfig)) {
1271
				$arConfig = $ARCurrent->arConfig;
1272
			}
1273 4
			unset($ARCurrent->arResult);
1274 4
			if (isset($arConfig['library']) && is_array($arConfig['library'])) {
1275
				if (!$ARConfig->libraries[$this->path]) {
1276
					$ARConfig->libraries[$this->path] = array();
1277
				}
1278
				foreach ($arConfig['library'] as $libName => $libPath) {
1279
					$this->loadLibrary($libName, $libPath);
1280
				}
1281
				unset($arConfig['library']);
1282
			}
1283 4
			$ARConfig->pinpcache[$this->path] = (array) $arConfig;
1284 2
		}
1285 36
		$ARConfig->cache[$this->path]->inConfigIni = false;
1286 36
		$this->clearChildConfigs( $this->path ); // remove any config data for child objects, since these are set before their parent config was set
1287 36
		$ARConfigChecked = $initialConfigChecked;
1288 36
		$ARCurrent->nls = $initialNLS;
1289
1290 36
		$arConfig = &$ARConfig->pinpcache[$this->path];
1291 36 View Code Duplication
		if (!is_array($arConfig['authentication']['userdirs'])) {
1292
			$arConfig['authentication']['userdirs'] = array('/system/users/');
1293
		} else {
1294 36
			if (reset($arConfig['authentication']['userdirs']) != '/system/users/') {
1295
				array_unshift($arConfig['authentication']['userdirs'], '/system/users/');
1296
			}
1297
		}
1298 36 View Code Duplication
		if (!is_array($arConfig['authentication']['groupdirs'])) {
1299
			$arConfig['authentication']['groupdirs'] = array('/system/groups/');
1300
		} else {
1301 36
			if (reset($arConfig['authentication']['groupdirs']) != '/system/groups/') {
1302
				array_unshift($arConfig['authentication']['groupdirs'], '/system/groups/');
1303
			}
1304
		}
1305
1306 36
		$ARCurrent->arLoginSilent = $loginSilent;
1307 36
		$ARCurrent->arConfig = $prevArConfig;
1308 36
		$this->popContext();
1309 36
	}
1310
1311 36
	protected function getConfigData() {
1312 36
	global $ARConfig, $AR;
1313 36
		$context = $this->getContext(0);
1314 36
		if (!$ARConfig->cache[$this->path] && $context["scope"] != "pinp") {
1315
			// first inherit parent configuration data
1316 36
			$configcache= clone $ARConfig->cache[$this->parent];
1317 36
			$configcache->localTemplates = [];
1318 36
			$configcache->pinpTemplates = [];
1319 36
			$configcache->id = $this->id;
1320
1321
			// cache default templates
1322 36
			if (isset($this->data->config->templates) && count($this->data->config->templates)) {
1323
				$configcache->pinpTemplates    = $this->data->config->pinp;
1324
				$configcache->privatetemplates = $this->data->config->privatetemplates;
1325
				$configcache->localTemplates   = $this->data->config->templates;
1326
1327
				if( !$configcache->hasDefaultConfigIni ) {
1328
					foreach($configcache->localTemplates as $type => $templates ) {
1329
						if( isset($templates["config.ini"]) ) {
1330
							$configcache->hasDefaultConfigIni = true;
1331
							$configcache->hasConfigIni = true;
1332
							break;
1333
						}
1334
					}
1335
				}
1336 36
			} else if (isset($this->data->config->pinp) && count($this->data->config->pinp)) {
1337 4
				$configcache->pinpTemplates    = $this->data->config->pinp;
1338 2
			}
1339
1340 36
			if( !$configcache->hasDefaultConfigIni ) {
1341 36
				$configcache->hasConfigIni = false;
1342 36
				if(isset($this->data->config->pinp) && is_array($this->data->config->pinp) ) {
1343 4
					foreach( $this->data->config->pinp as $type => $templates ) {
1344 4
						if( isset($templates["config.ini"]) ) {
1345 4
							$configcache->hasConfigIni = true;
1346 4
							break;
1347
						}
1348 2
					}
1349 2
				}
1350 18
			}
1351
1352 36
			$localcachesettings = $this->data->config->cacheSettings;
1353 36
			if (!is_array($localcachesettings) ){
1354 36
				$localcachesettings = array();
1355 18
			}
1356
1357 36
			if (!is_array($configcache->cacheSettings) ) {
1358
				$configcache->cacheSettings = array();
1359
			}
1360
1361 36
			if ($this->data->config->cacheconfig) { // When removing this part, also fix the setting below.
1362 4
				$configcache->cache=$this->data->config->cacheconfig;
1363 2
			}
1364
1365 36
			if (!isset($localcachesettings['serverCache']) && isset($this->data->config->cacheconfig)) {
1366 4
				$localcachesettings["serverCache"] = $this->data->config->cacheconfig;
1367 2
			}
1368
1369 36
			if ($localcachesettings['serverCache'] != 0 ) {
1370 4
				$localcachesettings['serverCacheDefault'] = $localcachesettings['serverCache'];
1371 2
			}
1372
1373 36
			$configcache->cacheSettings = $localcachesettings + $configcache->cacheSettings;
1374
1375
			// store the current object type
1376 36
			$configcache->type = $this->type;
1377
1378 36
			if ($this->data->config->typetree && ($this->data->config->typetree!="inherit")) {
1379
				$configcache->typetree=$this->data->config->typetree;
1380
			}
1381 36
			if (isset($this->data->config->nlsconfig->list)) {
1382 4
				$configcache->nls = clone $this->data->config->nlsconfig;
1383 2
			}
1384
1385 36
			if ($this->data->config->grants["pgroup"]["owner"]) {
1386
				$configcache->ownergrants = $this->data->config->grants["pgroup"]["owner"];
1387
			}
1388 36
			if (isset($configcache->ownergrants) && is_array($configcache->ownergrants)) {
1389
				if ($AR->user && $AR->user->data->login != 'public' && $AR->user->data->login === $this->data->config->owner) {
1390
					$ownergrants = $configcache->ownergrants;
1391
					if (isset($ownergrants) && is_array($ownergrants)) {
1392
						foreach( $ownergrants as $grant => $val ) {
1393
							$AR->user->ownergrants[$this->path][$grant] = $val;
1394
						}
1395
					}
1396
				}
1397
			}
1398
1399 36
			if (isset($this->data->config->customconfig) && is_array($this->data->config->customconfig)) {
1400
				$configcache->custom=array_merge(is_array($configcache->custom)?$configcache->custom:array(), $this->data->config->customconfig);
1401
			}
1402 36
			$ARConfig->cache[$this->path]=$configcache;
1403
1404 18
		}
1405 36
	}
1406
1407 64
	public function loadConfig($path='') {
1408 64
	global $ARConfig, $ARConfigChecked, $ARCurrent;
1409 64
		$path=$this->make_path($path);
1410
		// debug("loadConfig($path)");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1411 64
		if (!isset($ARConfig->cache[$path]) ) {
1412 36
			$allnls = $ARCurrent->allnls;
1413 36
			$ARCurrent->allnls = true;
1414 36
			$configChecked = $ARConfigChecked;
1415 36
			if (($this->path == $path && !$this->arIsNewObject) || $this->exists($path)) {
1416 36
				$this->pushContext(array("scope" => "php"));
1417 36
				if( $this->path == $path ) {
1418
					// debug("loadConfig: currentpath $path ");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1419 36
					$this->getConfig();
1420 18
				} else {
1421
					//debug("loadConfig: get path $path ");
1422 4
					$cur_obj = current($this->get($path, "system.get.phtml"));
1423 4
					$cur_obj->getConfig();
1424
				}
1425 36
				$this->popContext();
1426 36
				$result=$ARConfig->cache[$path];
1427 18
			} else if ($path === '/') {
1428
				// special case: / doesn't exists in the store
1429
				$result=$ARConfig->cache['..'];
1430
			} else {
1431
				$parent=$this->make_path($path.'../');
1432
				if (!$ARConfig->cache[$parent]) {
1433
					$this->pushContext(array("scope" => "php"));
1434
					// debug("loadConfig: parent $parent");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1435
					$cur_obj = current($this->get($parent, "system.get.phtml"));
1436
					if( $cur_obj ) {
1437
						$cur_obj->getConfig();
1438
					}
1439
					$this->popContext();
1440
				}
1441
				$result=$ARConfig->cache[$parent];
1442
				$ARConfig->cache[ $path ] = $result;
1443
				$ARConfig->pinpcache[ $path ] = $ARConfig->pinpcache[ $parent ];
1444
			}
1445
			// restore old ARConfigChecked state
1446 36
			$ARConfigChecked = $configChecked;
1447 36
			$ARCurrent->allnls = $allnls;
1448 18
		} else {
1449
			// debug("loadConfig: exists $path ");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1450 52
			$result=$ARConfig->cache[$path];
1451
		}
1452 64
		return $result;
1453
	}
1454
1455
1456
	// TODO: look for a way to merge loadConfig and loadUserConfig into one function
1457
1458 12
	public function loadUserConfig($path='') {
1459 12
	global $ARConfig;
1460 12
		$path = $this->make_path($path);
1461 12
		$parent = $this->make_path($path.'../');
1462
1463 12
		if (!$ARConfig->cache[$path]) {
1464
			$this->loadConfig($path);
1465
		}
1466 12
		if (!$ARConfig->pinpcache[$path]) {
1467
			$config = $ARConfig->pinpcache[$parent];
1468
		} else {
1469 12
			$config = $ARConfig->pinpcache[$path];
1470
		}
1471 12
		return (array)$config;
1472
	}
1473
1474 4
	public function loadLibrary($name, $path) {
1475 4
	global $ARConfig;
1476 4
		$path=$this->make_path($path);
1477 4
		debug("pobject::loadLibrary($name, $path);");
1478 4
		if ($name===ARUNNAMED) {
1479 4
			if (strstr($path, $this->path)===0) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of strstr($path, $this->path) (string) and 0 (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
1480
				return ar::error('You cannot load an unnamed library from a child object.', 1109);
1481
			} else {
1482 4
				if (!isset($ARConfig->libraries[$this->path])) {
1483 4
					$ARConfig->libraries[$this->path] = [ $path ];
1484 2
				} else {
1485 2
					array_unshift($ARConfig->libraries[$this->path],$path);
1486
				}
1487
			}
1488 2
		} else if ($name && is_string($name)) {
1489
			$ARConfig->libraries[$this->path][$name]=$path;
1490
		} else if (is_int($name)) {
1491
			$ARConfig->libraries[$this->path][$name]=$path;
1492
		} else {
1493
			return ar::error('Illegal library name: '.$name, 1110);
1494
		}
1495 4
	}
1496
1497
	// returns a list of libraries loaded on $path
1498
	public function getLibraries($path = '') {
1499
	global $ARConfig;
1500
		$path = $this->make_path($path);
1501
		return (array)$ARConfig->libraries[$path];
1502
	}
1503
1504
	public function mergeLibraryConfig( $defaultLibraryName, $defaults ) {
1505
		$libraryName = ar::getvar('arLibrary');
1506
		if ( is_numeric($libraryName) || $libraryName == 'current' ) { // library is loaded unnamed
1507
			$libraryName = $defaultLibraryName;
1508
		}
1509
		if ( $libraryName ) {
1510
			$userConfig = ar::acquire('defaults.'.$libraryName);
1511
			if (isset($userConfig) && is_array($userConfig) ) {
1512
				$defaults = array_merge( $defaults, $userConfig );
1513
			}
1514
		}
1515
		return array_merge( $defaults, $this->getvar('arCallArgs') );
1516
	}
1517
1518
	public function _mergeLibraryConfig( $defaultLibraryName, $defaults ) {
1519
		return $this->mergeLibraryConfig( $defaultLibraryName, $defaults );
1520
	}
1521
1522 60
	protected function findTemplateOnPath($path, $arCallFunction, $arType, $reqnls, &$arSuperContext){
1523
1524 60
		debug('findTemplateOnPath: ['.$arType .']['.$arCallFunction.']['.$reqnls.']');
1525 60
		while ($arType!='ariadne_object' ) {
1526 60
			list($arMatchType,$arMatchSubType) = explode('.',$arType,2);
1527 60
			$local = ($path === $this->path);
1528 60
			debug("findTemplateOnPath context [". $path.":".$arType.":".$arCallFunction ."]");
1529 60
			$templates = ar('template')->ls($path);
1530 60
			if(isset($templates[$arCallFunction])) {
1531 12
				$template = null;
1532 12
				if (!isset($arSuperContext[$path.":".$arType.":".$arCallFunction])) {
1533
					$template = array_reduce($templates[$arCallFunction] , function($carry, $item) use ($arMatchType,$arMatchSubType, $reqnls, $local) {
1534 12
						if ( ( $item['local'] == true && $local == true ) || $item['local'] == false ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1535 12
							if ($item['type'] === $arMatchType && ($item['subtype'] == $arMatchSubType) ) {
1536 12
								if (isset($carry) && $carry['language'] !== 'any') {
1537
									return $carry;
1538 12
								} else if ($item['language'] === 'any' || $item['language'] === $reqnls ) {
1539 12
									return $item;
1540
								}
1541
							}
1542
						}
1543
						return $carry;
1544 12
					}, null);
1545 6
				}
1546 12
				if ( isset($template) && !isset($arSuperContext[$path.":".$arType.":".$arCallFunction])) {
1547 12
					debug("findTemplateOnPath returning for [". $path.":".$arType.":".$arCallFunction ."]");
1548 12
					return $template;
1549
				}
1550
			}
1551 48
			if (!isset($AR->superClass[$arType])) {
1552
				// no template found, no default.phtml found, try superclass.
1553 48
				if ($subcpos = strpos($arType, '.')) {
1554 24
					$arSuper = substr($arType, 0, $subcpos);
1555 12
				} else {
1556 48
					if (!class_exists($arType, false )) {
1557
						// the given class was not yet loaded, so do that now
1558
						$arTemp=$this->store->newobject('','',$arType,new object);
1559
					} else {
1560 48
						$arTemp=new $arType();
1561
					}
1562 48
					$arSuper=get_parent_class($arTemp);
1563
				}
1564 48
				$AR->superClass[$arType]=$arSuper;
0 ignored issues
show
Bug introduced by
The variable $AR 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...
1565 24
			} else {
1566
				$arSuper=$AR->superClass[$arType];
1567
			}
1568 48
			$arType=$arSuper;
1569 24
		}
1570
1571 48
		return null;
1572
	}
1573
1574 60
	public function getPinpTemplate($arCallFunction='view.html', $path=".", $top="", $inLibrary = false, $librariesSeen = null, $arSuperContext=array()) {
1575 60
	global $ARCurrent, $ARConfig, $AR, $ARConfigChecked;
1576 60
		debug("getPinpTemplate: function: $arCallFunction; path: $path; top: $top; inLib: $inLibrary","class");
1577 60
		$result = array();
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1578 60
		if (!$top) {
1579 60
			$top = '/';
1580 30
		}
1581 60
		$path = $this->make_path($path);
1582 60
		if (!is_array($arSuperContext)) {
1583
			$arSuperContext = array();
1584
		}
1585
1586 60
		$typepos = strpos($arCallFunction,"::");
1587 60
		if ($typepos !== false ) {
1588
			// template of a specific class defined via call("class::template");
1589
			$arCallType     = substr($arCallFunction, 0, $typepos);
1590
			$arCallFunction = substr($arCallFunction, $typepos+1);
1591
		} else {
1592 60
			$arCallType=$this->type;
1593
		}
1594
1595 60
		$libpos = strpos($arCallFunction,":");
1596 60
		if ( $libpos !== false ) {
1597
			// template of a specific library defined via call("library:template");
1598
			$arLibrary      = substr($arCallFunction, 0, $libpos);
1599
			$arCallFunction = substr($arCallFunction, $libpos+1);
1600
1601
			if ($arLibrary == 'current') {
1602
				// load the current arLibrary
1603
				$context       = $this->getContext(1);
1604
				$arLibrary     = $context['arLibrary'];
1605
				$arLibraryPath = $context['arLibraryPath'];
1606
			} else {
1607
				$libpath = $path;
1608
				while (!isset($arLibraryPath) && $libpath!=$lastlibpath) {
0 ignored issues
show
Bug introduced by
The variable $lastlibpath 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...
1609
					$lastlibpath = $libpath;
1610
					if (isset($ARConfig->libraries[$libpath][$arLibrary])) {
1611
						$arLibraryPath = $ARConfig->libraries[$libpath][$arLibrary];
1612
					} else {
1613
						if ($libpath == $top) {
1614
							break;
1615
						}
1616
						$libpath=$this->store->make_path($libpath, "..");
1617
					}
1618
				}
1619
			}
1620
			if ($arLibraryPath) {
1621
				debug("getPinpTemplate: found library '$arLibrary'. Searching for [".$arCallType."] $arCallFunction on '".$arLibraryPath."' up to '$top'");
0 ignored issues
show
Bug introduced by
The variable $arLibraryPath 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...
1622
				$librariesSeen[$arLibraryPath] = true;
1623
				$inLibrary = true;
1624
				$path = $arLibraryPath;
1625
			} else {
1626
				debug("getPinpTemplate: Failed to find library $arLibrary");
1627
			}
1628
			$path = $this->make_path($path);
1629
			debug("final lib path is ".$path);
1630
		}
1631
1632 60
		$checkpath           = $path;
1633 60
		$lastcheckedpath     = "";
1634 60
		$arCallClassTemplate = $ARCurrent->arCallClassTemplate;
1635 60
		$reqnls              = $this->reqnls;
1636 60
		$template            = null;
1637 60
		while (!$arCallClassTemplate && !isset($template) && $checkpath!=$lastcheckedpath) {
1638 60
			debug("getPinpTemplate: checking for ".$arCallFunction." on ".$checkpath);
1639 60
			$lastcheckedpath = $checkpath;
1640
1641 60
			$template = $this->findTemplateOnPath( $checkpath, $arCallFunction, $arCallType, $reqnls, $arSuperContext);
1642
1643 60
			if (isset($template)) {
1644
				// haal info uit template
1645 12
				debug("getPinpTemplate: found ".$arCallFunction." on ".$checkpath);
1646 54
			} else if ($inLibrary) {
1647
1648
				// faster matching on psection, prefix doesn't have to be a valid type
1649
				$prefix = substr($ARConfig->cache[$checkpath]->type,0,8);
1650
1651
				if ($prefix === 'psection') {
1652
					 debug("BREAKING; $arTemplateId");
0 ignored issues
show
Bug introduced by
The variable $arTemplateId does not exist. Did you mean $template?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1653
					// break search operation when we have found a
1654
					// psection object
1655
					break;
1656
				}
1657
			} else {
1658 48
				if (isset($ARConfig->libraries[$checkpath])) {
1659
					// need to check for unnamed libraries
1660 48
					$libraries = array_filter($ARConfig->libraries[$checkpath],'is_int',ARRAY_FILTER_USE_KEY);
1661 48
					foreach( $libraries as $key => $libpath ) {
1662 48
						$arLibraryPath = $libpath;
1663 48
						$arLibrary     = $key;
1664
1665 48
						$libprevpath = null;
1666 48
						while($libpath != $libprevpath ) {
1667 48
							$libprevpath = $libpath;
1668
1669 48
							$template = $this->findTemplateOnPath( $libpath, $arCallFunction, $arCallType, $reqnls, $arSuperContext);
1670 48
							if (isset($template)) {
1671
								break 2;
1672
							}
1673
1674 48
							$prefix = substr($ARConfig->cache[$libpath]->type,0,8);
1675 48
							if ($prefix === 'psection' || $top == $libpath) {
1676 48
								break;
1677
							}
1678
1679 48
							$libpath = $this->store->make_path($libpath, "..");
1680 24
						}
1681 24
					}
1682 48
					debug("getPinpTemplate: found ".$arCallFunction." on ".$template['path']);
1683 24
				}
1684
1685
			}
1686
1687 60
			if ($checkpath == $top) {
1688 48
				break;
1689
			}
1690
1691 60
			debug("getPinpTemplate: DONE checking for ".$arCallFunction." on ".$checkpath);
1692 60
			$checkpath=$this->store->make_path($checkpath, "..");
1693
			
1694 30
		}
1695 60
		$result = null;
1696 60
		if(isset($template)) {
1697 12
			$result = [];
1698 12
			debug("getPinpTemplate END; ".$template['id'] .' '.$template['path']);
1699 12
			$type = $template['type'];
1700 12
			if(isset($template['subtype'])) {
1701
				$type .= '.' . $template['subtype'];
1702
			}
1703 12
			$result["arTemplateId"]       = $template['id'];
1704 12
			$result["arCallTemplate"]     = $template['filename'];
1705 12
			$result["arCallType"]         = $arCallType;
1706 12
			$result["arCallTemplateName"] = $arCallFunction;
1707 12
			$result["arCallTemplateNLS"]  = $template['language'];
1708 12
			$result["arCallTemplateType"] = $type;
1709 12
			$result["arCallTemplatePath"] = $template['path'];
1710 12
			$result["arLibrary"]          = $arLibrary;
0 ignored issues
show
Bug introduced by
The variable $arLibrary 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...
1711 12
			$result["arLibraryPath"]      = $arLibraryPath;
1712 12
			$result["arLibrariesSeen"]    = $librariesSeen;
1713 12
			$result["arPrivateTemplate"]  = $template['private'];
1714 6
		}
1715 60
		return $result;
1716
	}
1717
1718 64
	public function CheckConfig($arCallFunction="", $arCallArgs="") {
1719
	// returns true when cache isn't up to date and no other template is
1720
	// defined for $path/$function. Else it takes care of output to the
1721
	// browser.
1722
	// All these templates must exist under a fixed directory, $AR->dir->templates
1723 64
	global $nocache, $AR, $ARConfig, $ARCurrent, $ARBeenHere, $ARnls, $ARConfigChecked;
1724 64
		$MAX_LOOP_COUNT=10;
1725
1726
1727
		// system templates (.phtml) have $arCallFunction=='', so the first check in the next line is to
1728
		// make sure that loopcounts don't apply to those templates.
1729 64
		if (0 && $arCallFunction && $ARBeenHere[$this->path][$arCallFunction]>$MAX_LOOP_COUNT) { // protect against infinite loops
1730
			error(sprintf($ARnls["err:maxloopexceed"],$this->path,$arCallFunction,$arCallArgs));
1731
			$this->store->close();
1732
			exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method CheckConfig() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
1733
		} else {
1734 64
			$ARBeenHere[$this->path][$arCallFunction]+=1;
1735
1736
			// this will prevent the parents from setting the cache time
1737 64
			$initialConfigChecked = $ARConfigChecked;
1738 64
			$ARConfigChecked = true;
1739 64
			$config = ($ARConfig->cache[$this->path]) ? $ARConfig->cache[$this->path] : $this->loadConfig();
1740 64
			$ARConfigChecked = $initialConfigChecked;
1741 64
			$ARConfig->nls=$config->nls;
1742
1743
1744
			// if a default language is entered in a parent and no language is
1745
			// explicitly selected in the url, use that default.
1746
			// The root starts with the system default (ariadne.phtml config file)
1747 64
			if ( !$ARCurrent->nls ) {
1748 64
				if ( $config->root['nls'] ) {
1749
					$this->reqnls = $config->root['nls'];
1750
					if ( !$ARConfigChecked ) {
1751
						$ARCurrent->nls = $this->reqnls;
1752
					}
1753 64
				} else if ( $config->nls->default ) {
1754 64
					$this->reqnls = $config->nls->default;
1755 64
					$this->nls = $this->reqnls;
1756 64
					if ( !$ARConfigChecked ) {
1757 32
						$ARCurrent->nls = $this->nls;
1758
					}
1759 32
				}
1760 32
			} else {
1761
				$this->reqnls = $ARCurrent->nls;
1762
			}
1763 64
			$nls = &$this->nls;
1764 64
			$reqnls = &$this->reqnls;
1765
1766 64
			if (!$ARConfigChecked && is_object($ARnls)) {
1767
				$ARnls->setLanguage($ARCurrent->nls);
1768
			}
1769
1770
1771 64
			if (!$ARCurrent->arContentTypeSent) {
1772
				ldHeader("Content-Type: text/html; charset=UTF-8");
1773
				$ARCurrent->arContentTypeSent = true;
1774
			}
1775
1776
/*			// FIXME: the acceptlang code works a bit too well.. it overrides psite configuration settings.
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
Coding Style introduced by
Comment refers to a FIXME task "the acceptlang code works a bit too well.. it overrides psite configuration settings"
Loading history...
1777
1778
			if ($ARCurrent->acceptlang && !$ARCurrent->nls) {
1779
				if ($ARCurrent->acceptlang && is_array($this->data->nls->list)) {
1780
					$validlangs = array_intersect(array_keys($ARCurrent->acceptlang), array_keys($this->data->nls->list));
1781
				}
1782
				if ($validlangs) {
1783
					$reqnls=array_shift($validlangs);
1784
					$ARCurrent->nls = $reqnls;
1785
				}
1786
			}
1787
*/
1788 64 View Code Duplication
			if (isset($this->data->custom) && is_array($this->data->custom) && $this->data->custom['none']) {
1789 4
				$this->customdata=$this->data->custom['none'];
0 ignored issues
show
Bug introduced by
The property customdata does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
1790 2
			}
1791 64 View Code Duplication
			if (isset($this->data->custom) && is_array($this->data->custom) && $this->data->custom[$nls]) {
1792
				$this->customnlsdata=$this->data->custom[$nls];
0 ignored issues
show
Bug introduced by
The property customnlsdata does not seem to exist. Did you mean nlsdata?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1793
			}
1794
1795 64
			if (!$ARConfigChecked) {
1796
				// this template is the first template called in this request.
1797
				$eventData = new object();
1798
				$eventData->arCallArgs = $arCallArgs;
0 ignored issues
show
Bug introduced by
The property arCallArgs does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1799
				$eventData->arCallFunction = $arCallFunction;
0 ignored issues
show
Bug introduced by
The property arCallFunction does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1800
1801
				$ARConfigChecked = true;
1802
				$result = ar_events::fire( 'onbeforeview', $eventData );
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1803
				$ARConfigChecked = $initialConfigChecked;
1804
				if ( !$result ) { //prevent default action: view
1805
					return false;
1806
				}
1807
			}
1808
1809 64
			if (!$ARConfigChecked) {
1810
				// if this object isn't available in the requested language, show
1811
				// a language select dialog with all available languages for this object.
1812
				if (isset($this->data->nls) && !$this->data->name) {
1813
					if (!$ARCurrent->forcenls && (!isset($this->data->nls->list[$reqnls]) || !$config->nls->list[$reqnls])) {
1814
						if (!$ARCurrent->nolangcheck && $arCallFunction != 'config.ini') {
1815
							$ARCurrent->nolangcheck=1;
1816
							$eventData = new object();
1817
							$eventData->arCallFunction = $arCallFunction;
1818
							$eventData->arCallArgs = $arCallArgs;
1819
							$eventData->arRequestedNLS = $reqnls;
0 ignored issues
show
Bug introduced by
The property arRequestedNLS does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1820
							$result = ar_events::fire( 'onlanguagenotfound', $eventData );
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1821
							if ( $result ) { // continue with default action: langaugeselect
1822
								$result->arCallArgs["arOriginalFunction"] = $result->arCallFunction;
1823
								$this->call("user.languageselect.html", $result->arCallArgs);
1824
								return false;
1825
							}
1826
						} else {
1827
							$this->nlsdata=$this->data->$nls;
1828
						}
1829
					} else {
1830
						$this->nlsdata=$this->data->$reqnls;
1831
					}
1832
				}
1833
				$ARCurrent->nolangcheck=1;
1834
			}
1835
1836
			/*
1837
				Set ARConfigChecked to true to indicate that we have been here
1838
				earlier.
1839
			*/
1840 64
			$ARConfigChecked = true;
1841 64
			if ($arCallFunction) { // don't search for templates named ''
1842
				// FIXME: Redirect code has to move to getPinpTemplate()
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "Redirect code has to move to getPinpTemplate"
Loading history...
1843 60
				$redirects	= $ARCurrent->shortcut_redirect;
1844 60
				if (isset($redirects) && is_array($redirects)) {
1845
					$redirpath = $this->path;
1846
					while (!$template['arTemplateId'] &&
0 ignored issues
show
Bug introduced by
The variable $template 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...
1847
							($redir = array_pop($redirects)) &&
1848
							$redir["keepurl"] &&
1849
							(substr($redirpath, 0, strlen($redir["dest"])) == $redir["dest"])
1850
					) {
1851
						$template = $this->getPinpTemplate($arCallFunction, $redirpath, $redir["dest"]);
1852
						$redirpath = $redir['src'];
1853
					}
1854
1855
					if (!$template["arTemplateId"] && $redirpath) {
1856
						$template = $this->getPinpTemplate($arCallFunction, $redirpath);
1857
					}
1858
				}
1859 60
				if (!$template["arTemplateId"]) {
1860 60
					$template = $this->getPinpTemplate($arCallFunction);
1861 30
				}
1862
1863 60
				if ($template["arCallTemplate"] && $template["arTemplateId"]) {
1864 12
					if (!isset($ARCurrent->cacheTemplateChain)) {
1865
						$ARCurrent->cacheTemplateChain = array();
1866
					}
1867 12
					if (!isset($ARCurrent->cacheTemplateChain[$template["arTemplateId"]])) {
1868 8
						$ARCurrent->cacheTemplateChain[$template["arTemplateId"]] = array();
1869 4
					}
1870 12
					if (!isset($ARCurrent->cacheTemplateChain[$template["arTemplateId"]][$template['arCallTemplate']])) {
1871 12
						$ARCurrent->cacheTemplateChain[$template["arTemplateId"]][$template['arCallTemplate']] = array();
1872 6
					}
1873 12
					if (!isset($ARCurrent->cacheTemplateChain[$template["arTemplateId"]][$template['arCallTemplate']][$template['arCallTemplateType']])) {
1874 12
						$ARCurrent->cacheTemplateChain[$template["arTemplateId"]][$template['arCallTemplate']][$template['arCallTemplateType']] = 0;
1875 6
					}
1876 12
					$ARCurrent->cacheTemplateChain[$template["arTemplateId"]][$template['arCallTemplate']][$template['arCallTemplateType']]++;
1877
1878
1879 12
					debug("CheckConfig: arCallTemplate=".$template["arCallTemplate"].", arTemplateId=".$template["arTemplateId"],"object");
1880
					// $arCallTemplate=$this->store->get_config("files")."templates".$arCallTemplate;
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
1881
					// check if template exists, if it doesn't exist, then continue the original template that called CheckConfig
1882 12
					$arTemplates=$this->store->get_filestore("templates");
0 ignored issues
show
Unused Code introduced by
$arTemplates is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1883 12
					$exists = ar('template')->exists($template['arCallTemplatePath'],$template["arCallTemplate"]);
1884 12
					if ( $exists ) {
1885
						// check if the requested language exists, if not do not display anything,
1886
						// unless otherwise indicated by $ARCurrent->allnls
1887
						// This triggers only for pinp templates called by other templates,
1888
						// as the first template (in the url) will first trigger the language
1889
						// choice dialogue instead.
1890 12
						$arLibrary = $template['arLibrary'];
1891 12
						if (is_int($arLibrary)) {
1892
							// set the library name for unnamed libraries to 'current'
1893
							// so that calls using getvar('arLibrary') will keep on working
1894
							$arLibrary = "current";
1895
						}
1896
1897 12 View Code Duplication
						if (!is_string($arCallArgs)) {
1898 12
							$arCallArgs['arCallFunction'] = $arCallFunction;
1899 12
							$arCallArgs['arLibrary']      = $arLibrary;
1900 12
							$arCallArgs['arLibraryPath']  = $template["arLibraryPath"];
1901 6
						}
1902
1903 12
						$ARCurrent->arCallStack[]=$arCallArgs;
1904
						// start running a pinp template
1905
1906 12
						$this->pushContext(
1907
							array(
1908 12
								"scope"              => "pinp",
1909 12
								"arLibrary"          => $arLibrary,
1910 12
								"arLibraryPath"      => $template['arLibraryPath'],
1911 12
								"arCallFunction"     => $arCallFunction,
1912 12
								"arCurrentObject"    => $this,
1913 12
								"arCallType"         => $template['arCallType'],
1914 12
								"arCallTemplateName" => $template['arCallTemplateName'],
1915 12
								"arCallTemplateNLS"  => $template['arCallTemplateNLS'],
1916 12
								"arCallTemplateType" => $template['arCallTemplateType'],
1917 12
								"arCallTemplatePath" => $template['arCallTemplatePath'],
1918 12
								"arLibrariesSeen"    => $template['arLibrariesSeen']
1919 6
							)
1920 6
						);
1921
1922
						// FIXME: is 2 het correcte getal? Kan dit minder magisch?
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "is 2 het correcte getal? Kan dit minder magisch?"
Loading history...
1923 12
						if (count($ARCurrent->arCallStack) == 2 && true === $template['arPrivateTemplate']) {
1924
							// Do not allow private templates to be called first in the stack.
1925
							// echo "Bad request";
1926
1927
							// FIXME: Echte header sturen? Of gewoon niet uitvoeren? Wat is het correcte gedrag?
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "Echte header sturen? Of gewoon niet uitvoeren? Wat is het correcte gedrag?"
Loading history...
1928
							// Return true zorgt er voor dat de default 404 handler het oppikt alsof het template niet bestaat.
1929
							$this->popContext();
1930
							array_pop($ARCurrent->arCallStack);
1931
							return true;
1932 12
						} else if ($ARCurrent->forcenls || isset($this->data->nls->list[$reqnls])) {
1933
							// the requested language is available.
1934 12
							$this->nlsdata=$this->data->$reqnls;
1935 12
							$this->nls=$reqnls;
1936 12
							$continue=true;
1937 6
						} else if (!isset($this->data->nls)) {
1938
							// the object has no language support
1939
							$this->nlsdata=$this->data;
1940
							$continue=true;
1941
						} else if (($ARCurrent->allnls) || (!$initialConfigChecked && $ARCurrent->nolangcheck)) {
1942
							// all objects must be displayed
1943
							// $this->reqnls=$this->nls; // set requested nls, for checks
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
1944
							$this->nls = isset($this->data->nls->default) ? $this->data->nls->default : $this->reqnls;
1945
							$this->nlsdata = $this->data->$nls ?: $this->data->{$this->nls} ?: $this->data;
1946
							$continue=true;
1947
						} else {
1948
							debug("CheckConfig: requested language not available, allnls not set","object");
1949
							// -> skip this object (do not run template but do return false)
1950
							$continue=false;
1951
						}
1952 12
						if ($continue) {
1953 12
							$eventData = new object();
1954 12 View Code Duplication
							if ( !$AR->contextCallHandler ) { /* prevent onbeforecall from re-entering here */
1955 12
								$AR->contextCallHandler = true;
1956 12
								$eventData->arCallArgs = $arCallArgs;
1957 12
								$eventData->arCallFunction = $arCallFunction;
1958 12
								$eventData->arContext = $this->getContext();
0 ignored issues
show
Bug introduced by
The property arContext does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1959 12
								$eventData = ar_events::fire('onbeforecall', $eventData);
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1960 12
								$ARCurrent->arResult = $eventData->arResult;
1961 12
								$AR->contextCallHandler = false;
1962 12
								$continue = ($eventData!=false);
1963 6
							}
1964 12
							if ( $continue ) {
1965 12
								if (!isset($ARCurrent->cacheCallChainSettings)) {
1966
									$ARCurrent->cacheCallChainSettings = array();
1967
								}
1968 12
								if ($ARConfig->cache[$this->path]->inConfigIni == false) {
1969 8
									$ARCurrent->cacheCallChainSettings[$this->id] = $config->cacheSettings;
1970 4
								}
1971
1972 12
								if ($ARCurrent->ARShowTemplateBorders) {
1973
									echo "<!-- arTemplateStart\nData: ".$this->type." ".$this->path." \nTemplate: ".$template["arCallTemplatePath"]." ".$template["arCallTemplate"]." \nLibrary:".$template["arLibrary"]." -->";
1974
								}
1975 12
								set_error_handler(array('pobject','pinpErrorHandler'),error_reporting());
1976 12
								$func = ar('template')->get($template['arCallTemplatePath'],$template['arCallTemplate']);
1977 12
								if(is_callable($func)){
1978 12
									$arResult = $func($this);
1979 6
								}
1980 12
								restore_error_handler();
1981 12
								if (isset($arResult)) {
1982 12
									$ARCurrent->arResult=$arResult;
1983 6
								}
1984 12
								if ($ARCurrent->ARShowTemplateBorders) {
1985
									echo "<!-- arTemplateEnd -->";
1986
								}
1987 12 View Code Duplication
								if ( !$AR->contextCallHandler ) { /* prevent oncall from re-entering here */
1988 12
									$AR->contextCallHandler = true;
1989 12
									$temp = $ARCurrent->arResult; /* event listeners will change ARCurrent->arResult */
1990 12
									$eventData->arResult = $temp;
1991 12
									ar_events::fire('oncall', $eventData );
1992 12
									$ARCurrent->arResult = $temp; /* restore correct result */
1993 12
									$AR->contextCallHandler = false;
1994 6
								}
1995 6
							}
1996 6
						}
1997 12
						array_pop($ARCurrent->arCallStack);
1998 12
						$this->popContext();
1999
2000 12
						if ( !$initialConfigChecked && $arCallFunction != 'config.ini' ) {
2001
							// this template was the first template called in this request.
2002
							$eventData = new object();
2003
							$eventData->arCallArgs = $arCallArgs;
2004
							$eventData->arCallFunction = $arCallFunction;
2005
							ar_events::fire( 'onview', $eventData ); // no default action to prevent, so ignore return value.
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2006
						}
2007 12
						return false;
2008
					} else {
2009 4
						debug("pobject: CheckConfig: no such file: ".$template["arTemplateId"].$template["arCallTemplate"]."","all");
2010
					}
2011 2
				} else {
2012 48
					debug("CheckConfig: no arCallTemplate ($arCallFunction from '$this->path')","object");
2013
				}
2014
2015 26
			}
2016
		}
2017 56
		return true;
2018
	}
2019
2020 24
	public function ClearCache($path="", $private=true, $recurse=false) {
2021 24
	global $AR;
2022 24
		$norealnode = false;
2023 24
		if (!$path) {
2024
			$path=$this->path;
2025
		} else {
2026 24
			$realpath = current($this->get($path, "system.get.path.phtml"));
2027 24
			if($realpath != false) {
2028 24
				$path = $realpath;
2029 12
			} else {
2030
				$norealnode = true;
2031
			}
2032
		}
2033
2034 24
		if($norealnode !== true) {
2035
			/*
2036
				we don't want to recurse to the currentsite, because the path
2037
				doesn't exists in the database, so it doesn't have a currentsite
2038
2039
				the privatecache should be emptied by delete, or by the cleanup
2040
				cronjob. The current path doesn't exists in the database, so a
2041
				object id which is needed to find the node in the cache, isn't
2042
				available
2043
			*/
2044
2045 24
			if ($private ) {
2046
				// now remove any private cache entries.
2047
				// FIXME: this doesn't scale very well.
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "this doesn't scale very well"
Loading history...
2048
				//        only scalable solution is storage in a database
2049
				//        but it will need the original path info to
2050
				//        remove recursively fast enough.
2051
				//        this means a change in the filestore api. -> 2.5
2052
2053
				// Use chunks of max 5000 objects at a time to be more memory-efficient;
2054 24
				$pcache=$this->store->get_filestore("privatecache");
2055 24
				if ($recurse) {
2056
					$offset = 0;
2057
					$limit = 5000;
2058
					$ids=$this->store->info($this->store->find($path, "" , $limit, $offset));
2059
					while (is_array($ids) && count($ids)) {
2060
						foreach($ids as $value) {
2061
							$eventData = new object();
2062
							$eventData = ar_events::fire( 'onbeforeclearprivatecache', $eventData, $value['type'], $value['path'] );
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2063
							if ( !$eventData ) {
2064
								continue;
2065
							}
2066
2067
							$pcache->purge($value["id"]);
2068
							ar_events::fire( 'onclearprivatecache', $eventData, $value['type'], $value['path'] );
2069
						}
2070
2071
						$offset += $limit;
2072
						$ids = $this->store->info($this->store->find($path, "", $limit, $offset));
2073
					}
2074
				} else {
2075 24
					$eventData = new object();
2076 24
					$eventData = ar_events::fire( 'onbeforeclearprivatecache', $eventData, $this->type, $this->path );
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2077 24
					if ( $eventData ) {
2078 24
						$pcache->purge($this->id);
2079 24
						ar_events::fire( 'onclearprivatecache', $eventData, $this->type, $this->path );
2080 12
					}
2081
				}
2082 12
			}
2083
2084
			// now clear all parents untill the current site
2085 24
			$site=$this->currentsite($path);
2086 24
			$project=$this->currentproject($path);
2087 24
			if ($path!=$site && $path != $project && $path!='/') {
2088 24
				$parent=$this->make_path($path.'../');
2089 24
				$this->ClearCache($parent, $private, false);
2090 12
			}
2091 12
		}
2092 24
		$recursed = array();
2093
2094
		// filesystem cache image filenames are always lower case, so
2095
		// use special path for that. Remember 'real' path name for
2096
		// recursion and stuff
2097 24
		$fs_path=strtolower($path);
2098 24
		$nlslist=$AR->nls->list;
2099 24
		$nlslist["."]="default";
2100 24
		$cache_types[] = "normal";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$cache_types was never initialized. Although not strictly required by PHP, it is generally a good practice to add $cache_types = 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...
2101 24
		$cache_types[] = "compressed";
2102 24
		$cache_types[] = "session";
2103
2104 24
		global $cache_config,$store_config;
2105 24
		$cachestore=new cache($cache_config);
2106
2107
2108 24
		$filestore = $this->store->get_config("files");
2109 24
		foreach($cache_types as $type){
2110 24
			foreach($nlslist as $nls => $language){
2111
				// break away if nls doesn't exists
2112
				// is dir is cached, so it should not cost more that it add's in speed
2113 24
				if(!is_dir($filestore."cache/$type/$nls")){
2114 24
					continue;
2115
				}
2116
2117
				$fpath=$filestore."cache/$type/$nls".$fs_path;
2118
				$hpath=$filestore."cacheheaders/$type/$nls".$fs_path;
2119
				if ($dir=@dir($fpath)) {
2120
					while (false !== ($entry = $dir->read())) {
2121
						if ($entry!="." && $entry!="..") {
2122
							if (is_file($fpath.$entry)) {
2123
								@unlink($fpath.$entry);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2124
								@unlink($hpath.$entry);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2125
								$cachestore->delete("/".$type."/".$nls.$fs_path.$entry);
2126
							} else if ( $recurse && !$recursed[$entry]) {
2127
								$this->ClearCache($path.$entry."/", false, true);
2128
								$recursed[$entry]=true;
2129
							}
2130
						}
2131
					}
2132
					$dir->close();
2133
					// remove empty directory entry's, hide errors about directory entry's with content
2134
					@rmdir($fpath);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2135
					@rmdir($hpath);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2136
				} else if (file_exists(substr($fpath,0,-1)."=")) {
2137
					@unlink(substr($fpath,0,-1)."=");
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2138
					@unlink(substr($hpath,0,-1)."=");
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2139 12
					$cachestore->delete("/".$type."/".$nls.substr($fs_path,0,-1)."=");
2140
				}
2141 12
			}
2142 12
		}
2143 24
	}
2144
2145
	public function getcache($name, $nls="") {
2146
		global $ARCurrent, $ARnls;
2147
		$result=false;
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
2148
		$this->error = '';
2149
		if ($name) {
2150
			$result=false;
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
2151
			if (!$nls) {
2152
				$nls=$this->nls;
2153
			}
2154
			$file=$nls.".".$name;
2155
2156
			$minfresh = time();
2157
			if (isset($ARCurrent->RequestCacheControl["min-fresh"])) {
2158
				$minfresh += $ARCurrent->RequestCacheControl["min-fresh"];
2159
			}
2160
2161
			$pcache=$this->store->get_filestore("privatecache");
2162
			if ( $pcache->exists($this->id, $file) &&
2163
			     ($pcache->mtime($this->id, $file) > ($minfresh) )  ) {
2164
2165
				$result = $pcache->read($this->id, $file);
2166
2167
				$contentType = $ARCurrent->ldHeaders['content-type'];
2168
				if (preg_match('|^content-type:[ ]*([^ /]+)/|i', $contentType, $matches)) {
2169
					$contentType = $matches[1];
2170
				} else {
2171
					$contentType = '';
2172
				}
2173
2174 View Code Duplication
				if (!$contentType || strtolower($contentType) == 'text') {
2175
					require_once($this->store->get_config('code')."modules/mod_url.php");
2176
					$temp = explode('.', $file);
2177
					$imageNLS = $temp[0];
2178
					$result = URL::ARtoRAW($result, $imageNLS);
0 ignored issues
show
Unused Code introduced by
The call to URL::ARtoRAW() has too many arguments starting with $imageNLS.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2179
				}
2180
			} else {
2181
				$result=false;
2182
				$ARCurrent->cache[]=$file;
2183
				ob_start();
2184
				/* output buffering is recursive, so this won't interfere with
2185
				   normal page caching, unless you forget to call savecache()...
2186
				   so normal pagecache needs to check $ARCurrent->cache, if it's
2187
				   not empty, issue a warning and don't cache the outputbuffer...
2188
				   savecache() must then pop the stack.
2189
				*/
2190
			}
2191
		} else {
2192
			$this->error = ar::error($ARnls["err:nonamecache"], 1111);
2193
			$result = false;
2194
		}
2195
		return $result;
2196
	}
2197
2198
	public function cached($name, $nls="") {
2199
		if ($image=$this->getcache($name, $nls)) {
2200
			echo $image;
2201
			$result=true;
2202
		} else {
2203
			$result=false;
2204
		}
2205
		return $result;
2206
	}
2207
2208
	public function savecache($time="") {
2209
		global $ARCurrent, $ARnls, $DB;
2210
		$result = false;
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
2211
		$this->error = '';
2212
		if (!$time) {
2213
			$time=2; // 'freshness' in hours.
2214
		}
2215
		if ($file=array_pop($ARCurrent->cache)) {
2216
			$image=ob_get_contents();
2217
			if ($image !== false) {
2218
				$result = true;
2219
				$origimage = $image;
2220
2221
				$contentType = $ARCurrent->ldHeaders['content-type'];
2222
				if (preg_match('|^content-type:[ ]*([^ /]+)/|i', $contentType, $matches)) {
2223
					$contentType = $matches[1];
2224
				} else {
2225
					$contentType = '';
2226
				}
2227
2228 View Code Duplication
				if (!$contentType || strtolower($contentType) == 'text') {
2229
					require_once($this->store->get_config('code')."modules/mod_url.php");
2230
					$temp = explode('.', $file);
2231
					$imageNLS = $temp[0];
2232
					$image = URL::RAWtoAR($image, $imageNLS);
2233
				}
2234
2235
				if( $time > 0  && $DB["wasUsed"] == 0) {
2236
					$pcache=$this->store->get_filestore("privatecache");
2237
					$pcache->write($image, $this->id, $file);
2238
					$time=time()+($time*3600);
2239 View Code Duplication
					if (!$pcache->touch($this->id, $file, $time)) {
2240
						$this->error = ar::error("savecache: ERROR: couldn't touch $file", 1113);
2241
						$result = false;
2242
					}
2243
				}
2244
				ob_end_clean();
2245
				echo $origimage;
2246
			} else {
2247
				debug("skipped saving cache - ob_get_contents returned false so output buffering was not active", "all");
2248
				$result = false;
2249
			}
2250
		} else {
2251
			$this->error = ar::error($ARnls["err:savecachenofile"], 1112);
2252
			$result = false;
2253
		}
2254
		return $result;
2255
	}
2256
2257
	public function getdatacache($name) {
2258
		global $ARCurrent, $ARnls;
2259
		$result=false;
2260
		$this->error = '';
2261
		if ($name) {
2262
2263
			$minfresh = time();
2264
			if (isset($ARCurrent->RequestCacheControl["min-fresh"])) {
2265
				$minfresh += $ARCurrent->RequestCacheControl["min-fresh"];
2266
			}
2267
2268
			$pcache=$this->store->get_filestore("privatecache");
2269
			if ( $pcache->exists($this->id, $name) &&
2270
			     ($pcache->mtime($this->id, $name) > $minfresh) ) {
2271
				$result = unserialize($pcache->read($this->id, $name));
2272
			} else {
2273
				debug("getdatacache: $name doesn't exists, returning false.","all");
2274
			}
2275
		} else {
2276
			$this->error = ar::error($ARnls["err:nonamecache"], 1111);
2277
		}
2278
		return $result;
2279
	}
2280
2281
	public function savedatacache($name,$data,$time="") {
2282
		global $DB;
2283
		$this->error = '';
2284
		if (!$time) {
2285
			$time=2; // 'freshness' in hours.
2286
		}
2287
		$pcache=$this->store->get_filestore("privatecache");
2288
		if( $time > 0  && $DB["wasUsed"] == 0) {
2289
			$pcache->write(serialize($data), $this->id, $name);
2290
			$time=time()+($time*3600);
2291 View Code Duplication
			if (!$pcache->touch($this->id, $name, $time)) {
2292
				$this->error = ar::error('Could not touch '.$name, 1113);
2293
				return false;
2294
			}
2295
		}
2296
		return true;
2297
	}
2298
2299 52
	public function getdata($varname, $nls="none", $emptyResult=false) {
0 ignored issues
show
Coding Style introduced by
getdata uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
getdata uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2300
	// function to retrieve variables from $this->data, with the correct
2301
	// language version.
2302 52
	global $ARCurrent;
2303
2304 52
		$result = false;
2305 52
		if ($nls!="none") {
2306 48 View Code Duplication
			if ($ARCurrent->arCallStack) {
2307 48
				$arCallArgs=end($ARCurrent->arCallStack);
2308 48
				if (isset($arCallArgs) && is_array($arCallArgs)) {
2309 48
					extract($arCallArgs);
2310 24
				} else if (is_string($arCallArgs)) {
2311
					Parse_Str($arCallArgs);
2312
				}
2313 24
			}
2314 48
			if (isset(${$nls}[$varname])) {
2315 28
				$result=${$nls}[$varname];
2316 48
			} else if (isset($ARCurrent->$nls) && isset($ARCurrent->$nls->$varname)) {
2317
				$result=$ARCurrent->$nls->$varname;
2318 48
			} else if (($values=$_POST[$nls]) && isset($values[$varname])) {
2319
				$result=$values[$varname];
2320 48
			} else if (($values=$_GET[$nls]) && isset($values[$varname])) {
2321
				$result=$values[$varname];
2322 48
			} else if (($arStoreVars=$_POST["arStoreVars"]) && isset($arStoreVars[$nls][$varname])) {
2323
				$result=$arStoreVars[$nls][$varname];
2324 48
			} else if (($arStoreVars=$_GET["arStoreVars"]) && isset($arStoreVars[$nls][$varname])) {
2325
				$result=$arStoreVars[$nls][$varname];
2326
			}
2327 48
			if ($result===false) {
2328 48
				if (isset($this->data->${nls}) && isset($this->data->${nls}->${varname})) {
2329 36
					$result=$this->data->${nls}->${varname};
2330 12
				}
2331 24
			}
2332 24
		} else { // language independant variable.
2333 52 View Code Duplication
			if ($ARCurrent->arCallStack) {
2334 52
				$arCallArgs=end($ARCurrent->arCallStack);
2335 52
				if (isset($arCallArgs) && is_array($arCallArgs)) {
2336 48
					extract($arCallArgs);
2337 34
				} else if (is_string($arCallArgs)) {
2338
					Parse_Str($arCallArgs);
2339
				}
2340 26
			}
2341 52
			if (isset($$varname)) {
2342 24
				$result=$$varname;
2343 52
			} else if (isset($ARCurrent->$varname)) {
2344
				$result=$ARCurrent->$varname;
2345 52 View Code Duplication
			} else if (isset($_POST[$varname])) {
2346
				$result=$_POST[$varname];
2347 52
			} else if (isset($_GET[$varname])) {
2348
				$result=$_GET[$varname];
2349 52
			} else if (($arStoreVars=$_POST["arStoreVars"]) && isset($arStoreVars[$varname])) {
2350
				$result=$arStoreVars[$varname];
2351 52
			} else if (($arStoreVars=$_GET["arStoreVars"]) && isset($arStoreVars[$varname])) {
2352
				$result=$arStoreVars[$varname];
2353
			}
2354 52
			if ($result===false) {
2355 52
				if (isset($this->data->$varname)) {
2356 24
					$result=$this->data->$varname;
2357 12
				}
2358 26
			}
2359
		}
2360 52
		if ( $result === false ) {
2361 52
			$result = $emptyResult;
2362 26
		}
2363 52
		return $result;
2364
	}
2365
2366
	public function showdata($varname, $nls="none", $emptyResult=false) {
2367
		echo htmlspecialchars($this->getdata($varname, $nls, $emptyResult), ENT_QUOTES, 'UTF-8');
2368
	}
2369
2370
	public function setnls($nls) {
2371
		ldSetNls($nls);
2372
	}
2373
2374
	public function getcharset() {
2375
		return "UTF-8";
2376
	}
2377
2378
	public function HTTPRequest($method, $url, $postdata = "", $port=80 ) {
2379
		$maxtries = 5;
2380
		$tries = 0;
2381
		$redirecting = true;
2382
2383
		if(isset($postdata) && is_array($postdata)) {
2384
			foreach($postdata as $key=>$val) {
2385
				if(!is_integer($key)) {
2386
					$data .= "$key=".urlencode($val)."&";
0 ignored issues
show
Bug introduced by
The variable $data 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...
2387
				}
2388
			}
2389
		} else {
2390
			$data = $postdata;
2391
		}
2392
2393
		while ($redirecting && $tries < $maxtries) {
2394
			$tries++;
2395
			// get host name and URI from URL, URI not needed though
2396
			preg_match("/^([htps]*:\/\/)?([^\/]+)(.*)/i", $url, $matches);
2397
			$host = $matches[2];
2398
			$uri = $matches[3];
2399
			if (!$matches[1]) {
2400
				$url="http://".$url;
2401
			}
2402
			$connection = @fsockopen( $host, $port, $errno, $errstr, 120);
2403
			if( $connection ) {
2404
				if( strtoupper($method) == "GET" ) {
2405
					if ($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2406
						$uri .= "?" . $data;
2407
					}
2408
					fputs( $connection, "GET $uri HTTP/1.0\r\n");
2409
				} else if( strtoupper($method) == "POST" ) {
2410
					fputs( $connection, "POST $uri HTTP/1.0\r\n");
2411
				} else {
2412
					fputs( $connection, "$method $uri HTTP/1.0\r\n");
2413
				}
2414
2415
				fputs( $connection, "Host: $host\r\n");
2416
				fputs( $connection, "Accept: */*\r\n");
2417
				fputs( $connection, "Accept: image/gif\r\n");
2418
				fputs( $connection, "Accept: image/x-xbitmap\r\n");
2419
				fputs( $connection, "Accept: image/jpeg\r\n");
2420
2421
				if( strtoupper($method) == "POST" ) {
2422
					$strlength = strlen( $data);
2423
					fputs( $connection, "Content-type: application/x-www-form-urlencoded\r\n" );
2424
					fputs( $connection, "Content-length: ".$strlength."\r\n\r\n");
2425
					fputs( $connection, $data."\r\n");
2426
				}
2427
2428
				fputs( $connection, "\r\n" , 2);
2429
2430
				$headerContents = '';
2431
				$headerStart = 0;
2432
				$headerEnd = 0;
2433
				$redirecting = false;
2434
2435
				while (!feof($connection)) {
2436
					$currentLine = fgets ($connection, 1024);
2437
					if ($headerEnd && $redirecting) {
2438
						break;
2439
					} else if ($headerEnd && !$redirecting) {
2440
						//this is the html from the page
2441
						$contents = $contents . $currentLine;
0 ignored issues
show
Bug introduced by
The variable $contents 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...
2442
					} else if ( preg_match("/^HTTP/", $currentLine) ) {
2443
						//came to the start of the header
2444
						$headerStart = 1;
2445
						$headerContents = $currentLine;
2446
					} else if ( $headerStart && preg_match('/^[\n\r\t ]*$/', $currentLine) ) {
2447
						//came to the end of the header
2448
						$headerEnd = 1;
2449
					} else {
2450
						//this is the header, if you want it...
2451
						if (preg_match("/^Location: (.+?)\n/is",$currentLine,$matches) ) {
2452
							$headerContents .= $currentLine;
2453
							//redirects are sometimes relative
2454
							$newurl = $matches[1];
2455
							if (!preg_match("/http:\/\//i", $newurl, $matches) ) {
2456
								$url .= $newurl;
2457
							} else {
2458
								$url = $newurl;
2459
							}
2460
							//extra \r's get picked up sometimes
2461
							//i think only with relative redirects
2462
							//this is a quick fix.
2463
							$url = preg_replace("/\r/s","",$url);
2464
							$redirecting = true;
2465
						} else {
2466
							$headerContents.=$currentLine;
2467
						}
2468
					}
2469
				}
2470
			} else {
2471
				$this->error="$errstr ($errno)";
2472
				$contents=false;
2473
				$url = "";
2474
			}
2475
			@fclose($connection);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2476
		}
2477
		if (($method!="GET") && ($method!="POST")) {
2478
			$contents=$headerContents."\n".$contents;
0 ignored issues
show
Bug introduced by
The variable $headerContents 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...
2479
		}
2480
		return $contents;
2481
	}
2482
2483
	public function make_filesize( $size="" ,$precision=0) {
2484
		$suffixes = array('B','KB','MB','GB','TB','PB','EB','ZB','YB');
2485
2486
		if( $size === "" ) {
2487
			$size = $this->size;
0 ignored issues
show
Bug introduced by
The property size does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
2488
		}
2489
		while ( (count($suffixes) > 1) && ($size > 1024) ){
2490
			$size = $size / 1024;
2491
			array_shift($suffixes);
2492
		}
2493
		$size = round($size,$precision);
2494
		if($precision==0){ // compatible with the old make_filesize
2495
			$size = intval($size);
2496
		}
2497
		$result = $size." ".array_shift($suffixes);
2498
		return $result;
2499
	}
2500
2501
	public function convertToUTF8($data, $charset = "CP1252") {
2502
2503
		include_once($this->store->get_config("code")."modules/mod_unicode.php");
2504
2505
		if (isset($data) && is_array($data)) {
2506
			foreach($data as $key => $val){
2507
				$data[$key] = $this->convertToUTF8($val, $charset);
2508
			}
2509
		} else
2510
		if (is_object($data)) {
2511
			foreach($data as $key => $val){
2512
				$data->$key = $this->convertToUTF8($val, $charset);
2513
			}
2514
		} else {
2515
			$data = unicode::convertToUTF8($charset, $data);
2516
		}
2517
		return $data;
2518
	}
2519
2520 28
	public function resetloopcheck() {
2521 28
		global $ARBeenHere;
2522 28
		$ARBeenHere=array();
2523 28
	}
2524
2525
/********************************************************************
2526
2527
  "safe" functions.
2528
2529
  The following functions are safe versions of existing functions
2530
  above.
2531
  - They don't change anything in the database.
2532
    This means that to save/delete something, a user will need to call
2533
    "system.save.data.phtml" or "system.delete.phtml" which check grants.
2534
  - All functions except _get and _exists don't take a path as
2535
    argument, they use the current objects path instead.
2536
2537
  These are meant to be used by 'pinp' versions of templates,
2538
  meaning user defined templates. 'pinp' rewrites call to functions
2539
  to the form '$this->_function'.
2540
2541
  All pinp files automatically first call CheckLogin('read').
2542
2543
********************************************************************/
2544
2545
	public function _call($function, $args="") {
2546
		// remove possible path information (greedy match)
2547
		if ( !( $function instanceof \Closure ) ) {
2548
			$function = basename( (string) $function );
2549
		}
2550
		return $this->call($function, $args);
0 ignored issues
show
Bug introduced by
It seems like $function can also be of type object<Closure>; however, ariadne_object::call() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Documentation introduced by
$args is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2551
	}
2552
2553
	public function _call_super($arCallArgs="") {
2554
	global $ARCurrent, $AR;
2555
		$context = $this->getContext();
2556
		if (!$arCallArgs) {
2557
			$arCallArgs = end($ARCurrent->arCallStack);
2558
		}
2559
		$arSuperContext  = (array)$context['arSuperContext'];
2560
		$arLibrary       = $context['arLibrary'];
2561
		$arLibraryPath   = $context['arLibraryPath'];
2562
		$arCallType      = $context['arCallTemplateType'];
2563
		$arSuperPath     = $context['arCallTemplatePath'];
2564
		$arLibrariesSeen = $context['arLibrariesSeen'];
2565
		$arCallFunction  = $arSuperFunction = $context['arCallFunction'];
2566
		if ($arLibrary) {
2567
			$arSuperFunction = str_replace($arLibrary.':', '', $arCallFunction);
2568
		}
2569
		if (strpos($arSuperFunction, "::") !== false) {
2570
			// template of a specific class defined via call("class::template");
2571
			list($arBaseType, $arSuperFunction)=explode("::", $arSuperFunction);
0 ignored issues
show
Unused Code introduced by
The assignment to $arBaseType is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
2572
		}
2573
		// remove current library path from the arLibrariesSeen array so that
2574
		// Ariadne will be able to re-enter the library and toggle the arSuperContext boolean there.
2575
		unset($arLibrariesSeen[$arLibraryPath]);
2576
		$arSuperContext[$arSuperPath.":".$arCallType.":".$arSuperFunction] = true;
2577
2578
		debug("call_super: searching for the template following (path: $arSuperPath; type: $arCallType; function: $arCallFunction) from $this->path");
2579
		// FIXME: Redirect code has to move to getPinpTemplate()
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "Redirect code has to move to getPinpTemplate"
Loading history...
2580
		$redirects	= $ARCurrent->shortcut_redirect;
2581
		if (isset($redirects) && is_array($redirects)) {
2582
			$redirpath = $this->path;
2583
			while (!$template['arTemplateId'] &&
0 ignored issues
show
Bug introduced by
The variable $template 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...
2584
				($redir = array_pop($redirects)) &&
2585
				$redir["keepurl"] &&
2586
				(substr($redirpath, 0, strlen($redir["dest"])) == $redir["dest"])
2587
			) {
2588
				debug("call_super: following shortcut redirect: $redirpath; to ".$redir["dest"]);
2589
				$template = $this->getPinpTemplate($arCallFunction, $redirpath, $redir["dest"], false, $arLibrariesSeen, $arSuperContext);
2590
				$redirpath = $redir['src'];
2591
			}
2592 View Code Duplication
			if (!$template["arTemplateId"]) {
2593
				$template = $this->getPinpTemplate($arCallFunction, $redirpath, '', false, $arLibrariesSeen, $arSuperContext);
2594
			}
2595
		}
2596 View Code Duplication
		if (!$template["arTemplateId"]) {
2597
			$template = $this->getPinpTemplate($arCallFunction, $this->path, '', false, $arLibrariesSeen, $arSuperContext);
2598
		}
2599
		if ($template["arCallTemplate"] && $template["arTemplateId"]) {
2600
			$exists = ar('template')->exists($template['arCallTemplatePath'],$template["arCallTemplate"]);
2601
			if ( $exists ) {
2602
				debug("call_super: found template ".$template["arCallTemplate"]." on object with id ".$template["arTemplateId"]);
2603
				$arLibrary = $template['arLibrary'];
2604
				debug("call_super: found template on ".$template["arTemplateId"]);
2605
				if (is_int($arLibrary)) {
2606
					// set the library name for unnamed libraries to 'current'
2607
					// so that calls using getvar('arLibrary') will keep on working
2608
					$arLibrary = "current";
2609
				}
2610 View Code Duplication
				if (!is_string($arCallArgs)) {
2611
					$arCallArgs['arCallFunction'] = $arCallFunction;
2612
					$arCallArgs['arLibrary'] = $arLibrary;
2613
					$arCallArgs['arLibraryPath'] = $template["arLibraryPath"];
2614
				}
2615
				$ARCurrent->arCallStack[]=$arCallArgs;
2616
				$this->pushContext(
2617
					array(
2618
						"scope"              => "pinp",
2619
						"arSuperContext"     => $arSuperContext,
2620
						"arLibrary"          => $arLibrary,
2621
						"arLibraryPath"      => $template['arLibraryPath'],
2622
						"arCallFunction"     => $arCallFunction,
2623
						"arCurrentObject"    => $this,
2624
						"arCallType"         => $template['arCallType'],
2625
						"arCallTemplateName" => $template['arCallTemplateName'],
2626
						"arCallTemplateNLS"  => $template['arCallTemplateNLS'],
2627
						"arCallTemplateType" => $template['arCallTemplateType'],
2628
						"arCallTemplatePath" => $template['arCallTemplatePath']
2629
					)
2630
				);
2631
				$continue = true;
2632
				$eventData = new object();
2633 View Code Duplication
				if ( !$AR->contextCallHandler ) { /* prevent onbeforecall from re-entering here */
2634
					$AR->contextCallHandler = true;
2635
					$eventData->arCallArgs = $arCallArgs;
0 ignored issues
show
Bug introduced by
The property arCallArgs does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2636
					$eventData->arCallFunction = $arCallFunction;
0 ignored issues
show
Bug introduced by
The property arCallFunction does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2637
					$eventData->arContext = $this->getContext();
0 ignored issues
show
Bug introduced by
The property arContext does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2638
					$eventData = ar_events::fire('onbeforecall', $eventData);
0 ignored issues
show
Documentation introduced by
$eventData is of type object<object>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2639
					$ARCurrent->arResult = $eventData->arResult;
2640
					$AR->contextCallHandler = false;
2641
					$continue = ($eventData!=false);
2642
				}
2643
				if ( $continue ) {
2644
					set_error_handler(array('pobject','pinpErrorHandler'),error_reporting());
2645
					$func = ar('template')->get($template['arCallTemplatePath'],$template['arCallTemplate']);
2646
					if(is_callable($func)){
2647
						$arResult = $func($this);
2648
					}
2649
					restore_error_handler();
2650
2651 View Code Duplication
					if ( !$AR->contextCallHandler ) { /* prevent oncall from re-entering here */
2652
						$AR->contextCallHandler = true;
2653
						$temp = $ARCurrent->arResult; /* event listeners will change ARCurrent->arResult */
2654
						$eventData->arResult = $arResult;
0 ignored issues
show
Bug introduced by
The variable $arResult 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...
2655
						ar_events::fire('oncall', $eventData );
2656
						$ARCurrent->arResult = $temp; /* restore correct result */
2657
						$AR->contextCallHandler = false;
2658
					}
2659
				}
2660
				array_pop($ARCurrent->arCallStack);
2661
				$this->popContext();
2662
			}
2663
		}
2664
		return $arResult;
2665
	}
2666
2667
	public function _get($path, $function="view.html", $args="") {
2668
		// remove possible path information (greedy match)
2669
		if ( !($function instanceof \Closure) ) {
2670
			$function = basename( (string) $function);
2671
		}
2672
		return $this->store->call($function, $args,
2673
			$this->store->get(
2674
				$this->make_path($path)));
2675
	}
2676
2677
	public function _call_object($object, $function, $args="") {
2678
		return $object->call($function, $args);
2679
	}
2680
2681 View Code Duplication
	public function _ls($function="list.html", $args="") {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2682
		// remove possible path information (greedy match)
2683
		if ( ! ( $function instanceof \Closure ) ) {
2684
			$function = basename( (string) $function );
2685
		}
2686
		return $this->store->call($function, $args,
2687
			$this->store->ls($this->path));
2688
	}
2689
2690 View Code Duplication
	public function _parents($function="list.html", $args="", $top="") {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2691
		// remove possible path information (greedy match)
2692
		if ( !($function instanceof \Closure ) ) {
2693
			$function = basename( (string) $function);
2694
		}
2695
		return $this->parents($this->path, $function, $args, $top);
2696
	}
2697
2698
	public function _find($criteria, $function="list.html", $args="", $limit=100, $offset=0) {
2699
		$this->error = '';
2700
		// remove possible path information (greedy match)
2701
		if ( !($function instanceof \Closure ) ) {
2702
			$function = basename( (string) $function);
2703
		}
2704
		$result = $this->store->call($function, $args,
2705
			$this->store->find($this->path, $criteria, $limit, $offset));
2706 View Code Duplication
		if ($this->store->error) {
2707
			$this->error = ar::error( ''.$this->store->error, 1107, $this->store->error );
2708
		}
2709
		return $result;
2710
	}
2711
2712
	public function _exists($path) {
2713
		return $this->store->exists($this->make_path($path));
2714
	}
2715
2716
	public function _implements($implements) {
2717
		return $this->AR_implements($implements);
2718
	}
2719
2720 52
	public function getvar($var) {
0 ignored issues
show
Coding Style introduced by
getvar uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
getvar uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2721 52
	global $ARCurrent, $ARConfig; // Warning: if you add other variables here, make sure you cannot get at it through $$var.
2722
2723 52 View Code Duplication
		if ($ARCurrent->arCallStack) {
2724 48
			$arCallArgs=end($ARCurrent->arCallStack);
2725 48
			if (isset($arCallArgs) && is_array($arCallArgs)) {
2726 36
				extract($arCallArgs);
2727 32
			} else if (is_string($arCallArgs)) {
2728
				Parse_Str($arCallArgs);
2729
			}
2730 24
		}
2731 52
		if (isset($$var) && ($var!='ARConfig')) {
2732 16
			$result=$$var;
2733 52
		} else if (isset($ARCurrent->$var)) {
2734
			$result=$ARCurrent->$var;
2735 52
		} else if (isset($ARConfig->pinpcache[$this->path][$var])) {
2736
			$result=$ARConfig->pinpcache[$this->path][$var];
2737 52 View Code Duplication
		} else if (isset($_POST[$var])) {
2738
			$result=$_POST[$var];
2739 52
		} else if (isset($_GET[$var])) {
2740
			$result=$_GET[$var];
2741 52
		} else if (($arStoreVars=$_POST["arStoreVars"]) && isset($arStoreVars[$var])) {
2742
			$result=$arStoreVars[$var];
2743 52
		} else if (($arStoreVars=$_GET["arStoreVars"]) && isset($arStoreVars[$var])) {
2744
			$result=$arStoreVars[$var];
2745
		}
2746 52
		return $result;
2747
	}
2748
2749
	public function _getvar($var) {
2750
		return $this->getvar($var);
2751
	}
2752
2753
	public function putvar($var, $value) {
2754
		global $ARCurrent;
2755
2756
		$ARCurrent->$var=$value;
2757
	}
2758
2759
	public function _putvar($var, $value) {
2760
		return $this->putvar($var, $value);
2761
	}
2762
2763
	public function _setnls($nls) {
2764
		$this->setnls($nls);
2765
	}
2766
2767
	// not exposed to pinp for obvious reasons
2768
	public function sgKey($grants) {
2769
		global $AR;
2770
		if( !$AR->sgSalt || !$this->CheckSilent("config") ) {
2771
			return false;
2772
		}
2773
		// serialize the grants so the order does not matter, mod_grant takes care of the sorting for us
2774
		$this->_load("mod_grant.php");
2775
		$mg = new mod_grant();
2776
		$grantsarray = array();
2777
		$mg->compile($grants, $grantsarray);
2778
		$grants = serialize($grantsarray);
2779
		return sha1( $AR->sgSalt . $grants . $this->path);
2780
	}
2781
2782
	public function sgBegin($grants, $key = '', $path = '.') {
2783
		global $AR;
2784
		$result = false;
2785
		$context = $this->getContext();
2786
		$path    = $this->make_path($path);
2787
2788
		// serialize the grants so the order does not matter, mod_grant takes care of the sorting for us
2789
		$this->_load("mod_grant.php");
2790
		$mg = new mod_grant();
2791
		$grantsarray = array();
2792
		$mg->compile($grants, $grantsarray);
2793
2794
		if ($context['scope'] == 'pinp') {
2795
			$checkgrants = serialize($grantsarray);
2796
			$check = ( $AR->sgSalt ? sha1( $AR->sgSalt . $checkgrants . $path) : false ); // not using suKey because that checks for config grant
2797
		} else {
2798
			$check = true;
2799
			$key = true;
2800
		}
2801
		if( $check !== false && $check === $key ) {
2802
			$AR->user->grants = array(); // unset all grants for the current user, this makes sure GetValidGrants gets called again for this path and all childs
2803
			$grantsarray = (array)$AR->sgGrants[$path];
2804
			$mg->compile($grants, $grantsarray);
2805
			$AR->sgGrants[$path] = $grantsarray;
2806
			$result = true;
2807
		}
2808
		return $result;
2809
	}
2810
2811
	public function sgEnd($path = '.') {
2812
		global $AR;
2813
		$AR->user->grants = array(); // unset all grants for the current user, this makes sure GetValidGrants gets called again for this path and all childs
2814
		$path = $this->make_path( $path );
2815
		unset($AR->sgGrants[$path]);
2816
		return true; // temp return true;
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...
2817
	}
2818
2819
	public function sgCall($grants, $key, $function="view.html", $args="") {
2820
		$result = false;
2821
		if( $this->sgBegin($grants, $key ) ) {
2822
			$result = $this->call($function, $args);
0 ignored issues
show
Documentation introduced by
$args is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2823
			$this->sgEnd();
2824
		}
2825
		return $result;
2826
	}
2827
2828
	public function _sgBegin($grants, $key, $path = '.') {
2829
		return $this->sgBegin($grants, $key, $path);
2830
	}
2831
2832
	public function _sgEnd($path = '.') {
2833
		return $this->sgEnd($path);
2834
	}
2835
2836
	public function _sgCall($grants, $key, $function="view.html", $args="") {
2837
		return $this->sgCall($grants, $key, $function, $args);
2838
	}
2839
2840
	public function _widget($arWidgetName, $arWidgetTemplate, $arWidgetArgs="", $arWidgetType="lib") {
2841
	global $AR, $ARConfig, $ARCurrent, $ARnls;
2842
2843
		$arWidgetName=preg_replace("/[^a-zA-Z0-9\/]/","",$arWidgetName);
2844
		$arWidgetTemplate=preg_replace("/[^a-zA-Z0-9\.]/","",$arWidgetTemplate);
2845
		$wgResult=null;
2846
		if ($arWidgetType=="www") {
2847
			$coderoot=$AR->dir->root;
2848
		} else {
2849
			$coderoot=$this->store->get_config("code");
2850
		}
2851
		if (file_exists($coderoot."widgets/$arWidgetName")) {
2852
			if (file_exists($coderoot."widgets/$arWidgetName/$arWidgetTemplate")) {
2853
				if (isset($arWidgetArgs) && is_array($arWidgetArgs)) {
2854
					extract($arWidgetArgs);
2855
				} else if (is_string($arWidgetArgs)) {
2856
					Parse_str($arWidgetArgs);
2857
				}
2858
				include($coderoot."widgets/$arWidgetName/$arWidgetTemplate");
2859
			} else {
2860
				error("Template $arWidgetTemplate for widget $arWidgetName not found.");
2861
			}
2862
		} else {
2863
			error(sprintf($ARnls["err:widgetnotfound"],$arWidgetName));
2864
		}
2865
		if ($wgResult) {
2866
			return $wgResult;
2867
		}
2868
	}
2869
2870
	public function _getdata($varname, $nls="none", $emptyResult=false) {
2871
		return $this->getdata($varname, $nls, $emptyResult);
2872
	}
2873
2874
	public function _showdata($varname, $nls="none", $emptyResult=false) {
2875
		$this->showdata($varname, $nls, $emptyResult);
2876
	}
2877
2878
	public function _gettext($index=false) {
2879
	global $ARnls;
2880
		if (!$index) {
2881
			return $ARnls;
2882
		} else {
2883
			return $ARnls[$index];
2884
		}
2885
	}
2886
2887
	public function _loadtext($nls, $section="") {
2888
	global $ARnls, $ARCurrent;
2889
		if( is_object($ARnls) ) {
2890
			$ARnls->load($section, $nls);
2891
			$ARnls->setLanguage($nls);
2892
			$this->ARnls = $ARnls;
0 ignored issues
show
Bug introduced by
The property ARnls does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
2893
		} else { // older loaders and other shizzle
2894
2895
			$nls = preg_replace('/[^a-z]*/i','',$nls);
2896
			$section = preg_replace('/[^a-z0-9\._:-]*/i','',$section);
2897
			if (!$section) {
2898
				include($this->store->get_config("code")."nls/".$nls);
2899
				$this->ARnls = array_merge((array)$this->ARnls, $ARnls);
2900
			} else {
2901
				$nlsfile = $this->store->get_config("code")."nls/".$section.".".$nls;
2902
				if(strpos($nlsfile, ':') === false && file_exists($nlsfile)) {
2903
					include($nlsfile);
2904
					$this->ARnls = array_merge((array)$this->ARnls, $ARnls);
2905
				} else {
2906
					// current result;
2907
					$arResult = $ARCurrent->arResult;
2908
					$this->pushContext(array());
2909
						$oldnls = $this->reqnls;
2910
						$this->reqnls = $nls;
2911
						$this->CheckConfig($section, array('nls' => $nls));
0 ignored issues
show
Documentation introduced by
array('nls' => $nls) is of type array<string,?,{"nls":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2912
						$this->reqnls = $oldnls;
2913
					$this->popContext();
2914
					// reset current result (CheckConfig may have changed it when it should not have).
2915
					$ARCurrent->arResult = $arResult;
2916
				}
2917
			}
2918
		}
2919
	}
2920
2921
	public function _startsession() {
2922
	global $ARCurrent;
2923
		ldStartSession(0);
2924
		return $ARCurrent->session->id;
2925
	}
2926
2927
	public function _putsessionvar($varname, $varvalue) {
2928
	global $ARCurrent;
2929
2930
		if ($ARCurrent->session) {
2931
			return $ARCurrent->session->put($varname, $varvalue);
2932
		} else {
2933
			return false;
2934
		}
2935
	}
2936
2937
	public function _getsessionvar($varname) {
2938
	global $ARCurrent;
2939
2940
		if ($ARCurrent->session) {
2941
			return $ARCurrent->session->get($varname);
2942
		} else {
2943
			return false;
2944
		}
2945
	}
2946
2947
	public function _setsessiontimeout($timeout = 0) {
2948
	global $ARCurrent;
2949
		if ($ARCurrent->session) {
2950
			return $ARCurrent->session->setTimeout($timeout);
2951
		} else {
2952
			return false;
2953
		}
2954
	}
2955
2956
	public function _killsession() {
2957
	global $ARCurrent;
2958
2959
		if ($ARCurrent->session) {
2960
			$ARCurrent->session->kill();
2961
			unset($ARCurrent->session);
2962
		}
2963
	}
2964
2965
	public function _sessionid() {
2966
	global $ARCurrent;
2967
		if ($ARCurrent->session) {
2968
			return $ARCurrent->session->id;
2969
		} else {
2970
			return 0;
2971
		}
2972
	}
2973
2974
	public function _resetloopcheck() {
2975
		return $this->resetloopcheck();
2976
	}
2977
2978
	public function _make_path($path="") {
2979
		return $this->make_path($path);
2980
	}
2981
2982
	public function _make_ariadne_url($path="") {
2983
		return $this->make_ariadne_url($path);
2984
	}
2985
2986
	public function _make_url($path="", $nls=false, $session=true, $https=null, $keephost=null) {
2987
		return $this->make_url($path, $nls, $session, $https, $keephost);
2988
	}
2989
2990
	public function _make_local_url($path="", $nls=false, $session=true, $https=null) {
2991
		return $this->make_local_url($path, $nls, $session, $https);
2992
	}
2993
2994
	public function _getcache($name, $nls='') {
2995
		return $this->getcache($name, $nls);
2996
	}
2997
2998
	public function _cached($name, $nls='') {
2999
		return $this->cached($name, $nls);
3000
	}
3001
3002
	public function _savecache($time="") {
3003
		return $this->savecache($time);
3004
	}
3005
3006
	public function _getdatacache($name) {
3007
		return $this->getdatacache($name);
3008
	}
3009
3010
	public function _savedatacache($name,$data,$time="")
3011
	{
3012
		return $this->savedatacache($name,$data,$time);
3013
	}
3014
3015 56
	public function currentsite($path="", $skipRedirects = false) {
3016 56
		global $ARCurrent, $ARConfig;
3017 56
		if (!$path) {
3018 48
			$path=$this->path;
3019 24
		}
3020 56
		$config=($ARConfig->cache[$path]) ? $ARConfig->cache[$path] : $this->loadConfig($path);
3021 56
		if (!$skipRedirects && @count($ARCurrent->shortcut_redirect)) {
3022
			$redir = end($ARCurrent->shortcut_redirect);
3023
			if ($redir["keepurl"] && substr($path, 0, strlen($redir["dest"])) == $redir["dest"]) {
3024
				if (substr($config->site, 0, strlen($redir["dest"]))!=$redir["dest"]) {
3025
					// search currentsite from the reference
3026
					$config = ($ARConfig->cache[$redir['src']]) ? $ARConfig->cache[$redir['src']] : $this->loadConfig($redir['src']);
3027
				}
3028
			}
3029
		}
3030 56
		return $config->site;
3031
	}
3032
3033
	public function parentsite($site) {
3034
	global $ARConfig;
3035
		$path=$this->store->make_path($site, "..");
3036
		$config=($ARConfig->cache[$path]) ? $ARConfig->cache[$path] : $this->loadConfig($path);
3037
		return $config->site;
3038
	}
3039
3040 4 View Code Duplication
	public function currentsection($path="") {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3041 4
	global $ARConfig;
3042 4
		if (!$path) {
3043 4
			$path=$this->path;
3044 2
		}
3045 4
		$config=($ARConfig->cache[$path]) ? $ARConfig->cache[$path] : $this->loadConfig($path);
3046 4
		return $config->section;
3047
	}
3048
3049 View Code Duplication
	public function parentsection($path) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3050
	global $ARConfig;
3051
		$path=$this->store->make_path($path, "..");
3052
		$config=($ARConfig->cache[$path]) ? $ARConfig->cache[$path] : $this->loadConfig($path);
3053
		return $config->section;
3054
	}
3055
3056 24 View Code Duplication
	public function currentproject($path="") {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
3057 24
	global $ARConfig;
3058 24
		if (!$path) {
3059
			$path=$this->path;
3060
		}
3061 24
		$config=($ARConfig->cache[$path]) ? $ARConfig->cache[$path] : $this->loadConfig($path);
3062 24
		return $config->project;
3063
	}
3064
3065
	public function parentproject($path) {
3066
	global $ARConfig;
3067
		$path=$this->store->make_path($path, "..");
3068
		$config=($ARConfig->cache[$path]) ? $ARConfig->cache[$path] : $this->loadConfig($path);
3069
		return $config->project;
3070
	}
3071
3072
	public function validateFormSecret() {
3073
		global $ARCurrent;
3074
		if (!$ARCurrent->session) {
3075
			return true;
3076
		}
3077
3078
		if ($ARCurrent->session && $ARCurrent->session->data && $ARCurrent->session->data->formSecret) {
3079
			$formSecret = $this->getvar("formSecret");
3080
			return ($formSecret === $ARCurrent->session->data->formSecret);
3081
		}
3082
		return false;
3083
	}
3084
3085
	public function _validateFormSecret() {
3086
		return $this->validateFormSecret();
3087
	}
3088
3089
	public function getValue($name, $nls=false) {
3090
	global $ARCurrent;
3091
		switch ($nls) {
3092
			case "none":
3093
				$result = $this->data->$name;
3094
			break;
3095
			case false:
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
3096
				$nls = $ARCurrent->nls;
3097
				if (!isset($this->data->$nls) || !isset($this->data->$nls->$name)) {
3098
					$result = $this->data->$name;
3099
					break;
3100
				}
3101
			default:
3102
				$result = $this->data->$nls->$name;
3103
		}
3104
		return $result;
3105
	}
3106
3107
	public function setValue($name, $value, $nls=false) {
3108
3109
	global $AR, $ARConfig;
3110
		if ($value === null) {
3111
			if ($nls && $nls!="none") {
3112
				unset($this->data->$nls->$name);
3113
				if (!count(get_object_vars($this->data->$nls))) {
3114
					unset($this->data->$nls);
3115
					unset($this->data->nls->list[$nls]);
3116
					if (!count($this->data->nls->list)) {
3117
						unset($this->data->nls->list);
3118
						unset($this->data->nls);
3119
					} else {
3120
						if ($this->data->nls->default == $nls) {
3121
							if ($this->data->nls->list[$ARConfig->nls->default]) {
3122
								$this->data->nls->default = $ARConfig->nls->default;
3123
							} else {
3124
								list($this->data->nls->default) = each($this->data->nls->list);
3125
							}
3126
						}
3127
					}
3128
				}
3129
			} else {
3130
				unset($this->data->$name);
3131
			}
3132
		} else
3133
		if (!$nls) {
3134
			$this->data->$name = $value;
3135
		} else {
3136
			if (!$this->data->$nls) {
3137
				$this->data->$nls = new object;
3138
				if (!$this->data->nls) {
3139
					$this->data->nls = new object;
3140
					$this->data->nls->default = $nls;
0 ignored issues
show
Bug introduced by
The property default does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
3141
				}
3142
				$this->data->nls->list[$nls] = $AR->nls->list[$nls];
0 ignored issues
show
Bug introduced by
The property list does not seem to exist in object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
3143
			}
3144
			$this->data->$nls->$name = $value;
3145
		}
3146
	}
3147
3148
	public function showValue($name, $nls=false) {
3149
		$result = $this->getValue($name, $nls);
3150
		echo $result;
3151
		return $result;
3152
	}
3153
3154
	public function _getValue($name, $nls=false) {
3155
		return $this->getValue($name, $nls);
3156
	}
3157
3158
	public function _setValue($name, $value, $nls=false) {
3159
		return $this->setValue($name, $value, $nls);
3160
	}
3161
3162
	public function _showValue($name, $nls=false) {
3163
		return $this->showValue($name, $nls);
3164
	}
3165
3166
	public function _currentsite($path="", $skipRedirects = false) {
3167
		return $this->currentsite( $path, $skipRedirects );
3168
	}
3169
3170
	public function _parentsite($site) {
3171
		return $this->parentsite($site);
3172
	}
3173
3174
	public function _currentsection() {
3175
		return $this->currentsection();
3176
	}
3177
3178
	public function _parentsection($section) {
3179
		return $this->parentsection($section);
3180
	}
3181
3182
	public function _currentproject() {
3183
		return $this->currentproject();
3184
	}
3185
3186
	public function _parentproject($path) {
3187
		return $this->parentproject($path);
3188
	}
3189
3190
	public function _checkAdmin($user) {
3191
		return $this->CheckAdmin($user);
3192
	}
3193
3194
	public function _checkgrant($grant, $modifier=ARTHISTYPE, $path=".") {
3195
		// as this is called within a pinp template,
3196
		// all the grants are already loaded, so
3197
		// checksilent will fullfill our needs
3198
		$this->pushContext(array("scope" => "php"));
3199
			$result = $this->CheckSilent($grant, $modifier, $path);
3200
		$this->popContext();
3201
		return $result;
3202
	}
3203
3204
	public function _checkpublic($grant, $modifier=ARTHISTYPE) {
3205
3206
		return $this->CheckPublic($grant, $modifier);
3207
	}
3208
3209
	public function _getcharset() {
3210
		return $this->getcharset();
3211
	}
3212
3213
	public function _count_find($query='') {
3214
		return $this->count_find($this->path, $query);
3215
	}
3216
3217
	public function _count_ls() {
3218
		return $this->count_ls($this->path);
3219
	}
3220
3221
	public function _HTTPRequest($method, $url, $postdata = "", $port=80) {
3222
		return $this->HTTPRequest($method, $url, $postdata, $port);
3223
	}
3224
3225
	public function _make_filesize( $size="" ,$precision=0) {
3226
		return $this->make_filesize( $size ,$precision);
3227
	}
3228
3229
	public function _convertToUTF8($data, $charset = "CP1252") {
3230
		return $this->convertToUTF8($data,$charset);
3231
	}
3232
3233
	public function _getuser() {
3234
	global $AR;
3235
		if ($AR->pinp_user && $AR->pinp_user->data->login == $AR->user->data->login) {
3236
			$user = $AR->pinp_user;
3237
		} else {
3238
			$this->pushContext(array("scope" => "php"));
3239
				if ( $AR->user instanceof ariadne_object ) {
3240
					$user = current($AR->user->get(".", "system.get.phtml"));
3241
				} else {
3242
					$user = $AR->user;
3243
				}
3244
				$AR->pinp_user = $user;
3245
			$this->popContext();
3246
		}
3247
		return $user;
3248
	}
3249
3250
	public function ARinclude($file) {
3251
		include($file);
3252
	}
3253
3254 4
	public function _load($class) {
3255
		// only allow access to modules in the modules directory.
3256 4
		$class = preg_replace('/[^a-z0-9\._]/i','',$class);
3257 4
		include_once($this->store->get_config("code")."modules/".$class);
3258 4
	}
3259
3260
	public function _import($class) {
3261
		// deprecated
3262
		return $this->_load($class);
3263
	}
3264
3265 40
	public function html_to_text($text) {
3266 40
		$trans = array_flip(get_html_translation_table(HTML_ENTITIES));
3267 40
		$cb  = function($matches) use ($trans) {
3268
			return strtr($matches[1],$trans);
3269 40
		};
3270
		//strip nonbreaking space, strip script and style blocks, strip html tags, convert html entites, strip extra white space
3271 40
		$search_clean = array("%&nbsp;%i", "%<(script|style)[^>]*>.*?<\/(script|style)[^>]*>%si", "%<[\/]*[^<>]*>%Usi", "%\s+%");
3272 40
		$replace_clean = array(" ", " ", " ", " ");
3273
3274 40
		$text = preg_replace_callback(
3275 40
			"%(\&[a-zA-Z0-9\#]+;)%s",
3276 14
			$cb,
3277
			$text
3278 14
		);
3279 40
		$text = preg_replace($search_clean, $replace_clean, $text);
3280 40
		return $text;
3281
	}
3282
3283
	public function _html_to_text($text) {
3284
		return $this->html_to_text($text);
3285
	}
3286
3287
	public function _newobject($filename, $type) {
3288
		$newpath=$this->make_path($filename);
3289
		$newparent=$this->store->make_path($newpath, "..");
3290
		$data=new object;
3291
		$object=$this->store->newobject($newpath, $newparent, $type, $data);
3292
		$object->arIsNewObject=true;
3293
		return $object;
3294
	}
3295
3296
	public function _save($properties="", $vtype="") {
3297
		if (isset($properties) && is_array($properties)) {
3298
			// isn't this double work, the save function doesn this again
3299
			foreach ($properties as $prop_name => $prop) {
3300
				foreach ($prop as $prop_index => $prop_record) {
3301
					$record = array();
3302 View Code Duplication
					foreach ($prop_record as $prop_field => $prop_value) {
3303
						switch (gettype($prop_value)) {
3304
							case "integer":
3305
							case "boolean":
3306
							case "double":
3307
								$value = $prop_value;
3308
							break;
3309
							default:
3310
								$value = $prop_value;
3311
								if (substr($prop_value, 0, 1) === "'" && substr($prop_value, -1) === "'"
3312
										&& "'".AddSlashes(StripSlashes(substr($prop_value, 1, -1)))."'" == $prop_value) {
3313
									$value = stripSlashes(substr($prop_value,1,-1));
3314
									// todo add deprecated warning
3315
								}
3316
						}
3317
						$record[$prop_field] = $value;
3318
					}
3319
					$properties[$prop_name][$prop_index] = $record;
3320
				}
3321
			}
3322
		}
3323
3324
		if ($this->arIsNewObject && $this->CheckSilent('add', $this->type)) {
3325
			unset($this->data->config);
3326
			$result = $this->save($properties, $vtype);
0 ignored issues
show
Bug introduced by
It seems like $properties can also be of type array or null; however, ariadne_object::save() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
3327
		} else if (!$this->arIsNewObject && $this->CheckSilent('edit', $this->type)) {
3328
			$this->data->config = current($this->get('.', 'system.get.data.config.phtml'));
3329
			$result = $this->save($properties, $vtype);
0 ignored issues
show
Bug introduced by
It seems like $properties can also be of type array or null; however, ariadne_object::save() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
3330
		}
3331
		return $result;
0 ignored issues
show
Bug introduced by
The variable $result 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...
3332
	}
3333
3334
	public function _is_supported($feature) {
3335
		return $this->store->is_supported($feature);
3336
	}
3337
3338
	/*
3339
		since the preg_replace() function is able to execute normal php code
3340
		we have to intercept all preg_replace() calls and parse the
3341
		php code with the pinp parser.
3342
	*/
3343
3344
3345
	/*	this is a private function used by the _preg_replace wrapper */
3346
	// FIXME: remove this function when the minimal php version for ariadne is raised to php 7.0
0 ignored issues
show
Coding Style introduced by
Comment refers to a FIXME task "remove this function when the minimal php version for ariadne is raised to php 7.0"
Loading history...
3347
	protected function preg_replace_compile($pattern, $replacement) {
3348
	global $AR;
3349
		include_once($this->store->get_config("code")."modules/mod_pinp.phtml");
3350
		preg_match("/^\s*(.)/", $pattern, $regs);
3351
		$delim = $regs[1];
3352
		if (@eregi("\\${delim}[^$delim]*\\${delim}.*e.*".'$', $pattern)) {
3353
			$pinp = new pinp($AR->PINP_Functions, 'local->', '$AR_this->_');
3354
			return substr($pinp->compile("<pinp>$replacement</pinp>"), 5, -2);
3355
		} else {
3356
			return $replacement;
3357
		}
3358
	}
3359
3360
	public function _preg_replace($pattern, $replacement, $text, $limit = -1) {
3361
		if (version_compare(PHP_VERSION, '7.0.0', '<')) {
3362
			if (isset($pattern) && is_array($pattern)) {
3363
				$newrepl = array();
3364
				reset($replacement);
3365
				foreach ($pattern as $i_pattern) {
3366
					list(, $i_replacement) = each($replacement);
3367
					$newrepl[] = $this->preg_replace_compile($i_pattern, $i_replacement);
3368
				}
3369
			} else {
3370
				$newrepl = $this->preg_replace_compile($pattern, $replacement);
3371
			}
3372
		} else {
3373
			// php7 is safe, no more eval
3374
			$newrepl = $replacement;
3375
		}
3376
		return preg_replace($pattern, $newrepl, $text, $limit);
3377
	}
3378
3379
	/* ob_start accepts a callback but we don't want that
3380
	 * this wrapper removes the arguments from the ob_start call
3381
	 */
3382
	public function _ob_start() {
3383
		return ob_start();
3384
	}
3385
3386
	public function _loadConfig($path='') {
3387
		return clone $this->loadConfig($path);
3388
	}
3389
3390
	public function _loadUserConfig($path='') {
3391
		return $this->loadUserConfig($path);
3392
	}
3393
3394
	public function _loadLibrary($name, $path) {
3395 4
		return $this->loadLibrary($name, $path);
3396
	}
3397
3398
	public function _resetConfig($path='') {
3399
		return $this->resetConfig($path);
3400
	}
3401
3402
	public function _getLibraries($path = '') {
3403
		return $this->getLibraries($path);
3404
	}
3405
3406
3407
	public function _getSetting($setting) {
3408
	global $AR;
3409
3410
		switch ($setting) {
3411
			case 'www':
3412
			case 'dir:www':
3413
				return $AR->dir->www;
3414
			case 'images':
3415
			case 'dir:images':
3416
				return $AR->dir->images;
3417
			case 'ARSessionKeyCheck':
3418
				$result = null;
3419
				if (function_exists('ldGenerateSessionKeyCheck')) {
3420
					$result = ldGenerateSessionKeyCheck();
3421
				}
3422
				return $result;
3423
			break;
3424
			case 'nls:list':
3425
				return $AR->nls->list;
3426
			break;
3427
			case 'nls:default':
3428
				return $AR->nls->default;
3429
			break;
3430
			case 'svn':
3431
				return $AR->SVN->enabled;
3432
			break;
3433
		}
3434
	}
3435
3436
	public function __call($name,$arguments) {
3437
		if ( $name[0] == '_' ) {
3438
			$fname = substr($name, 1);
3439
			if ( isset($this->{$fname}) && $this->{$fname} instanceof \Closure ) {
3440
				\Closure::bind( $this->{$fname}, $this );
3441
				return call_user_func_array( $this->{$fname}, $arguments);
3442
			}
3443
		}
3444
		switch($name) {
3445
			case "implements":
3446
				return $this->AR_implements($arguments[0]);
3447
			break;
3448
			default:
3449
				trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $name), E_USER_ERROR);
3450
				return false;
3451
			break;
3452
		}
3453
	}
3454
3455
	static public function pinpErrorHandler($errno, $errstr, $errfile, $errline, $errcontext) {
0 ignored issues
show
Unused Code introduced by
The parameter $errfile 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...
Unused Code introduced by
The parameter $errcontext 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...
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
3456 5
		global $nocache;
3457 5
		if (($errno & error_reporting()) == 0) {
3458 5
			return true;
3459
		}
3460
3461
		$nocache = true;
3462
		$context = pobject::getContext();
3463
		if ($context["arLibraryPath"]) { //  != null) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
3464
			$msg = "Error on line $errline in ".$context['arCallTemplateType'].'::'.$context['arCallFunction'] ." in library ".$context["arLibraryPath"] ."\n".$errstr."\n";
3465
		} else {
3466
			$msg = "Error on line $errline in ".$context['arCallTemplateType'].'::'.$context['arCallFunction'] ." on object ".$context['arCurrentObject']->path."\n".$errstr."\n";
3467
		}
3468
		$display = ini_get('display_errors');
3469
3470
		if($display) {
3471
			echo $msg;
3472
		}
3473
		error_log($msg);
3474
3475
		return false;
3476
	}
3477
3478
} // end of ariadne_object class definition
3479