View difference between Paste ID: wgPjdcX1 and uyiP1wAE
SHOW: | | - or go back to the newest paste.
1
<?php
2
/**
3
*
4
* @package Kleeja
5
* @copyright (c) 2007 Kleeja.com
6
* @license ./docs/license.txt
7
*
8
*/
9
10
11
//no for directly open
12
if (!defined('IN_COMMON'))
13
{
14
	exit();
15
}
16
17
18
19
20
/**
21
 *  Detect a bot activity an record it
22
*/
23
function kleeja_detecting_bots()
24
{
25
	global $SQL, $usrcp, $dbprefix, $config, $klj_session;
26
27
	// get information ..
28
	$agent	= $SQL->escape($_SERVER['HTTP_USER_AGENT']);
29
	$time	= time();
30
31
	//for stats
32
	if (strpos($agent, 'Google') !== false)
33
	{
34
		$update_query = array(
35
								'UPDATE'	=> "{$dbprefix}stats",
36
								'SET'		=> "last_google=$time, google_num=google_num+1"
37
							);
38
        is_array($plugin_run_result = Plugins::getInstance()->run('qr_update_google_lst_num', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
39
		$SQL->build($update_query);
40
	}
41
	elseif (strpos($agent, 'Bing') !== false)
42
	{
43
		$update_query = array(
44
								'UPDATE'	=> "{$dbprefix}stats",
45
								'SET'		=> "last_bing=$time, bing_num=bing_num+1"
46
							);
47
        is_array($plugin_run_result = Plugins::getInstance()->run('qr_update_bing_lst_num', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
48
		$SQL->build($update_query);
49
	}
50
51
	//put another bots as a hook if you want !
52
    is_array($plugin_run_result = Plugins::getInstance()->run('anotherbots_onlline_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
53
54
	//clean online table
55
	if((time() - $config['last_online_time_update']) >= 3600)
56
	{
57
		#what to add here ?
58
		//update last_online_time_update
59
		update_config('last_online_time_update', time());
60
	}
61
62
    is_array($plugin_run_result = Plugins::getInstance()->run('KleejaOnline_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
63
}
64
65
66
/**
67
 * Ban system
68
*/
69
function get_ban()
70
{
71
	global $banss, $lang, $tpl, $text, $SQL;
72
73
	//visitor ip now
74
	$ip	= get_ip();
75
76
	//now .. loop for banned ips
77
	if (is_array($banss) && !empty($ip))
78
	{
79
		foreach ($banss as $ip2)
80
		{
81
			$ip2 = trim($ip2);
82
83
			if(empty($ip2))
84
			{
85
				continue;
86
			}
87
88
			//first .. replace all * with something good .
89
			$replace_it = str_replace("*", '([0-9]{1,3})', $ip2);
90
			$replace_it = str_replace(".", '\.', $replace_it);
91
92
			if ($ip == $ip2 || @preg_match('/' . preg_quote($replace_it, '/') . '/i', $ip))
93
			{
94
                is_array($plugin_run_result = Plugins::getInstance()->run('banned_get_ban_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
95
96
                //
97
                // if the request is an image
98
                //
99
                if(
100
                    ( defined('IN_DOWNLOAD') && (ig('img') || ig('thmb') || ig('thmbf') || ig('imgf')) )
101
                    || g('go', 'str', '') == 'queue'
102
                )
103
                {
104
105
                    @$SQL->close();
106
                    $fullname = "images/banned_user.jpg";
107
                    $filesize = filesize($fullname);
108
                    header("Content-length: $filesize");
109
                    header("Content-type: image/jpg");
110
                    readfile($fullname);
111
                    exit;
112
                }
113
                else
114
                {
115
                    kleeja_info($lang['U_R_BANNED'], $lang['U_R_BANNED'], true);
116
                }
117
			}
118
		}
119
	}
120
121
    is_array($plugin_run_result = Plugins::getInstance()->run('get_ban_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
122
}
123
124
125
/**
126
 * Check if the given plugin installed ?
127
 * @param $plugin_name
128
 * @return bool
129
 */
130
function kleeja_plugin_exists($plugin_name)
131
{
132
	global $SQL, $dbprefix;
133
134
    $query = array(
135
					'SELECT'	=> 'p.plg_id',
136
					'FROM'		=> "{$dbprefix}plugins p",
137
					'WHERE'		=> "p.plg_name = '" . $SQL->escape($plugin_name) . "'",
138
				);
139
140
		$result	= $SQL->build($query);
141
		$num = $SQL->num_rows($result);
142
		if($num)
143
		{
144
			$d = $SQL->fetch($result);
145
			$SQL->freeresult();
146
			return $d['plg_id'];
147
		}
148
149
		return false;
150
}
151
152
/**
153
* Return current page url
154
*/
155
function kleeja_get_page()
156
{
157
	if(isset($_SERVER['REQUEST_URI']))
158
	{
159
		$location = $_SERVER['REQUEST_URI'];
160
    } elseif (isset($_ENV['REQUEST_URI'])) {
161
        $location = $_ENV['REQUEST_URI'];
162
	}
163
	else
164
	{
165
		if(isset($_SERVER['PATH_INFO']))
166
		{
167
			$location = $_SERVER['PATH_INFO'];
168
		}
169
		elseif(isset($_ENV['PATH_INFO']))
170
		{
171
			$location = $_SERVER['PATH_INFO'];
172
		}
173
		elseif(isset($_ENV['PHP_SELF']))
174
		{
175
			$location = $_ENV['PHP_SELF'];
176
		}
177
		else
178
		{
179
			$location = $_SERVER['PHP_SELF'];
180
		}
181
		if(isset($_SERVER['QUERY_STRING']))
182
		{
183
			$location .= "?" . $_SERVER['QUERY_STRING'];
184
		}
185
		elseif(isset($_ENV['QUERY_STRING']))
186
		{
187
			$location = "?" . $_ENV['QUERY_STRING'];
188
		}
189
	}
190
191
	$return = str_replace(array('&amp;'), array('&'), htmlspecialchars($location));
192
	return $return;
193
}
194
195
/**
196
 * Fix email string to be UTF8
197
 * @param $text
198
 * @return string
199
 */
200
function _sm_mk_utf8($text)
201
{
202
	return "=?UTF-8?B?" . kleeja_base64_encode($text) . "?=";
203
}
204
205
/**
206
 * Send an email message
207
 * @param string $to
208
 * @param string $body
209
 * @param string $subject
210
 * @param string $fromAddress
211
 * @param string $fromName
212
 * @param string $bcc
213
 * @return bool
214
 */
215
function send_mail($to, $body, $subject, $fromAddress, $fromName, $bcc = '')
216
{
217
	$eol = "\r\n";
218
	$headers = '';
219
    $headers .= 'From: ' . _sm_mk_utf8(trim(preg_replace('#[\n\r:]+#s', '', $fromName))) . ' <' . trim(preg_replace('#[\n\r:]+#s', '', $fromAddress)) . '>' . $eol;
220
	$headers .= 'MIME-Version: 1.0' . $eol;
221
	$headers .= 'Content-transfer-encoding: 8bit' . $eol; // 7bit
222
	$headers .= 'Content-Type: text/plain; charset=utf-8' . $eol; // format=flowed
223
	$headers .= 'X-Mailer: Kleeja Mailer' . $eol;
224
    $headers .= 'Reply-To: ' . _sm_mk_utf8(trim(preg_replace('#[\n\r:]+#s', '', $fromName))) . ' <' . trim(preg_replace('#[\n\r:]+#s', '', $fromAddress)) . '>' . $eol;
225
    if (!empty($bcc)) {
226
        $headers .= 'Bcc: ' . trim(preg_replace('#[\n\r:]+#s', '', $bcc)) . $eol;
227
    }
228
229
    is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_send_mail', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
230
231
	$body = str_replace(array("\n", "\0"), array("\r\n", ''), $body);
232
233
    // Change the line breaks used in the headers according to OS
234
	if (strtoupper(substr(PHP_OS, 0, 3)) == 'MAC')
235
	{
236
		$headers = str_replace("\r\n", "\r", $headers);
237
	}
238
	else if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN')
239
	{
240
		$headers = str_replace("\r\n", "\n", $headers);
241
	}
242
243
	$mail_sent = @mail(trim(preg_replace('#[\n\r]+#s', '', $to)), _sm_mk_utf8(trim(preg_replace('#[\n\r]+#s', '', $subject))), $body, $headers);
244
245
	return $mail_sent;
246
}
247
248
249
/**
250
 * Get remote files
251
 * (c) punbb + Kleeja team
252
 * @param $url
253
 * @param bool $save_in
254
 * @param int $timeout
255
 * @param bool $head_only
256
 * @param int $max_redirects
257
 * @param bool $binary
258
 * @return bool|string|array
259
 */
260
function fetch_remote_file($url, $save_in = false, $timeout = 20, $head_only = false, $max_redirects = 10, $binary = false)
261
{
262
    is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_fetch_remote_file_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
263
264
	// Quite unlikely that this will be allowed on a shared host, but it can't hurt
265
	if (function_exists('ini_set'))
266
	{
267
		@ini_set('default_socket_timeout', $timeout);
268
	}
269
	$allow_url_fopen = function_exists('ini_get') ? strtolower(@ini_get('allow_url_fopen')) : strtolower(@get_cfg_var('allow_url_fopen'));
270
271
	if(function_exists('curl_init') && !$save_in)
272
	{
273
		$ch = curl_init();
274
		curl_setopt($ch, CURLOPT_URL, $url);
275
//		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
276
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
277
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
278
		curl_setopt($ch, CURLOPT_HEADER, true);
279
		curl_setopt($ch, CURLOPT_NOBODY, $head_only);
280
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
281
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; Kleeja)');
282
283
		// Grab the page
284
		$data = @curl_exec($ch);
285
        $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
286
		curl_close($ch);
287
288
		// Process 301/302 redirect
289
        if ($data !== false && ($response_code == '301' || $response_code == '302') && $max_redirects > 0)
290
		{
291
			$headers = explode("\r\n", trim($data));
292
			foreach ($headers as $header)
293
			{
294
				if (substr($header, 0, 10) == 'Location: ')
295
				{
296
                    $response = fetch_remote_file(substr($header, 10), $save_in, $timeout, $head_only, $max_redirects - 1);
297
					if ($head_only)
298
					{
299
                        if ($response != false)
300
						{
301
                            $headers[] = $response;
302
						}
303
						return $headers;
304
					}
305
					else
306
					{
307
						return false;
308
					}
309
				}
310
			}
311
		}
312
313
		// Ignore everything except a 200 response code
314
        if ($data !== false && $response_code == '200')
315
		{
316
			if ($head_only)
317
			{
318
				return explode("\r\n", str_replace("\r\n\r\n", "\r\n", trim($data)));
319
			}
320
			else
321
			{
322
				preg_match('#HTTP/1.[01] 200 OK#', $data, $match, PREG_OFFSET_CAPTURE);
323
				$last_content = substr($data, $match[0][1]);
324
				$content_start = strpos($last_content, "\r\n\r\n");
325
				if ($content_start !== false)
326
				{
327
					return substr($last_content, $content_start + 4);
328
				}
329
			}
330
		}
331
332
	}
333
	// fsockopen() is the second best thing
334
	else if(function_exists('fsockopen'))
335
	{
336
	    $url_parsed = parse_url($url);
337
	    $host = $url_parsed['host'];
338
	    $port = empty($url_parsed['port']) || $url_parsed['port'] == 0 ? 80 : $url_parsed['port'];
339
		$path = $url_parsed['path'];
340
341
		if (isset($url_parsed["query"]) && $url_parsed["query"] != '')
342
		{
343
			$path .= '?' . $url_parsed['query'];
344
		}
345
346
	    if(!$fp = @fsockopen($host, $port, $errno, $errstr, $timeout))
347
		{
348
			return false;
349
		}
350
351
		// Send a standard HTTP 1.0 request for the page
352
		fwrite($fp, ($head_only ? 'HEAD' : 'GET') . " $path HTTP/1.0\r\n");
353
		fwrite($fp, "Host: $host\r\n");
354
		fwrite($fp, 'User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; Kleeja)' . "\r\n");
355
		fwrite($fp, 'Connection: Close'."\r\n\r\n");
356
357
		stream_set_timeout($fp, $timeout);
358
		$stream_meta = stream_get_meta_data($fp);
359
360
        $fp2 = null;
361
362
		//let's open new file to save it in.
363
		if($save_in)
364
		{
365
			$fp2 = @fopen($save_in, 'w' . ($binary ? '' : ''));
366
		}
367
368
		// Fetch the response 1024 bytes at a time and watch out for a timeout
369
		$in = false;
370
		$h = false;
371
372
		while (!feof($fp) && !$stream_meta['timed_out'])
373
		{
374
			$s = fgets($fp, 1024);
375
			if($save_in)
376
			{
377
					if($s == "\r\n") //|| $s == "\n")
378
					{
379
						$h = true;
380
						continue;
381
					}
382
383
					if($h)
384
					{
385
						@fwrite($fp2, $s);
386
					}
387
			}
388
389
			$in .= $s;
390
			$stream_meta = stream_get_meta_data($fp);
391
		}
392
393
		fclose($fp);
394
395
		if($save_in)
396
		{
397
			unset($in);
398
			@fclose($fp2);
399
			return true;
400
		}
401
402
		// Process 301/302 redirect
403
		if ($in !== false && $max_redirects > 0 && preg_match('#^HTTP/1.[01] 30[12]#', $in))
404
		{
405
			$headers = explode("\r\n", trim($in));
406
			foreach ($headers as $header)
407
			{
408
				if (substr($header, 0, 10) == 'Location: ')
409
				{
410
                    $response = fetch_remote_file(substr($header, 10), $save_in, $timeout, $head_only, $max_redirects - 1);
411
                    if ($response != false)
412
					{
413
                        $headers[] = $response;
414
					}
415
					return $headers;
416
				}
417
			}
418
		}
419
420
		// Ignore everything except a 200 response code
421
		if ($in !== false && preg_match('#^HTTP/1.[01] 200 OK#', $in))
422
		{
423
			if ($head_only)
424
			{
425
				return explode("\r\n", trim($in));
426
			}
427
			else
428
			{
429
				$content_start = strpos($in, "\r\n\r\n");
430
				if ($content_start !== false)
431
				{
432
					return substr($in, $content_start + 4);
433
				}
434
			}
435
		}
436
		return $in;
437
	}
438
	// Last case scenario, we use file_get_contents provided allow_url_fopen is enabled (any non 200 response results in a failure)
439
	else if (in_array($allow_url_fopen, array('on', 'true', '1')))
440
	{
441
		// PHP5's version of file_get_contents() supports stream options
442
		if (version_compare(PHP_VERSION, '5.0.0', '>='))
443
		{
444
			// Setup a stream context
445
			$stream_context = stream_context_create(
446
				array(
447
					'http' => array(
448
						'method'		=> $head_only ? 'HEAD' : 'GET',
449
						'user_agent'	=> 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; Kleeja)',
450
						'max_redirects'	=> $max_redirects + 1,	// PHP >=5.1.0 only
451
						'timeout'		=> $timeout	// PHP >=5.2.1 only
452
					)
453
				)
454
			);
455
456
			$content = @file_get_contents($url, false, $stream_context);
457
		}
458
		else
459
		{
460
			$content = @file_get_contents($url);
461
		}
462
463
		// Did we get anything?
464
		if ($content !== false)
465
		{
466
			// Gotta love the fact that $http_response_header just appears in the global scope (*cough* hack! *cough*)
467
			if ($head_only)
468
			{
469
				return $http_response_header;
470
			}
471
472
			if($save_in)
473
			{
474
				$fp2 = fopen($save_in, 'w' . ($binary ? 'b' : ''));
475
				@fwrite($fp2, $content);
476
				@fclose($fp2);
477
				unset($content);
478
				return true;
479
			}
480
481
			return $content;
482
		}
483
	}
484
485
	return false;
486
}
487
488
489
/**
490
 * Delete cache
491
 * @param string $name
492
 * @param bool $all if true, all cache in cache folder will be deleted
493
 * @return bool
494
 */
495
function delete_cache($name, $all=false)
496
{
497
498
	#Those files are exceptions and not for deletion
499
	$exceptions = array('.htaccess', 'index.html', 'php.ini', 'web.config');
500
501
	#ignore kleeja_log in dev stage.
502
	if(defined('DEV_STAGE'))
503
	{
504
		array_push($exceptions, 'kleeja_log.log');
505
	}
506
507
	is_array($plugin_run_result = Plugins::getInstance()->run('delete_cache_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
508
509
	//handle array of cached files
510
	if(is_array($name))
511
	{
512
		foreach($name as $n)
513
		{
514
			delete_cache($n, false);
515
		}
516
		return true;
517
	}
518
519
	$path_to_cache = PATH . 'cache';
520
521
	if($all)
522
	{
523
        $del = true;
524
525
		if($dh = @opendir($path_to_cache))
526
		{
527
			while (($file = @readdir($dh)) !== false)
528
			{
529
				if($file != '.' && $file != '..' && !in_array($file, $exceptions))
530
				{
531
                    kleeja_unlink($path_to_cache . '/' . $file, true);
532
				}
533
			}
534
			@closedir($dh);
535
		}
536
	}
537
	else
538
	{
539
		if(strpos($name, 'tpl_') !== false && strpos($name, '.html') !== false)
540
		{
541
			$name = str_replace('.html', '', $name);
542
		}
543
544
		$del = true;
545
		$name = str_replace('.php', '', $name) . '.php';
546
		if (file_exists($path_to_cache . '/' . $name))
547
		{
548
			$del = kleeja_unlink ($path_to_cache . "/" . $name, true);
549
		}
550
	}
551
552
	return $del;
553
}
554
555
/**
556
 * Try delete files or at least change its name.
557
 * for those who have dirty hosting
558
 * @param string $filePath
559
 * @param bool $cache_file
560
 * @return bool
561
 */
562
function kleeja_unlink($filePath, $cache_file = false)
563
{
564
565
    $return = false;
566
567
    is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_unlink_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
568
569
570
    if($return)
571
    {
572
        return true;
573
    }
574
575
    //99.9% who use this
576
	if(function_exists('unlink'))
577
	{
578
        return unlink($filePath);
579
	}
580
	//5% only who use this
581
	//else if (function_exists('exec'))
582
	//{
583
	//	$out = array();
584
	//	$return = null;
585
	//	exec('del ' . escapeshellarg(realpath($filepath)) . ' /q', $out, $return);
586
	//	return $return;
587
	//}
588
	//5% only who use this
589
	//else if (function_exists('system'))
590
	//{
591
	//	$return = null;
592
	//	system ('del ' . escapeshellarg(realpath($filepath)) . ' /q', $return);
593
	//	return $return;
594
	//}
595
	//just rename cache file if there is new thing
596
	else if (function_exists('rename') && $cache_file)
597
	{
598
        $new_name = substr($filePath, 0, strrpos($filePath, '/') + 1) . 'old_' . md5($filePath . time()) . '.php';
599
        return rename($filePath, $new_name);
600
	}
601
602
	return false;
603
}
604
605
/**
606
 * Get mime header
607
 * @param string $ext file extension
608
 * @return string mime
609
 */
610
function get_mime_for_header($ext)
611
{
612
	$mime_types = array(
613
		"323" => "text/h323",
614
		"rar"=> "application/x-rar-compressed",
615
        "aac" => "audio/aac",
616
		"acx" => "application/internet-property-stream",
617
		"ai" => "application/postscript",
618
		"aif" => "audio/x-aiff",
619
		"aifc" => "audio/x-aiff",
620
		"aiff" => "audio/x-aiff",
621
		"asf" => "video/x-ms-asf",
622
		"asr" => "video/x-ms-asf",
623
		"asx" => "video/x-ms-asf",
624
		"au" => "audio/basic",
625
		"avi" => "video/x-msvideo",
626
		"axs" => "application/olescript",
627
		"bas" => "text/plain",
628
		"bcpio" => "application/x-bcpio",
629
		"bin" => "application/octet-stream",
630
		"bmp" => "image/bmp", # this is not a good mime, but it work anyway
631
		//"bmp"	=> "image/x-ms-bmp", # @see bugs.php.net/47359
632
		"c" => "text/plain",
633
		"cat" => "application/vnd.ms-pkiseccat",
634
		"cdf" => "application/x-cdf",
635
		"cer" => "application/x-x509-ca-cert",
636
		"class" => "application/octet-stream",
637
		"clp" => "application/x-msclip",
638
		"cmx" => "image/x-cmx",
639
		"cod" => "image/cis-cod",
640
		"psd" => "image/psd",
641
		"cpio" => "application/x-cpio",
642
		"crd" => "application/x-mscardfile",
643
		"crl" => "application/pkix-crl",
644
		"crt" => "application/x-x509-ca-cert",
645
		"csh" => "application/x-csh",
646
        "webm" => "video/webm",
647
		"css" => "text/css",
648
		"dcr" => "application/x-director",
649
		"der" => "application/x-x509-ca-cert",
650
		"dir" => "application/x-director",
651
		"dll" => "application/x-msdownload",
652
		"dms" => "application/octet-stream",
653
		"doc" => "application/msword",
654
		"dot" => "application/msword",
655
		"dvi" => "application/x-dvi",
656
		"dxr" => "application/x-director",
657
		"eps" => "application/postscript",
658
		"etx" => "text/x-setext",
659
		"evy" => "application/envoy",
660
		"exe" => "application/octet-stream",
661
		"fif" => "application/fractals",
662
		"flr" => "x-world/x-vrml",
663
		"gif" => "image/gif",
664
		"gtar" => "application/x-gtar",
665
		"gz" => "application/x-gzip",
666
		"h" => "text/plain",
667
		"hdf" => "application/x-hdf",
668
		"hlp" => "application/winhlp",
669
		"hqx" => "application/mac-binhex40",
670
		"hta" => "application/hta",
671
		"htc" => "text/x-component",
672
		"htm" => "text/html",
673
		"html" => "text/html",
674
		"htt" => "text/webviewhtml",
675
		"ico" => "image/x-icon",
676
		"ief" => "image/ief",
677
		"iii" => "application/x-iphone",
678
		"ins" => "application/x-internet-signup",
679
		"isp" => "application/x-internet-signup",
680
		"jfif" => "image/pipeg",
681
		"jpe" => "image/jpeg",
682
		"jpeg" => "image/jpeg",
683
		"jpg" => "image/jpeg",
684
		"png" => "image/png",
685
		"js" => "application/x-javascript",
686
		"latex" => "application/x-latex",
687
		"lha" => "application/octet-stream",
688
		"lsf" => "video/x-la-asf",
689
		"lsx" => "video/x-la-asf",
690
		"lzh" => "application/octet-stream",
691
		"m13" => "application/x-msmediaview",
692
		"m14" => "application/x-msmediaview",
693
		"m3u" => "audio/x-mpegurl",
694
		"man" => "application/x-troff-man",
695
		"mdb" => "application/x-msaccess",
696
		"me" => "application/x-troff-me",
697
		"mht" => "message/rfc822",
698
		"mhtml" => "message/rfc822",
699
		"mid" => "audio/mid",
700
		"mny" => "application/x-msmoney",
701
		"mov" => "video/quicktime",
702
		"movie" => "video/x-sgi-movie",
703
		"mp2" => "video/mpeg",
704
		"mp3" => "audio/mpeg",
705
		"mp4" => "video/mp4",
706
		"m4a" => "audio/mp4",
707
		"mpa" => "video/mpeg",
708
		"mpe" => "video/mpeg",
709
		"mpeg" => "video/mpeg",
710
		"mpg" => "video/mpeg",
711
		"amr" => "audio/3gpp",
712
		"mpp" => "application/vnd.ms-project",
713
		"mpv2" => "video/mpeg",
714
		"ms" => "application/x-troff-ms",
715
		"mvb" => "application/x-msmediaview",
716
		"nws" => "message/rfc822",
717
		"oda" => "application/oda",
718
		"p10" => "application/pkcs10",
719
		"p12" => "application/x-pkcs12",
720
		"p7b" => "application/x-pkcs7-certificates",
721
		"p7c" => "application/x-pkcs7-mime",
722
		"p7m" => "application/x-pkcs7-mime",
723
		"p7r" => "application/x-pkcs7-certreqresp",
724
		"p7s" => "application/x-pkcs7-signature",
725
		"pbm" => "image/x-portable-bitmap",
726
		"pdf" => "application/pdf",
727
		"pfx" => "application/x-pkcs12",
728
		"pgm" => "image/x-portable-graymap",
729
		"pko" => "application/ynd.ms-pkipko",
730
		"pma" => "application/x-perfmon",
731
		"pmc" => "application/x-perfmon",
732
		"pml" => "application/x-perfmon",
733
		"pmr" => "application/x-perfmon",
734
		"pmw" => "application/x-perfmon",
735
		"pnm" => "image/x-portable-anymap",
736
		"pot" => "application/vnd.ms-powerpoint",
737
		"ppm" => "image/x-portable-pixmap",
738
		"pps" => "application/vnd.ms-powerpoint",
739
		"ppt" => "application/vnd.ms-powerpoint",
740
		"prf" => "application/pics-rules",
741
		"ps" => "application/postscript",
742
		"pub" => "application/x-mspublisher",
743
		"qt" => "video/quicktime",
744
		"ra" => "audio/x-pn-realaudio",
745
		"ram" => "audio/x-pn-realaudio",
746
		"ras" => "image/x-cmu-raster",
747
		"rgb" => "image/x-rgb",
748
		"rmi" => "audio/mid",
749
		"roff" => "application/x-troff",
750
		"rtf" => "application/rtf",
751
		"rtx" => "text/richtext",
752
		"swf" => "application/x-shockwave-flash",
753
		"scd" => "application/x-msschedule",
754
		"sct" => "text/scriptlet",
755
		"setpay" => "application/set-payment-initiation",
756
		"setreg" => "application/set-registration-initiation",
757
		"sh" => "application/x-sh",
758
		"shar" => "application/x-shar",
759
		"sit" => "application/x-stuffit",
760
		"snd" => "audio/basic",
761
		"spc" => "application/x-pkcs7-certificates",
762
		"spl" => "application/futuresplash",
763
		"src" => "application/x-wais-source",
764
		"sst" => "application/vnd.ms-pkicertstore",
765
		"stl" => "application/vnd.ms-pkistl",
766
		"stm" => "text/html",
767
		"svg" => "image/svg+xml",
768
		"sv4cpio" => "application/x-sv4cpio",
769
		"sv4crc" => "application/x-sv4crc",
770
		"t" => "application/x-troff",
771
		"tar" => "application/x-tar",
772
		"tcl" => "application/x-tcl",
773
		"tex" => "application/x-tex",
774
		"texi" => "application/x-texinfo",
775
		"texinfo" => "application/x-texinfo",
776
		"tgz" => "application/x-compressed",
777
		"tif" => "image/tiff",
778
		"tiff" => "image/tiff",
779
		"tr" => "application/x-troff",
780
		"trm" => "application/x-msterminal",
781
		"tsv" => "text/tab-separated-values",
782
		"txt" => "text/plain",
783
		"uls" => "text/iuls",
784
		"ustar" => "application/x-ustar",
785
		"vcf" => "text/x-vcard",
786
		"vrml" => "x-world/x-vrml",
787
		"wav" => "audio/x-wav",
788
		"wcm" => "application/vnd.ms-works",
789
		"wdb" => "application/vnd.ms-works",
790
        "webm" => "video/mp4",
791
		"wks" => "application/vnd.ms-works",
792
		"wmf" => "application/x-msmetafile",
793
		"wps" => "application/vnd.ms-works",
794
		"wri" => "application/x-mswrite",
795
		"wrl" => "x-world/x-vrml",
796
		"wrz" => "x-world/x-vrml",
797
        "aac" => "aac/audio",
798
		"xaf" => "x-world/x-vrml",
799
		"xbm" => "image/x-xbitmap",
800
		"xla" => "application/vnd.ms-excel",
801
		"xlc" => "application/vnd.ms-excel",
802
		"xlm" => "application/vnd.ms-excel",
803
		"xls" => "application/vnd.ms-excel",
804
		"xlt" => "application/vnd.ms-excel",
805
		"xlw" => "application/vnd.ms-excel",
806
		"xof" => "x-world/x-vrml",
807
		"xpm" => "image/x-xpixmap",
808
		"xwd" => "image/x-xwindowdump",
809
		"z" => "application/x-compress",
810
		"zip" => "application/zip",
811
		"3gpp"=> "video/3gpp",
812
		"3gp" => "video/3gpp",
813
		"3gpp2" => "video/3gpp2",
814
		"3g2" => "video/3gpp2",
815
		"midi" => "audio/midi",
816
		"pmd" => "application/x-pmd",
817
		"jar" => "application/java-archive",
818
		"jad" => "text/vnd.sun.j2me.app-descriptor",
819
		'apk' => 'application/vnd.android.package-archive',
820
		//add more mime here
821
	);
822
823
	//return mime
824
	$ext = strtolower($ext);
825
    if(in_array($ext, array_keys($mime_types)))
826
    {
827
		$return = $mime_types[$ext];
828
	}
829
	else
830
	{
831
    	$return = 'application/force-download';
832
	}
833
834
    is_array($plugin_run_result = Plugins::getInstance()->run('get_mime_for_header_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
835
	return $return;
836
}
837
838
839
/**
840
 * Include language file
841
 * @param string $name language filename, 'acp, common..'
842
 * @param string $folder
843
 * @return bool
844
 */
845
function get_lang($name, $folder = '')
846
{
847
	global $config, $lang;
848
849
	if(is_null($lang) || !is_array($lang))
850
    {
851
        $lang = array();
852
    }
853
854
    is_array($plugin_run_result = Plugins::getInstance()->run('get_lang_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
855
856
	$name = str_replace('..', '', $name);
857
	if($folder != '')
858
	{
859
        $folder = str_replace(array('..', '/'), '', $folder);
860
		$name = $folder . '/' . $name;
861
	}
862
863
	$path = PATH . 'lang/' . $config['language'] . '/' . str_replace('.php', '', $name) . '.php';
864
865
    $lang_to_add = @include_once($path);
866
867
	if($lang_to_add === false)
868
	{
869
        //fallback to English
870
        $path_en = PATH . 'lang/en/' . str_replace('.php', '', $name) . '.php';
871
        $lang_to_add = @include_once($path_en);
872
        if ($lang_to_add === false) {
873
			big_error('There is no language file in the current path', 'lang/' . $config['language'] . '/' . str_replace('.php', '', $name) . '.php  not found');
874
        }
875
	}
876
877
	if(is_array($lang_to_add))
878
	{
879
        $lang = array_merge($lang, $lang_to_add);
880
    }
881
882
883
	return true;
884
}
885
886
887
/*
888
* Get fresh config value
889
* some time cache doesn't not work as well, so some important
890
* events need fresh version of config values ...
891
*/
892
function get_config($name)
893
{
894
	global $dbprefix, $SQL, $d_groups, $userinfo;
895
896
	$table = "{$dbprefix}config c";
897
898
	#what if this config is a group-configs related ?
899
	$group_id_sql = '';
900
	if(array_key_exists($name, $d_groups[$userinfo['group_id']]['configs']))
901
	{
902
		$table = "{$dbprefix}groups_data c";
903
		$group_id_sql = " AND c.group_id=" . $userinfo['group_id'];
904
	}
905
906
	$query = array(
907
					'SELECT'	=> 'c.value',
908
					'FROM'		=> $table,
909
					'WHERE'		=> "c.name = '" . $SQL->escape($name) . "'" . $group_id_sql
910
				);
911
912
	$result	= $SQL->build($query);
913
	$v		= $SQL->fetch($result);
914
	$return	= $v['value'];
915
916
    is_array($plugin_run_result = Plugins::getInstance()->run('get_config_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
917
	return $return;
918
}
919
920
/*
921
* Add new config option
922
* type: where does your config belone, 0 = system, genetal = has no specifc cat., other = other items.
923
* html: the input or radio to let the user type or choose from them, see the database:configs to understand.
924
* dynamic: every refresh of the page, the config data will be brought from db, not from the cache !
925
* plg_id: if this config belong to plugin .. see devKit.
926
*/
927
function add_config($name, $value, $order = '0', $html = '', $type = '0', $plg_id = '0', $dynamic = false)
928
{
929
	global $dbprefix, $SQL, $config, $d_groups;
930
931
	if(get_config($name))
932
	{
933
		return true;
934
	}
935
936
	if($html != '' && $type == '0')
937
	{
938
		$type = 'other';
939
	}
940
941
	if($type == 'groups')
942
	{
943
		#add this option to all groups
944
		$group_ids = array_keys($d_groups);
945
		foreach($group_ids as $g_id)
946
		{
947
			$insert_query	= array(
948
									'INSERT'	=> '`name`, `value`, `group_id`',
949
									'INTO'		=> "{$dbprefix}groups_data",
950
                'VALUES' => "'" . $SQL->escape($name) . "','" . $SQL->escape($value) . "', " . $g_id,
951
								);
952
953
            is_array($plugin_run_result = Plugins::getInstance()->run('insert_sql_add_config_func_groups_data', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
954
955
			$SQL->build($insert_query);
956
		}
957
	}
958
959
	$insert_query	= array(
960
							'INSERT'	=> '`name` ,`value` ,`option` ,`display_order`, `type`, `plg_id`, `dynamic`',
961
							'INTO'		=> "{$dbprefix}config",
962
							'VALUES'	=> "'" . $SQL->escape($name) . "','" . $SQL->escape($value) . "', '" . $SQL->real_escape($html) . "','" . intval($order) . "','" . $SQL->escape($type) . "','" . intval($plg_id) . "','"  . ($dynamic ? '1' : '0') . "'",
963
						);
964
965
    is_array($plugin_run_result = Plugins::getInstance()->run('insert_sql_add_config_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
966
967
	$SQL->build($insert_query);
968
969
	if($SQL->affected())
970
	{
971
		delete_cache('data_config');
972
		$config[$name] = $value;
973
		return true;
974
	}
975
976
	return false;
977
}
978
979
/**
980
 * add an array of new configs
981
 * @param $configs
982
 * @return bool
983
 */
984
function add_config_r($configs)
985
{
986
	if(!is_array($configs))
987
	{
988
		return false;
989
	}
990
991
	//array(name=>array(value=>,order=>,html=>),...);
992
	foreach($configs as $n=>$m)
993
	{
994
        add_config(
995
            $n,
996
            empty($m['value']) ? '' : $m['value'],
997
            empty($m['order']) ? 0 : $m['order'],
998
            empty($m['html']) ? '' : $m['html'],
999
            empty($m['type']) ? 'other' : $m['type'],
1000
            empty($m['plg_id']) ? 0 : $m['plg_id'],
1001
            empty($m['dynamic']) ? false : $m['dynamic']
1002
        );
1003
    }
1004
1005
    return true;
1006
}
1007
1008
function update_config($name, $value, $escape = true, $group = false)
1009
{
1010
	global $SQL, $dbprefix, $d_groups, $userinfo;
1011
1012
	$value = ($escape) ? $SQL->escape($value) : $value;
1013
	$table = "{$dbprefix}config";
1014
1015
	#what if this config is a group-configs related ?
1016
	$group_id_sql = '';
1017
    if (array_key_exists($name, $d_groups[$userinfo['group_id']]['configs']) && $group != false)
1018
	{
1019
		$table = "{$dbprefix}groups_data";
1020
		if($group == -1)
1021
		{
1022
			$group_id_sql = ' AND group_id=' . $userinfo['group_id'];
1023
		}
1024
		else if($group)
1025
		{
1026
			$group_id_sql = ' AND group_id=' . intval($group);
1027
		}
1028
	}
1029
1030
	$update_query	= array(
1031
							'UPDATE'	=> $table,
1032
							'SET'		=> "value='" . ($escape ? $SQL->escape($value) : $value) . "'",
1033
							'WHERE'		=> 'name = "' . $SQL->escape($name) . '"' . $group_id_sql
1034
					);
1035
1036
    is_array($plugin_run_result = Plugins::getInstance()->run('update_sql_update_config_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1037
1038
	$SQL->build($update_query);
1039
	if($SQL->affected())
1040
	{
1041
		if($table == "{$dbprefix}groups_data")
1042
		{
1043
			$d_groups[$userinfo['group_id']]['configs'][$name] = $value;
1044
			delete_cache('data_groups');
1045
			return true;
1046
		}
1047
1048
		$config[$name] = $value;
1049
		delete_cache('data_config');
1050
		return true;
1051
	}
1052
1053
	return false;
1054
}
1055
1056
/*
1057
* Delete config
1058
*/
1059
function delete_config($name)
1060
{
1061
	if(is_array($name))
1062
	{
1063
		foreach($name as $n)
1064
		{
1065
			delete_config($n);
1066
		}
1067
1068
	}
1069
1070
	global $dbprefix, $SQL, $d_groups, $userinfo;
1071
1072
	//
1073
	// 'IN' doesnt work here with delete, i dont know why ?
1074
	//
1075
	$delete_query	= array(
1076
								'DELETE'	=> "{$dbprefix}config",
1077
								'WHERE'		=>  "name  = '" . $SQL->escape($name) . "'"
1078
						);
1079
    is_array($plugin_run_result = Plugins::getInstance()->run('del_sql_delete_config_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1080
1081
	$SQL->build($delete_query);
1082
1083
	if(array_key_exists($name, $d_groups[$userinfo['group_id']]['configs']))
1084
	{
1085
		$delete_query	= array(
1086
									'DELETE'	=> "{$dbprefix}groups_data",
1087
									'WHERE'		=>  "name  = '" . $SQL->escape($name) . "'"
1088
							);
1089
        is_array($plugin_run_result = Plugins::getInstance()->run('del_sql_delete_config_func2', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1090
1091
		$SQL->build($delete_query);
1092
	}
1093
1094
	if($SQL->affected())
1095
	{
1096
		return true;
1097
	}
1098
1099
	return false;
1100
}
1101
1102
//
1103
//update words to lang
1104
//
1105
function update_olang($name, $lang = 'en', $value)
1106
{
1107
	global $SQL, $dbprefix;
1108
1109
1110
	$update_query	= array(
1111
							'UPDATE'	=> "{$dbprefix}lang",
1112
							'SET'		=> "trans='" . $SQL->escape($value) . "'",
1113
							'WHERE'		=> 'word = "' . $SQL->escape($name) . '", lang_id = "' .  $SQL->escape($lang) . '"'
1114
					);
1115
    is_array($plugin_run_result = Plugins::getInstance()->run('update_sql_update_olang_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1116
1117
	$SQL->build($update_query);
1118
	if($SQL->affected())
1119
	{
1120
        delete_cache('data_lang' . $lang);
1121
        $olang[$name] = htmlspecialchars($value);
1122
		return true;
1123
	}
1124
1125
	return false;
1126
}
1127
1128
//
1129
//add words to lang
1130
//
1131
function add_olang($words = array(), $lang = 'en', $plg_id = '0')
1132
{
1133
	global $dbprefix, $SQL;
1134
1135
	foreach($words as $w=>$t)
1136
	{
1137
		$insert_query = array(
1138
								'INSERT'	=> 'word ,trans ,lang_id, plg_id',
1139
								'INTO'		=> "{$dbprefix}lang",
1140
								'VALUES'	=> "'" . $SQL->escape($w) . "','" . $SQL->real_escape($t) . "', '" . $SQL->escape($lang) . "','" . intval($plg_id) . "'",
1141
						);
1142
        is_array($plugin_run_result = Plugins::getInstance()->run('insert_sql_add_olang_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1143
		$SQL->build($insert_query);
1144
	}
1145
1146
    delete_cache('data_lang' . $lang);
1147
	return;
1148
}
1149
1150
//
1151
//delete words from lang
1152
//
1153
/**
1154
 * @param string|array $words language terms to use a in $olang[word] or olang.word
1155
 * @param string $lang langauge of given word
1156
 * @param string $plg_id plugin id associated with these words, optional
1157
 * @return bool
1158
 */
1159
function delete_olang($words = '', $lang = 'en', $plg_id = 0)
1160
{
1161
	global $dbprefix, $SQL;
1162
1163
	if(is_array($words))
1164
	{
1165
		foreach($words as $w)
1166
		{
1167
            delete_olang($w, $lang);
1168
		}
1169
1170
        return true;
1171
	}
1172
1173
	$delete_query	= array(
1174
							'DELETE'	=> "{$dbprefix}lang",
1175
							'WHERE'		=> "word = '" . $SQL->escape($words) . "' AND lang_id = '" . $SQL->escape($lang) . "'"
1176
						);
1177
1178
	if(!empty($plg_id))
1179
	{
1180
		$delete_query['WHERE'] = "plg_id = " . intval($plg_id);
1181
	}
1182
1183
    is_array($plugin_run_result = Plugins::getInstance()->run('del_sql_delete_olang_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1184
1185
	$SQL->build($delete_query);
1186
1187
    return $SQL->affected();
1188
}
1189
1190
1191
/**
1192
 *  Administrator sometime needs some files and delete other ..
1193
 *  we do that for him .. because he has no time .. :)
1194
 * last_down - $config[del_f_day]
1195
 * @param int $from
1196
 */
1197
function klj_clean_old_files($from = 0)
1198
{
1199
	global $config, $SQL, $stat_last_f_del, $dbprefix;
1200
1201
	$return = false;
1202
    is_array($plugin_run_result = Plugins::getInstance()->run('klj_clean_old_files_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1203
1204
	if((int) $config['del_f_day'] <= 0 || $return)
1205
	{
1206
		return;
1207
	}
1208
1209
	if(!$stat_last_f_del || empty($stat_last_f_del))
1210
	{
1211
		$stat_last_f_del = time();
1212
	}
1213
1214
	if ((time() - $stat_last_f_del) >= 86400)
1215
	{
1216
		$totaldays	= (time() - ($config['del_f_day']*86400));
1217
		$not_today	= time() - 86400;
1218
1219
		#This feature will work only if id_form is not empty or direct !
1220
		$query = array(
1221
					'SELECT'	=> 'f.id, f.last_down, f.name, f.type, f.folder, f.time, f.size, f.id_form',
1222
					'FROM'		=> "{$dbprefix}files f",
1223
					'WHERE'		=> "f.last_down < $totaldays AND f.time < $not_today AND f.id > $from AND f.id_form <> '' AND f.id_form <> 'direct'",
1224
					'ORDER BY'	=> 'f.id ASC',
1225
					'LIMIT'		=> '20',
1226
					);
1227
1228
        is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_klj_clean_old_files_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1229
1230
		$result	= $SQL->build($query);
1231
1232
		$num_of_files_to_delete = $SQL->num_rows($result);
1233
		if($num_of_files_to_delete == 0)
1234
		{
1235
		   	 //update $stat_last_f_del !!
1236
			$update_query = array(
1237
								'UPDATE'	=> "{$dbprefix}stats",
1238
								'SET'		=> "last_f_del ='" . time() . "'",
1239
							);
1240
1241
            is_array($plugin_run_result = Plugins::getInstance()->run('qr_update_lstf_del_date_kcof', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1242
1243
			$SQL->build($update_query);
1244
			//delete stats cache
1245
			delete_cache("data_stats");
1246
			update_config('klj_clean_files_from', '0');
1247
			$SQL->freeresult($result);
1248
			return;
1249
		}
1250
1251
		$last_id_from = $files_num = $imgs_num = $real_num = $sizes = 0;
1252
		$ids = array();
1253
		$ex_ids =  array();
1254
		//$ex_types = explode(',', $config['livexts']);
1255
1256
1257
        is_array($plugin_run_result = Plugins::getInstance()->run('beforewhile_klj_clean_old_files_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1258
1259
1260
        //phpfalcon plugin
1261
        $exlive_types = explode(',', $config['imagefolderexts']);
1262
1263
		//delete files
1264
		while($row=$SQL->fetch_array($result))
1265
		{
1266
			$continue = true;
1267
			$real_num++;
1268
			$last_id_from = $row['id'];
1269
			$is_image = in_array(strtolower(trim($row['type'])), array('gif', 'jpg', 'jpeg', 'bmp', 'png')) ? true : false;
1270
1271
			/*
1272
			//exceptions
1273
			if(in_array($row['type'], $ex_types) || $config['id_form'] == 'direct')
1274
			{
1275
				$ex_ids[] = $row['id'];
1276
				continue;
1277
			}
1278
			*/
1279
1280
            //exceptions
1281
			//if($config['id_form'] == 'direct')
1282
			//{
1283
				//$ex_ids[] = $row['id'];
1284
				//move on
1285
				//continue;
1286
			//}
1287
1288
			//your exepctions
1289
            is_array($plugin_run_result = Plugins::getInstance()->run('while_klj_clean_old_files_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1290
1291
1292
1293
			if($continue)
1294
			{
1295
				//delete from folder ..
1296
				if (file_exists($row['folder'] . "/" . $row['name']))
1297
				{
1298
					@kleeja_unlink ($row['folder'] . "/" . $row['name']);
1299
				}
1300
				//delete thumb
1301
				if (file_exists($row['folder'] . "/thumbs/" . $row['name'] ))
1302
				{
1303
					@kleeja_unlink ($row['folder'] . "/thumbs/" . $row['name'] );
1304
				}
1305
1306
				$ids[] = $row['id'];
1307
				if($is_image)
1308
				{
1309
					$imgs_num++;
1310
				}
1311
				else
1312
				{
1313
					$files_num++;
1314
				}
1315
				$sizes += $row['size'];
1316
			}
1317
	    }#END WHILE
1318
1319
		$SQL->freeresult($result);
1320
1321
		if(sizeof($ex_ids))
1322
		{
1323
			$update_query	= array(
1324
									'UPDATE'	=> "{$dbprefix}files",
1325
									'SET'		=> "last_down = '" . (time() + 2*86400) . "'",
1326
									'WHERE'		=> "id IN (" . implode(',', $ex_ids) . ")"
1327
									);
1328
            is_array($plugin_run_result = Plugins::getInstance()->run('qr_update_lstdown_old_files', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1329
			$SQL->build($update_query);
1330
		}
1331
1332
		if(sizeof($ids))
1333
		{
1334
			$query_del	= array(
1335
								'DELETE'	=> "{$dbprefix}files",
1336
								'WHERE'	=> "id IN (" . implode(',', $ids) . ")"
1337
								);
1338
1339
			//update number of stats
1340
			$update_query	= array(
1341
									'UPDATE'	=> "{$dbprefix}stats",
1342
									'SET'		=> "sizes=sizes-$sizes,files=files-$files_num, imgs=imgs-$imgs_num",
1343
									);
1344
1345
            is_array($plugin_run_result = Plugins::getInstance()->run('qr_del_delf_old_files', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1346
1347
			$SQL->build($query_del);
1348
			$SQL->build($update_query);
1349
		}
1350
1351
		update_config('klj_clean_files_from', $last_id_from);
1352
    } //stat_del
1353
}
1354
1355
/**
1356
 * klj_clean_old
1357
 * @param string $table database table
1358
 * @param string|integer $for can be 'all, or a number of days like 30'
1359
 */
1360
function klj_clean_old($table, $for = 'all')
1361
{
1362
	global $SQL, $config, $dbprefix;
1363
1364
	$days = time() - (3600 * 24 * intval($for));
1365
1366
	$query = array(
1367
					'SELECT'	=> 'f.id, f.time',
1368
					'DELETE'		=> "`{$dbprefix}" . $table . "` f",
1369
					'ORDER BY'	=> 'f.id ASC',
1370
					'LIMIT'		=> '30',
1371
					);
1372
1373
	if($for != 'all')
1374
	{
1375
		$query['WHERE']	= "f.time < $days";
1376
	}
1377
1378
    is_array($plugin_run_result = Plugins::getInstance()->run('qr_select_klj_clean_old_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1379
1380
	$result	= $SQL->build($query);
1381
	$num_to_delete = $SQL->num_rows($result);
1382
	if($num_to_delete == 0)
1383
	{
1384
		$t = $table == 'call' ? 'calls' : $table;
1385
		update_config('queue', preg_match('/:del_' . $for . $t . ':/i', '', $config['queue']));
1386
		$SQL->freeresult($result);
1387
		return;
1388
	}
1389
1390
	$ids = array();
1391
	while($row=$SQL->fetch_array($result))
1392
	{
1393
		$ids[] = $row['id'];
1394
	}
1395
1396
	$SQL->freeresult($result);
1397
1398
	$query_del	= array(
1399
							'DELETE'	=> "`" . $dbprefix . $table . "`",
1400
							'WHERE'	=> "id IN (" . implode(',', $ids) . ")"
1401
						);
1402
1403
    is_array($plugin_run_result = Plugins::getInstance()->run('qr_del_delf_old_table', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1404
1405
	$SQL->build($query_del);
1406
1407
	return;
1408
}
1409
1410
/**
1411
* get_ip() for the user
1412
*/
1413
function get_ip()
1414
{
1415
1416
	$ip = '';
1417
    if (!empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
1418
        $ip = $_SERVER["HTTP_CF_CONNECTING_IP"];
1419
    } else if (!empty($_SERVER['REMOTE_ADDR']))
1420
	{
1421
		$ip = $_SERVER['REMOTE_ADDR'];
1422
	}
1423
1424
    #if IP chain
1425
    if (strpos($ip, ',') !== false) {
1426
        $ip = explode(',', $ip);
1427
        $ip = trim($ip[0]);
1428
    }
1429
1430
    #is it IPv6?
1431
    $ip_v6 = preg_match("/^[0-9a-f]{1,4}:([0-9a-f]{0,4}:){1,6}[0-9a-f]{1,4}$/", $ip);
1432
    if ($ip_v6) {
1433
        #does it IPv4 hide in a IPv6 style
1434
        if (stripos($ip, '::ffff:') === 0) {
1435
            $ip = substr($ip, 7);
1436
        }
1437
    }
1438
1439
1440
    $return = preg_replace('/[^0-9a-z.:]/i', '', $ip);
1441
    is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_get_ip_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1442
	return $return;
1443
}
1444
1445
1446
/**
1447
 * Check and verify captcha field after submit
1448
 * @return bool
1449
 */
1450
function kleeja_check_captcha()
1451
{
1452
	global $config;
1453
	if((int) $config['enable_captcha'] == 0 && !defined('IN_REAL_INDEX') && !defined('IN_ADMIN'))
1454
	{
1455
		return true;
1456
	}
1457
1458
1459
	$return = false;
1460
	if(!empty($_SESSION['klj_sec_code']) && ip('kleeja_code_answer'))
1461
	{
1462
		if($_SESSION['klj_sec_code'] == trim(p('kleeja_code_answer')))
1463
		{
1464
			unset($_SESSION['klj_sec_code']);
1465
			$return = true;
1466
		}
1467
	}
1468
1469
    is_array($plugin_run_result = Plugins::getInstance()->run('kleeja_check_captcha_func', get_defined_vars())) ? extract($plugin_run_result) : null; //run hook
1470
	return $return;
1471
}
1472
1473
1474
/**
1475
 * For logging and testing, enabled only for DEV_STAGE!
1476
 * @param string $text a string to log
1477
 */
1478
function kleeja_log($text)
1479
{
1480
	if(!defined('DEV_STAGE'))
1481
	{
1482
		return;
1483
	}
1484
1485
	$log_file = PATH . 'cache/kleeja_log.log';
1486
    $l_c = @file_get_contents($log_file);
1487
	$fp = @fopen($log_file, 'w');
1488
	@fwrite($fp, $text . " [time : " . date('H:i a, d-m-Y') . "] \r\n" . $l_c);
1489
	@fclose($fp);
1490
	return;
1491
}
1492
1493
1494
/**
1495
 * Return the first and last seek of range to be flushed.
1496
 * @param string $range
1497
 * @param $fileSize
1498
 * @return array
1499
 */
1500
function kleeja_set_range($range, $fileSize)
1501
{
1502
	$dash	= strpos($range, '-');
1503
	$first	= trim(substr($range, 0, $dash));
1504
	$last	= trim(substr($range, $dash+1));
1505
	if (!$first)
1506
	{
1507
		$suffix	= $last;
1508
        $last = $fileSize - 1;
1509
        $first = $fileSize - $suffix;
1510
		if($first < 0)
1511
		{
1512
			$first = 0;
1513
		}
1514
	}
1515
	else
1516
	{
1517
        if (!$last || $last > $fileSize - 1) {
1518
            $last = $fileSize - 1;
1519
		}
1520
	}
1521
1522
	if($first > $last)
1523
	{
1524
		//unsatisfiable range
1525
		header("Status: 416 Requested range not satisfiable");
1526
        header("Content-Range: */$fileSize");
1527
		exit;
1528
	}
1529
1530
	return array($first, $last);
1531
}
1532
1533
/**
1534
 * Outputs up to $bytes from the file $file to standard output,
1535
 * $buffer_size bytes at a time.
1536
 * @param resource $file
1537
 * @param integer $bytes
1538
 * @param integer $buffer_size
1539
 */
1540
function kleeja_buffered_range($file, $bytes, $buffer_size = 1024)
1541
{
1542
	$bytes_left = $bytes;
1543
	while($bytes_left > 0 && !feof($file))
1544
	{
1545
		if($bytes_left > $buffer_size)
1546
		{
1547
			$bytes_to_read = $buffer_size;
1548
		}
1549
		else
1550
		{
1551
			$bytes_to_read = $bytes_left;
1552
		}
1553
1554
		$bytes_left	-= $bytes_to_read;
1555
		$contents	= fread($file, $bytes_to_read);
1556
		echo $contents;
1557
		@flush();
1558
		@ob_flush();
1559
	}
1560
}
1561
1562
/**
1563
 * user_can, used for checking the acl for the current user
1564
 * @param string $acl_name
1565
 * @param int $group_id
1566
 * @return bool
1567
 */
1568
function user_can($acl_name, $group_id = 0)
1569
{
1570
	global $d_groups, $userinfo;
1571
1572
	if($group_id == 0)
1573
	{
1574
		$group_id = $userinfo['group_id'];
1575
	}
1576
1577
	return (bool) $d_groups[$group_id]['acls'][$acl_name];
1578
}
1579
1580
1581
function ig($name)
1582
{
1583
    return isset($_GET[$name]) ? true : false;
1584
}
1585
1586
function ip($name)
1587
{
1588
    return isset($_POST[$name]) ? true : false;
1589
}
1590
1591
function g($name, $type = 'str', $default = '')
1592
{
1593
    if (isset($_GET[$name]))
1594
    {
1595
        return $type == 'str' ? htmlspecialchars($_GET[$name]) : intval($_GET[$name]);
1596
    }
1597
1598
    return $type == 'str' ? htmlspecialchars($default) : intval($default);
1599
}
1600
1601
function p($name, $type = 'str', $default = '')
1602
{
1603
    if (isset($_POST[$name]))
1604
    {
1605
        return $type == 'str'
1606
            ? str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), htmlspecialchars(trim($_POST[$name])))
1607
            : intval($_POST[$name]);
1608
    }
1609
1610
1611
    return $type == 'str' ? htmlspecialchars($default) : intval($default);
1612
}
1613
1614
/**
1615
 * add htaccess rule to the .htaccess file
1616
 * @param array|string $rules
1617
 * @param string $unique_id useful for the deletion later
1618
 * @return bool
1619
 */
1620
function add_to_htaccess($rules, $unique_id = '')
1621
{
1622
    if(!file_exists(PATH . '.htaccess') && file_exists(PATH . 'htaccess.txt') && function_exists('rename'))
1623
    {
1624
        rename(PATH . 'htaccess.txt', PATH . '.htaccess');
1625
    }
1626
1627
    #still not exists ?
1628
    if(!file_exists(PATH . '.htaccess'))
1629
    {
1630
        $original_htaccess_content = '<IfModule mod_rewrite.c>' . PHP_EOL . 'RewriteEngine on' . PHP_EOL . '</IfModule>';
1631
        file_put_contents(PATH . '.htaccess', $original_htaccess_content);
1632
    }
1633
1634
    if(!file_exists(PATH . '.htaccess'))
1635
    {
1636
        return false;
1637
    }
1638
1639
1640
    $current_htaccess_content = file_get_contents(PATH . '.htaccess');
1641
1642
1643
    $rules = is_array($rules) ? implode(PHP_EOL, $rules) : $rules;
1644
1645
    if(!empty($unique_id))
1646
    {
1647
        $rules = '#start_' . $unique_id  . PHP_EOL . $rules . PHP_EOL . '#end_' .$unique_id;
1648
    }
1649
1650
1651
    if(strpos($current_htaccess_content, '</IfModule>') !== false)
1652
    {
1653
        $current_htaccess_content = str_replace('</IfModule>', $rules . PHP_EOL .'</IfModule>', $current_htaccess_content);
1654
    }
1655
    else
1656
    {
1657
        $current_htaccess_content .= PHP_EOL . $rules;
1658
    }
1659
1660
1661
    file_put_contents(PATH . '.htaccess', $current_htaccess_content);
1662
1663
    return true;
1664
}
1665
1666
1667
/**
1668
 * remove htaccess rules using previously used unique id
1669
 * @param string $unique_id
1670
 * @return bool
1671
 */
1672
function remove_from_htaccess($unique_id)
1673
{
1674
1675
	$file = PATH . '.htaccess';
1676
1677
    if(!file_exists($file))
1678
    {
1679
		$file = PATH . 'htaccess.txt';
1680
1681
		if(!file_exists($file))
1682
		{
1683
			return true;
1684
		}
1685
    }
1686
1687
1688
    $current_htaccess_content = file_get_contents($file);
1689
1690
    $new_htaccess_content = preg_replace(
1691
        '/^#start_' . preg_quote($unique_id) . '.*' . '#end_' . preg_quote($unique_id) . '$/sm',
1692
        '',
1693
        $current_htaccess_content
1694
        );
1695
1696
1697
    if($new_htaccess_content === $current_htaccess_content)
1698
    {
1699
        return false;
1700
    }
1701
1702
    file_put_contents($file, $new_htaccess_content);
1703
1704
    return true;
1705
1706
}