Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Common.php « modules - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f0075686858da147b30c6df6cb63e896fd4c7fae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
<?php
/**
 * Static class providing functions used by both the CORE of Piwik and the
 * visitor logging engine. 
 * 
 * This is the only external class loaded by the Piwik.php file.
 * This class should contain only the functions that are used in 
 * both the CORE and the piwik.php statistics logging engine.
 */
class Piwik_Common 
{
	/**
	 * Returns the variable after cleaning operations.
	 * NB: The variable still has to be escaped before going into a SQL Query!
	 * 
	 * If an array is passed the cleaning is done recursively on all the sub-arrays. \
	 * The keys of the array are filtered as well!
	 * 
	 * How this method works:
	 * - The variable returned has been htmlspecialchars to avoid the XSS security problem.
	 * - The single quotes are not protected so "Piwik's amazing" will still be "Piwik's amazing".
	 * 
	 * - Transformations are:
	 * 		- '&' (ampersand) becomes '&amp;'
	 *  	- '"'(double quote) becomes '&quot;' 
	 * 		- '<' (less than) becomes '&lt;'
	 * 		- '>' (greater than) becomes '&gt;'
	 * - It handles the magic_quotes setting.
	 * - A non string value is returned without modification
	 *
	 * @param mixed The variable to be cleaned
	 * @return mixed The variable after cleaning
	 */
	static public function sanitizeInputValues($value) 
	{
		if (is_array($value)) 
		{
			foreach (array_keys($value) as $key) 
			{
				$newKey = $key;
				$newKey = Piwik_Common::sanitizeInputValues($newKey);
				if ($key != $newKey) 
				{
				    $value[$newKey] = $value[$key];
				    unset($value[$key]);
				}
				
				$value[$newKey] = Piwik_Common::sanitizeInputValues($value[$newKey]);
			}
		}
		elseif(is_string($value))
		{
			$value = htmlspecialchars($value, ENT_COMPAT, 'UTF-8');

			/* Undo the damage caused by magic_quotes */
			if (get_magic_quotes_gpc()) 
			{
			    $value = stripslashes($value);
			}
		}
		elseif(!is_numeric($value)
			&& !is_null($value)
			&& !is_bool($value)
		)
		{
			throw new Exception("The value to escape has not a supported type. Value = ".var_export($value, true));
		}
		return $value;
    }

	/**
	 * Returns a variable from the $_REQUEST superglobal.
	 * If the variable doesn't have a value or an empty value, returns the defaultValue if specified.
	 * If the variable doesn't have neither a value nor a default value provided, an exception is raised.
	 * 
	 * @param string $varName name of the variable
	 * @param string $varDefault default value. If '', and if the type doesn't match, exit() !
	 * @param string $varType Expected type, the value must be one of the following: array, numeric, int, integer, string
	 * 
	 * @exception if the variable type is not known
	 * @exception if the variable we want to read doesn't have neither a value nor a default value specified
	 * 
	 * @return mixed The variable after cleaning
	 */
	static public function getRequestVar($varName, $varDefault = null, $varType = null)
	{
		$varDefault = self::sanitizeInputValues( $varDefault );
		
		if($varType == 'int')
		{
			// settype accepts only integer
			// 'int' is simply a shortcut for 'integer'
			$varType = 'integer';
		}
		
		// there is no value $varName in the REQUEST so we try to use the default value	
		if(empty($varName)
			|| !isset($_REQUEST[$varName]) 
			|| empty($_REQUEST[$varName]))
		{
			if( is_null($varDefault))
			{
				throw new Exception("\$varName '$varName' doesn't have value in \$_REQUEST and doesn't have a" .
						" \$varDefault value");
			}
			else
			{
				if( !is_null($varType) 
					&& in_array($varType, array('string', 'integer', 'array'))
				)
				{
					settype($varDefault, $varType);
				}
				return $varDefault;
			}
		}
		
		// Normal case, there is a value available in REQUEST for the requested varName
		$value = self::sanitizeInputValues( $_REQUEST[$varName] );
		
		if( !is_null($varType))
		{			
			$ok = false;
			
			if($varType == 'string')
			{
				if(is_string($value)) $ok = true;
			}			
			elseif($varType == 'numeric')
			{
					if(is_numeric($value) || $value==(int)$value || $value==(float)$value) $ok = true;
			}
			elseif($varType == 'integer')
			{
					if(is_int($value) || $value==(int)$value) $ok = true;
			}
			elseif($varType == 'array')
			{
					if(is_array($value)) $ok = true;
			}
			else
			{
				throw new Exception("\$varType specified is not known. It should be one of the following: array, numeric, int, integer, float, string");
			}
			
			// The type is not correct
			if($ok === false)
			{
				if($varDefault === null) 
				{	
					throw new Exception("\$varName '$varName' doesn't have a correct type in \$_REQUEST and doesn't " .
							"have a \$varDefault value");
				}
				// we return the default value with the good type set
				else
				{
					settype($varDefault, $varType);
					return $varDefault;
				}
			}
		}
				
		return $value;
	}
	
	
	static public function generateUniqId()
	{
		return md5(uniqid(rand(), true));
	}
	
	/**
	* get the visitor os
	* 
	* @param string $userAgent
	* @param array $osList
	* 
	* @return string 
	*/
	static public function getOs($userAgent)
	{
		$osNameToId = Array(
			'Nintendo Wii'	 => 'WII',
			'PlayStation Portable' => 'PSP',
			'PLAYSTATION 3'  => 'PS3',
			'Windows NT 6.0' => 'WVI',
			'Windows Vista'  => 'WVI',
			'Windows NT 5.2' => 'WS3',
			'Windows Server 2003' => 'WS3',
			'Windows NT 5.1' => 'WXP',
			'Windows XP'     => 'WXP',
			'Win98'          => 'W98',
			'Windows 98'     => 'W98',
			'Windows NT 5.0' => 'W2K',
			'Windows 2000'   => 'W2K',
			'Windows NT 4.0' => 'WNT',
			'WinNT'          => 'WNT',
			'Windows NT'     => 'WNT',
			'Win 9x 4.90'    => 'WME',
			'Win 9x 4.90'    => 'WME',
			'Windows Me'     => 'WME',
			'Win32'          => 'W95',
			'Win95'          => 'W95',		
			'Windows 95'     => 'W95',
			'Mac_PowerPC'    => 'MAC', 
			'Mac PPC'        => 'MAC',
			'PPC'            => 'MAC',
			'Mac PowerPC'    => 'MAC',
			'Mac OS'         => 'MAC',
			'Linux'          => 'LIN',
			'SunOS'          => 'SOS', 
			'FreeBSD'        => 'BSD', 
			'AIX'            => 'AIX', 
			'IRIX'           => 'IRI', 
			'HP-UX'          => 'HPX', 
			'OS/2'           => 'OS2', 
			'NetBSD'         => 'NBS',
			'Unknown'        => 'UNK' 
		);
		
		foreach($osNameToId as $key => $value)
		{
			if ($ok = ereg($key, $userAgent))
			{
				return $value;
			}
		}
		return 'UNK';
	}
		
	/**
	* get visitor browser 
	* 
	* @param string $userAgent
	* @return array array(  'name' 			=> '',
							'major_number' 	=> '',
							'minor_number' 	=> '',
							'version' 		=> '' // major_number.minor_number
						);
	*/
	static public function getBrowserInfo($userAgent)
	{
		$browsers = array(
				'msie'							=> 'IE',
				'microsoft internet explorer'	=> 'IE',
				'internet explorer'				=> 'IE',
				'netscape6'						=> 'NS',
				'netscape'						=> 'NS',
				'galeon'						=> 'GA',
				'phoenix'						=> 'PX',
				'firefox'						=> 'FF',
				'mozilla firebird'				=> 'FB',
				'firebird'						=> 'FB',
				'seamonkey'						=> 'SM',
				'chimera'						=> 'CH',
				'camino'						=> 'CA',
				'safari'						=> 'SF',
				'k-meleon'						=> 'KM',
				'mozilla'						=> 'MO',
				'opera'							=> 'OP',
				'konqueror'						=> 'KO',
				'icab'							=> 'IC',
				'lynx'							=> 'LX',
				'links'							=> 'LI',
				'ncsa mosaic'					=> 'MC',
				'amaya'							=> 'AM',
				'omniweb'						=> 'OW',
				'hotjava'						=> 'HJ',
				'browsex'						=> 'BX',
				'amigavoyager'					=> 'AV',
				'amiga-aweb'					=> 'AW',
				'ibrowse'						=> 'IB',
				'unknown'						=> 'unk'
		);
		
		$info = array(
			'name' 			=> 'UNK',
			'major_number' 	=> '',
			'minor_number' 	=> '',
			'version' 		=> ''
		);
		
		$browser = '';
		foreach($browsers as $key => $value) 
		{
			if(!empty($browser)) $browser .= "|";
			$browser .= $key;
		}
		
		$results = array();
		
		// added fix for Mozilla Suite detection
		if ((preg_match_all("/(mozilla)[\/\sa-z;.0-9-(]+rv:([0-9]+)([.0-9a-z]+)\) gecko\/[0-9]{8}$/i", $userAgent, $results)) 
		||	(preg_match_all("/($browser)[\/\sa-z(]*([0-9]+)([\.0-9a-z]+)?/i", $userAgent, $results))
			)
		 {
			$count = count($results[0])-1;
			
			// browser code
			$info['name'] = $browsers[strtolower($results[1][$count])];
			
			// majeur version number (7 in mozilla 1.7
			$info['major_number'] = $results[2][$count];
			
			// is an minor version number ? If not, 0
			$match = array();
			
			preg_match('/([.\0-9]+)?([\.a-z0-9]+)?/i', $results[3][$count], $match);
			
			if(isset($match[1])) 
			{
				// find minor version number (7 in mozilla 1.7, 9 in firefox 0.9.3)
				$info['minor_number'] = substr($match[1], 0, 2);
			} 
			else 
			{
				$info['minor_number'] = '.0';
			}
			
			$info['version'] = $info['major_number'] . $info['minor_number'];
		}	
		return $info;	
	}

	
	/**
	* Returns the best possible IP
	* 
	* @return string ip 
	*/
	static public function getIp() 
	{
		if(isset($_SERVER['HTTP_CLIENT_IP']) 
			&& ($ip = Piwik_Common::getFirstIpFromList($_SERVER['HTTP_CLIENT_IP']))
			&& strpos($ip, "unknown") === false)
		{
			return $ip;
		}
		elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) 
				&& $ip = Piwik_Common::getFirstIpFromList($_SERVER['HTTP_X_FORWARDED_FOR'])
				&& isset($ip) 
				&& !empty($ip)
				&& strpos($ip, "unknown")===false )
		{
			return $ip;
		}
		elseif( isset($_SERVER['HTTP_CLIENT_IP'])
				&& strlen( Piwik_Common::getFirstIpFromList($_SERVER['HTTP_CLIENT_IP']) ) != 0 )
		{
			return Piwik_Common::getFirstIpFromList($_SERVER['HTTP_CLIENT_IP']);
		}
		else if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) 
				&& strlen ($ip = Piwik_Common::getFirstIpFromList($_SERVER['HTTP_X_FORWARDED_FOR'])) != 0)
		{
			return $ip;
		}
		else
		{
			return Piwik_Common::getFirstIpFromList($_SERVER['REMOTE_ADDR']);
		}
	}
	
	
	/**
	* Returns the first element of a comma separated list of IPs
	* 
	* @param string $ip
	* 
	* @return string first element before ','
	*/
	static private function getFirstIpFromList($ip)
	{
		$p = strpos($ip, ',');
		if($p!==false)
		{
			return Piwik_Common::sanitizeInputValues(substr($ip, 0, $p));
		}
		return Piwik_Common::sanitizeInputValues($ip);
	}
	
		
	/**
	* Returns the continent of a given country
	* 
	* @param string Country 2 letters isocode
	* 
	* @return string Continent (3 letters code : afr, asi, eur, amn, ams, oce)
	*/
	function getContinent($country)
	{
		require_once PIWIK_INCLUDE_PATH . "/modules/DataFiles/Countries.php";
		
		$countryList = $GLOBALS['Piwik_CountryList'];
		
		if(isset($countryList[$country][0]))
		{
			return $countryList[$country][0];
		}
		else
		{
			return 'unk';
		}
	}
		
	/**
	* Returns the visitor country based only on the Browser Lang information
	* 
	* @param string $lang browser lang
	* 
	* @return string 
	*/
	function getCountry( $lang )
	{
		require_once PIWIK_INCLUDE_PATH . "/modules/DataFiles/Countries.php";
		
		$countryList = $GLOBALS['Piwik_CountryList'];
		
		$replaceLangCodeByCountryCode = array(
			// replace cs language (Serbia Montenegro country code) with czech country code
			'cs' => 'cz',
			// replace sv language (El Salvador country code) with sweden country code
			'sv' => 'se',
			// replace fa language (Unknown country code) with Iran country code
			'fa' => 'ir',
			// replace ja language (Unknown country code) with japan country code
			'ja' => 'jp',
			// replace ko language (Unknown country code) with corée country code
			'ko' => 'kr',
			// replace he language (Unknown country code) with Israel country code
			'he' => 'il',
			// replace da language (Unknown country code) with Danemark country code
			'da' => 'dk',
			// replace gb code with UK country code
			'gb' => 'uk',
			);
		
		
		if(empty($lang) || strlen($lang) < 2)
		{
			return 'xx';
		}
		
		$lang = str_replace(	array_keys($replaceLangCodeByCountryCode), 
								array_values($replaceLangCodeByCountryCode), 
								$lang
					);			

        // Ex: "fr"
		if(strlen($lang) == 2)
		{
			if(isset($countryList[$lang]))
			{
				return $lang;
			}
		}

		// when comma
		$offcomma = strpos($lang, ',');

		if($offcomma == 2)
		{
			// in 'fr,en-us', keep first two chars
			$domain = substr($lang, 0, 2);
			if(isset($countryList[$domain]))
			{
				return $domain;
			}

			// catch the second language Ex: "fr" in "en,fr"
			$domain = substr($lang, 3, 2);
			if(isset($countryList[$domain]))
			{
				return $domain;
			}
		}

		// detect second code Ex: "be" in "fr-be"
		$off = strpos($lang, '-');
		if($off!==false)
		{
			$domain = substr($lang, $off+1, 2);
			
			if(isset($countryList[$domain]))
			{
				return $domain;
			}
		}
		
		// catch the second language Ex: "fr" in "en;q=1.0,fr;q=0.9"
		if(preg_match("/^[a-z]{2};q=[01]\.[0-9],(?P<domain>[a-z]{2});/", $lang, $parts))
		{
			$domain = $parts['domain'];

			if(isset($GLOBALS['countryList'][$domain][0]))
			{
				return $domain;
			}
		}
		
		// finally try with the first ever langage code
		$domain = substr($lang, 0, 2);
		if(isset($countryList[$domain]))
		{
			return $domain;
		}
		
		// at this point we really can't guess the country
		return 'xx';
	}
		
	
}
?>