Issues (1752)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

class/cache/cache-memcached.php (12 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
require_once(dirname(__FILE__) . '/cache.php');
3
4
5
/**
6
 * Key - value cache system, data store in memcached.
7
 *
8
 * @deprecated  Use Fwlib\Cache\CacheMemcached
9
 * @package		fwolflib
10
 * @subpackage	class.cache
11
 * @copyright	Copyright 2012, Fwolf
12
 * @author		Fwolf <[email protected]>
13
 * @since		2012-11-13
14
 */
15
class CacheMemcached extends Cache {
0 ignored issues
show
There is at least one abstract method in this class. Maybe declare it as abstract, or implement the remaining methods: CacheGenVal, CacheLifetime
Loading history...
Deprecated Code introduced by
The class Cache has been deprecated with message: use Fwlib\Cache\Cache

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
16
17
	/**
18
	 * Memcache object
19
	 *
20
	 * @var	object
21
	 */
22
	public $oMemcached = NULL;
23
24
25
	/**
26
	 * Constructor
27
	 *
28
	 * @param	array	$ar_cfg
29
	 */
30
	public function __construct ($ar_cfg = array()) {
31
		parent::__construct($ar_cfg);
32
33
		// Unset for auto new
34
		unset($this->oMemcached);
35
	} // end of func __construct
36
37
38
	/**
39
	 * Delete cache data
40
	 * @param	string	$key
41
	 * @return	$this
42
	 */
43
	public function Del ($key) {
44
		if (1 == $this->aCfg['cache-memcached-autosplit']) {
45
			// Is value splitted ?
46
			$i_total = $this->oMemcached->get($this->Key($key
47
				. '[split]'));
48
			if (false === $i_total) {
49
				// No split found
50
				$this->oMemcached->delete($this->Key($key));
51
			} else {
52
				// Splitted string
53
				for ($i = 1; $i <= $i_total; $i++)
54
					$this->oMemcached->delete($this->Key($key
55
						. '[split-' . $i . '/' . $i_total . ']'));
56
				$this->oMemcached->delete($this->Key($key . '[split]'));
57
			}
58
		}
59
		else {
60
			$this->oMemcached->delete($this->Key($key));
61
		}
62
63
		return $this;
64
	} // end of func Del
65
66
67
	/**
68
	 * Is cache data expire ?
69
	 *
70
	 * Memcached expire when get fail.
71
	 * Usually use Get and check NULL is enough.
72
	 *
73
	 * @param	string	$key
74
	 * @param	int		$lifetime
75
	 * @return	boolean					True means it IS expired.
76
	 */
77
	public function Expire ($key, $lifetime = NULL) {
0 ignored issues
show
The parameter $lifetime 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...
78
		// Lifetime is handle by memcached
79
80
		$val = $this->oMemcached->get($this->Key($key));
0 ignored issues
show
$val 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...
81
		// Unknown item size, try twice
82
		if ((Memcached::RES_SUCCESS !=
83
			$this->oMemcached->getResultCode())
84
			&& (1 == $this->aCfg['cache-memcached-autosplit'])) {
85
			$val = $this->oMemcached->get($this->Key($key . '[split]'));
0 ignored issues
show
$val 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...
86
		}
87
88
		if (Memcached::RES_SUCCESS == $this->oMemcached->getResultCode())
89
			return false;
90
		else
91
			return true;
92
	} // end of func Expire
93
94
95
	/**
96
	 * Read cache and return value
97
	 *
98
	 * Lifetime setted when write cache.
99
	 * Return NULL when fail or expire.
100
	 *
101
	 * @param	string	$key
102
	 * @param	int		$lifetime
103
	 * @return	mixed
104
	 */
105
	public function Get ($key, $lifetime = NULL) {
0 ignored issues
show
The parameter $lifetime 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...
106
		// Lifetime is handle by memcached
107
108
		if (1 == $this->aCfg['cache-memcached-autosplit']) {
109
			// Is value splitted ?
110
			$s_key = $this->Key($key . '[split]');
111
			$i_total = $this->oMemcached->get($s_key);
112
			parent::$aLogGet[] = array(
113
				'key'	=> $s_key,
114
				'success'	=> Memcached::RES_SUCCESS
115
					== $this->oMemcached->getResultCode(),
116
			);
117
			if (false === $i_total) {
118
				// No split found
119
				$val = $this->oMemcached->get($this->Key($key));
120
				parent::$aLogGet[] = array(
121
					'key'	=> $this->Key($key),
122
					'success'	=> Memcached::RES_SUCCESS
123
						== $this->oMemcached->getResultCode(),
124
				);
125
			} else {
126
				// Splited string
127
				$val = '';
128
				for ($i = 1; $i <= $i_total; $i++) {
129
					$s_key = $this->Key($key
130
						. '[split-' . $i . '/' . $i_total . ']');
131
					$val .= $this->oMemcached->get($s_key);
132
					parent::$aLogGet[] = array(
133
						'key'	=> $s_key,
134
						'success'	=> Memcached::RES_SUCCESS
135
							== $this->oMemcached->getResultCode(),
136
					);
137
				}
138
				// Convert to string in JSON format
139
				$val = '"' . $val . '"';
140
			}
141
		}
142
		else {
143
			// Direct get
144
			$val = $this->oMemcached->get($this->Key($key));
145
			parent::$aLogGet[] = array(
146
				'key'	=> $this->Key($key),
147
				'success'	=> Memcached::RES_SUCCESS
148
					== $this->oMemcached->getResultCode(),
149
			);
150
		}
151
152
		if (Memcached::RES_SUCCESS == $this->oMemcached->getResultCode())
153
			return $this->ValDecode($val);
0 ignored issues
show
The method ValDecode() does not seem to exist on object<CacheMemcached>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
154
		else
155
			return NULL;
156
	} // end of func Get
157
158
159
	/**
160
	 * Gen cache key
161
	 *
162
	 * Memcached limit key length 250, and no control char or whitespace.
163
	 *
164
	 * @param	string	$str
165
	 * @return	string
166
	 */
167
	public function Key ($str) {
168
		// Eliminate white space
169
		$str = preg_replace('/\s/m', '', $str);
170
171
		// Key can't be empty
172
		if (empty($str))
173
			$str = 'empty-key';
174
175
		// Length limit
176
		$i = strlen($this->aCfg['cache-memcached-option-default']
177
			[Memcached::OPT_PREFIX_KEY]);
178
		if (isset($this->aCfg['cache-memcached-option']
179
			[Memcached::OPT_PREFIX_KEY]))
180
			$i = max($i, strlen($this->aCfg['cache-memcached-option']
181
				[Memcached::OPT_PREFIX_KEY]));
182
		if (250 < ($i + strlen($str))) {
183
			$s = hash('crc32b', $str);
184
			$str = substr($str, 0, 250 - $i - strlen($s)) . $s;
185
		}
186
187
		return $str;
188
	} // end of func Key
189
190
191
	/**
192
	 * New memcached object
193
	 *
194
	 * @return	object
195
	 */
196
	public function NewObjMemcached () {
197
		if (!empty($this->aCfg['cache-memcached-server'])) {
198
			// Check server and remove dead
199
			foreach ($this->aCfg['cache-memcached-server'] as $k => $svr) {
200
				$obj = new Memcached();
201
				$obj->addServers(array($svr));
202
				// Do set test
203
				$obj->set($this->Key('memcached server alive test'), true);
204
				if (0 != $obj->getResultCode()) {
205
					// Got error server
206
					$this->Log('Memcache server ' . implode($svr, ':')
207
						. ' test fail: ' . $obj->getResultCode()
208
						. ', msg: ' . $obj->getResultMessage()
209
						, 4);
210
					unset($this->aCfg['cache-memcached-server'][$k]);
211
				}
212
				unset($obj);
213
			}
214
		}
215
216
		$obj = new Memcached();
217
		$obj->addServers($this->aCfg['cache-memcached-server']);
218
219 View Code Duplication
		if (!empty($this->aCfg['cache-memcached-option-default'])) {
0 ignored issues
show
This code seems to be duplicated across 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...
220
			foreach ($this->aCfg['cache-memcached-option-default']
221
				as $k => $v)
222
				$obj->setOption($k, $v);
223
		}
224
225 View Code Duplication
		if (!empty($this->aCfg['cache-memcached-option'])) {
0 ignored issues
show
This code seems to be duplicated across 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...
226
			foreach ($this->aCfg['cache-memcached-option'] as $k => $v)
227
				$obj->setOption($k, $v);
228
		}
229
230
/*
231
		// Server error ?
232
		// getStats() return false when at least 1 server is dead.
233
		if (!empty($this->aCfg['cache-memcached-server'])
234
			&& false == $obj->getStats()) {
235
			$this->Log('One or more server is dead, code: '
236
				. $obj->getResultCode(). ', msg: '
237
				. $obj->getResultMessage()
238
				, 4);
239
		}
240
*/
241
242
		return $obj;
243
	} // end of func NewObjMemcached
244
245
246
	/**
247
	 * Write data to cache
248
	 *
249
	 * Lifetime setted when write cache.
250
	 *
251
	 * @param	string	$key
252
	 * @param	mixed	$val
253
	 * @param	int		$lifetime
254
	 * @return	$this
255
	 */
256
	public function Set ($key, $val, $lifetime = NULL) {
257
		// Convert expiration time
258
		$lifetime = $this->ExpireTime($lifetime);
0 ignored issues
show
The method ExpireTime() does not exist on CacheMemcached. Did you maybe mean Expire()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
259
260
		// Auto split large string val
261
		if ((1 == $this->aCfg['cache-memcached-autosplit'])
262
			&& is_string($val) && (strlen($val)
263
			> $this->aCfg['cache-memcached-maxitemsize'])) {
264
			$ar = str_split($val
265
				, $this->aCfg['cache-memcached-maxitemsize']);
266
			$i_total = count($ar);
267
268
			// Set split total
269
			$rs = $this->oMemcached->set($this->Key($key . '[split]')
270
				, $i_total, $lifetime);
271
272
			// Set split trunk
273
			for ($i = 1; $i <= $i_total; $i++) {
274
				$rs = $this->oMemcached->set($this->Key($key
275
					. '[split-' . $i . '/' . $i_total . ']')
276
					, $ar[$i - 1], $lifetime);
277
			}
278
		}
279
		else {
280
			// Normal set
281
			$rs = $this->oMemcached->set($this->Key($key)
282
				, $this->ValEncode($val), $lifetime);
0 ignored issues
show
The method ValEncode() does not seem to exist on object<CacheMemcached>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
283
		}
284
285
		if (false == $rs) {
286
			$this->Log('Memcache set error '
287
				. $this->oMemcached->getResultCode() . ': '
288
				. $this->oMemcached->getResultMessage()
289
				, 4);
290
		}
291
292
		return $this;
293
	} // end of func Set
294
295
296
	/**
297
	 * Set default config
298
	 *
299
	 * @return	this
300
	 */
301
	protected function SetCfgDefault () {
302
		parent::SetCfgDefault();
303
304
		// Cache type: memcached
305
		$this->aCfg['cache-type'] = 'memcached';
306
307
308
		// Memcached server
309
310
		$memcachedOptions = array(
311
			// Better for multi server
312
			Memcached::OPT_DISTRIBUTION	=>
313
				Memcached::DISTRIBUTION_CONSISTENT,
314
			// Better for multi app use one memcached
315
			Memcached::OPT_PREFIX_KEY	=> 'fw',
316
		);
317
		// Use json is better for debug
318
        if (Memcached::HAVE_JSON) {
319
            $memcachedOptions[Memcached::OPT_SERIALIZER] =
320
                Memcached::SERIALIZER_JSON;
321
        }
322
323
		// Default cache lifetime, 60s * 60m * 24h = 86400s(1d)
324
		$this->aCfg['cache-memcached-lifetime'] = 86400;
325
326
		// Auto split store item larger than max item size
327
		// 0/off, 1/on, when off, large item store will fail.
328
		$this->aCfg['cache-memcached-autosplit'] = 0;
329
330
		// Max item size, STRING val exceed this will auto split
331
		//   and store automatic, user need only care other val type.
332
		$this->aCfg['cache-memcached-maxitemsize'] = 1024000;
333
334
		// Memcached default option, set when new memcached obj
335
		$this->aCfg['cache-memcached-option-default'] = $memcachedOptions;
336
337
		// Memcached option, user set, replace default above
338
		$this->aCfg['cache-memcached-option'] = array(
339
		);
340
341
		// After change server cfg, you should unset $oMemcached.
342
		// or use SetCfgServer()
343
		$this->aCfg['cache-memcached-server'] = array();
344
345
346
		return $this;
347
	} // end of func SetCfgDefault
348
349
350
	/**
351
	 * Set cfg: memcached server
352
	 *
353
	 * @param	array	$ar_svr			1 or 2 dim array of server(s)
354
	 * @return	this
355
	 */
356
	public function SetCfgServer ($ar_svr = array()) {
357
		if (empty($ar_svr))
358
			return $this;
359
360
		if (isset($ar_svr[0]) && is_array($ar_svr[0])) {
361
			// 2 dim array
362
			$this->aCfg['cache-memcached-server'] = $ar_svr;
363
		}
364
		else {
365
			// 1 dim array only
366
			$this->aCfg['cache-memcached-server'] = array($ar_svr);
367
		}
368
369
		unset($this->oMemcached);
370
		return $this;
371
	} // end of func SetCfgServer
372
373
374
} // end of class CacheMemcached
375
?>
0 ignored issues
show
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
376