Completed
Push — master ( ac1b20...2d8bf8 )
by Agel_Nash
02:36
created

utils.functions.php ➔ make_csv()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style introduced by
File has mixed line endings; this may cause incorrect results
Loading history...
2
if (!function_exists('check_email')) {
3
	/**
4
	 * Проверка строки с email на наличие ошибок
5
	 * Если e-mail валидный, то в ответ будет получено false
6
	 * В противном случае имя ошибки
7
	 *     dns - ошибка проверки MX и A записи почтового домена
8
	 *     format - ошибка формата email
9
	 *
10
	 * @param string $email проверяемый email
11
	 * @param bool $dns проверять ли DNS записи
12
	 * @return false|string Результат проверки почтового ящика
13
	 */
14
	function check_email($email, $dns = true)
15
	{
16
		if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
17
			list(, $domain) = explode("@", $email, 2);
18
			if (!$dns || ($dns && checkdnsrr($domain, "MX") && checkdnsrr($domain, "A"))) {
19
				$error = false;
20
			}else {
21
				$error = 'dns';
22
			}
23
		}else {
24
			$error = 'format';
25
		}
26
		return $error;
27
	}
28
}
29
30
if (!function_exists('generate_password')) {
31
	/**
32
	 * Генерация пароля
33
	 *
34
	 * @param string $len длина пароля
35
	 * @param string $data правила генерации пароля
36
	 * @return string Строка с паролем
37
	 *
38
	 * Расшифровка значений $data
39
	 *     "A": A-Z буквы
40
	 *     "a": a-z буквы
41
	 *     "0": цифры
42
	 *     ".": все печатные символы
43
	 *
44
	 * @example
45
	 *     generate_password(10,"Aa"); //nwlTVzFdIt
46
	 *     generate_password(8,"0"); //71813728
47
	 *     generate_password(11,"A"); //VOLRTMEFAEV
48
	 *     generate_password(5,"a0"); //4hqi7
49
	 *     generate_password(5,"."); //2_Vt}
50
	 *     generate_password(20,"."); //AMV,>&?J)v55,(^g}Z06
51
	 *     generate_password(20,"aaa0aaa.A"); //rtvKja5xb0\KpdiRR1if
52
	 */
53
	function generate_password($len, $data = '')
54
	{
55
		if ($data == '') {
56
			$data = 'Aa0.';
57
		}
58
		$opt = strlen($data);
59
		$pass = array();
60
		for ($i = $len; $i > 0; $i--) {
61
			switch ($data[rand(0, ($opt - 1))]) {
62
				case 'A': 
63
					$tmp = rand(65, 90);
64
					break;
65
				case 'a':
66
					$tmp = rand(97, 122);
67
					break;
68
				case '0':
69
					$tmp = rand(48, 57);
70
					break;
71
				default:
72
					$tmp = rand(33, 126);
73
			}
74
			$pass[] = chr($tmp);
75
		}
76
		$pass = implode("", $pass);
77
		return $pass;
78
	}
79
}
80
81
if (!function_exists('get_gravatar')) {
82
	/**
83
	 * Получение ссылки на аватарку с gravatar
84
	 *
85
	 * @param   string $email Почта
86
	 * @param   integer $size Размер аватарки
87
	 * @return  string
88
	 */
89
	function get_gravatar($email, $size = 32)
90
	{
91
		$url = '//www.gravatar.com/avatar/' . md5(is_scalar($email) ? $email : '') . '?s=' . (int)abs($size);
92
		return $url;
93
	}
94
}
95
96
if (!function_exists('share_vk')) {
97
	/**
98
	 * Получение ссылки поделиться для "Вконтакте"
99
	 *
100
	 * @param  string $url Страница которой следует поделиться
101
	 * @param  string $title Заголовок
102
	 * @return string
103
	 */
104
	function share_vk($url, $title = '')
105
	{
106
		return 'http://vkontakte.ru/share.php?url=' . urlencode($url) . '&title=' . urlencode($title);
107
	}
108
}
109
110
if (!function_exists('share_ok')) {
111
	/**
112
	 * Получение ссылки поделиться для "Одноклассников"
113
	 *
114
	 * @param  string $url Страница которой следует поделиться
115
	 * @param  string $title Заголовок
116
	 * @return string
117
	 */
118
	function share_ok($url, $title = '')
119
	{
120
		return 'http://www.odnoklassniki.ru/dk?st.cmd=addShare&st._surl=' . urlencode($url) . '&st.comments=' . urlencode($title);
121
	}
122
}
123
124
if (!function_exists('share_google')) {
125
	/**
126
	 * Получение ссылки поделиться для "Google+"
127
	 *
128
	 * @param  string $url Страница которой следует поделиться
129
	 * @return string
130
	 */
131
	function share_google($url)
132
	{
133
		return 'https://plus.google.com/share?url=' . urlencode($url);
134
	}
135
}
136
137
if (!function_exists('share_facebook')) {
138
	/**
139
	 * Получение ссылки поделиться для "Facebook"
140
	 *
141
	 * @param  string $url Страница которой следует поделиться
142
	 * @param  string $title Заголовок
143
	 * @return string
144
	 */
145
	function share_facebook($url, $title = '')
146
	{
147
		return 'http://www.facebook.com/sharer/sharer.php?s=100&p[url]=' . urlencode($url) . '&p[title]=' . urlencode($title);
148
	}
149
}
150
151
if (!function_exists('share_twitter')) {
152
	/**
153
	 * Получение ссылки поделиться для "Twitter"
154
	 *
155
	 * @param  string $url Страница которой следует поделиться
156
	 * @param  string $title Заголовок
157
	 * @return string
158
	 */
159
	function share_twitter($url, $title = '')
160
	{
161
		return 'https://twitter.com/intent/tweet?url=' . urlencode($url) . '&text=' . urlencode($title);
162
	}
163
}
164
165
if (!function_exists('share_mail')) {
166
	/**
167
	 * Получение ссылки поделиться для "Mail.ru"
168
	 *
169
	 * @param  string $url Страница которой следует поделиться
170
	 * @param  string $title Заголовок
171
	 * @return string
172
	 */
173
	function share_mail($url, $title = '')
174
	{
175
		return 'http://connect.mail.ru/share?share_url=' . urlencode($url) . '&title=' . urlencode($title);
176
	}
177
}
178
179
if (!function_exists('share_linkedin')) {
180
	/**
181
	 * Получение ссылки поделиться для "LinkedIN"
182
	 *
183
	 * @param  string $url Страница которой следует поделиться
184
	 * @param  string $title Заголовок
185
	 * @return string
186
	 */
187
	function share_linkedin($url, $title = '')
188
	{
189
		return 'http://www.linkedin.com/shareArticle?mini=true&url=' . urlencode($url) . '&title=' . urlencode($title);
190
	}
191
}
192
193
if (!function_exists('qr_code')) {
194
	/**
195
	 * Генерация QR-кода для строки
196
	 *
197
	 * @param string $str строка
198
	 * @param int $size размер картинки
199
	 * @return string
200
	 */
201
	function qr_code($str, $size = 230)
202
	{
203
		$size = (int)$size;
204
		$size = implode("x", array($size, $size));
205
		return '//chart.apis.google.com/chart?cht=qr&chs=' . $size . '&chl=' . (is_scalar($str) ? urlencode($str) : '');
206
	}
207
}
208
209
if (!function_exists('get_user_ip')) {
210
	/**
211
	 * Получение реального ip текущего пользователя
212
	 *
213
	 * @param string $out IP адрес который будет отдан функцией, если больше ничего не обнаружено
214
	 * @return string IP пользователя
215
	 *
216
	 * @see http://stackoverflow.com/questions/5036443/php-how-to-block-proxies-from-my-site
217
	 */
218
	function get_user_ip($out = '127.0.0.1')
219
	{
220
		$_getEnv = function($data) {
221
			switch (true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $tmp = getenv($data) of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
222
				case (isset($_SERVER[$data])):
223
					$out = $_SERVER[$data];
224
					break;
225
				case (isset($_ENV[$data])):
226
					$out = $_ENV[$data];
227
					break;
228
				case ($tmp = getenv($data)):
229
					$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
230
					break;
231
				case (function_exists('apache_getenv') && $tmp = apache_getenv($data, true)):
232
					$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
233
					break;
234
				default:
235
					$out = false;
236
			}
237
			unset($tmp);
238
			return $out;
239
		};
240
241
		//Порядок условий зависит от приоритетов
242
		switch (true === true) {
243
			case ($tmp = $_getEnv('HTTP_COMING_FROM')):
244
				$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
245
				break;
246
			case ($tmp = $_getEnv('HTTP_X_COMING_FROM')):
247
				$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
248
				break;
249
			case ($tmp = $_getEnv('HTTP_VIA')):
250
				$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
251
				break;
252
			case ($tmp = $_getEnv('HTTP_FORWARDED')):
253
				$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
254
				break;
255
			case ($tmp = $_getEnv('HTTP_FORWARDED_FOR')):
256
				$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
257
				break;
258
			case ($tmp = $_getEnv('HTTP_X_FORWARDED')):
259
				$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
260
				break;
261
			case ($tmp = $_getEnv('HTTP_X_FORWARDED_FOR')):
262
				$out = $tmp;
0 ignored issues
show
Bug introduced by
The variable $tmp seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
263
				break;
264
			case (!empty($_SERVER['REMOTE_ADDR'])):
265
				$out = $_SERVER['REMOTE_ADDR'];
266
				break;
267
		}
268
		unset($tmp);
269
		return (is_scalar($out) && preg_match('|^(?:[0-9]{1,3}\.){3,3}[0-9]{1,3}$|', $out, $matches)) ? $out : false;
270
	}
271
}
272
273
if (!function_exists('whois_query')) {
274
	/**
275
	 * Получение whois информации о домене
276
	 * @see http://www.jonasjohn.de/snippets/php/whois-query.htm
277
	 *
278
	 * @param string $domain домен
279
	 * @return string
280
	 */
281
	function whois_query($domain)
282
	{
283
284
		// fix the domain name:
285
		$domain = strtolower(trim($domain));
286
		$domain = preg_replace('/^http:\/\//i', '', $domain);
287
		$domain = preg_replace('/^www\./i', '', $domain);
288
		$domain = explode('/', $domain);
289
		$domain = trim($domain[0]);
290
291
		// split the TLD from domain name
292
		$_domain = explode('.', $domain);
293
		$lst = count($_domain) - 1;
294
		$ext = $_domain[$lst];
295
296
		// You find resources and lists
297
		// like these on wikipedia:
298
		//
299
		// <a href="http://de.wikipedia.org/wiki/Whois">http://de.wikipedia.org/wiki/Whois</a>
300
		//
301
		$servers = array(
302
			"biz" => "whois.neulevel.biz",
303
			"com" => "whois.internic.net",
304
			"us" => "whois.nic.us",
305
			"coop" => "whois.nic.coop",
306
			"info" => "whois.nic.info",
307
			"name" => "whois.nic.name",
308
			"net" => "whois.internic.net",
309
			"gov" => "whois.nic.gov",
310
			"edu" => "whois.internic.net",
311
			"mil" => "rs.internic.net",
312
			"int" => "whois.iana.org",
313
			"ac" => "whois.nic.ac",
314
			"ae" => "whois.uaenic.ae",
315
			"at" => "whois.ripe.net",
316
			"au" => "whois.aunic.net",
317
			"be" => "whois.dns.be",
318
			"bg" => "whois.ripe.net",
319
			"br" => "whois.registro.br",
320
			"bz" => "whois.belizenic.bz",
321
			"ca" => "whois.cira.ca",
322
			"cc" => "whois.nic.cc",
323
			"ch" => "whois.nic.ch",
324
			"cl" => "whois.nic.cl",
325
			"cn" => "whois.cnnic.net.cn",
326
			"cz" => "whois.nic.cz",
327
			"de" => "whois.nic.de",
328
			"fr" => "whois.nic.fr",
329
			"hu" => "whois.nic.hu",
330
			"ie" => "whois.domainregistry.ie",
331
			"il" => "whois.isoc.org.il",
332
			"in" => "whois.ncst.ernet.in",
333
			"ir" => "whois.nic.ir",
334
			"mc" => "whois.ripe.net",
335
			"to" => "whois.tonic.to",
336
			"tv" => "whois.tv",
337
			"ru" => "whois.ripn.net",
338
			"org" => "whois.pir.org",
339
			"aero" => "whois.information.aero",
340
			"nl" => "whois.domain-registry.nl"
341
		);
342
343
		if (!isset($servers[$ext])) {
344
			throw new ErrorException('No matching nic server found!');
345
		}
346
347
		$nic_server = $servers[$ext];
348
349
		$output = '';
350
351
		// connect to whois server:
352
		if ($conn = fsockopen($nic_server, 43)) {
353
			fputs($conn, $domain . "\r\n");
354
			while (!feof($conn)) {
355
				$output .= fgets($conn, 128);
356
			}
357
			fclose($conn);
358
		}else {
359
			throw new ErrorException('Could not connect to ' . $nic_server . '!');
360
		}
361
362
		return $output;
363
	}
364
}
365
366
if (!function_exists('copyright')) {
367
	/**
368
	 * Геренатор года для подстановки в копирайты
369
	 *
370
	 * @param string $year год запуска проекта
371
	 * @param string $sep разделитель годов
372
	 * @return string
373
	 */
374
	function copyright($year, $sep = ' - ')
375
	{
376
		$y = date('Y');
377
		return ($y != $year) ? ($year . $sep . $y) : $year;
378
	}
379
}
380
381
if (!function_exists('mime_file')) {
382
	/**
383
	 * Получение MIME типа файла
384
	 *
385
	 * @param string $fname путь к файлу
386
	 * @return string
387
	 */
388
	function mime_file($fname)
389
	{
390
		$out = null;
391
		switch (true) {
392
			case class_exists('\finfo'):
393
				$fi = new \finfo(FILEINFO_MIME);
394
				$out = $fi->file($fname);
395
				break;
396
			case function_exists('mime_content_type'):
397
				list($out) = explode(';', @mime_content_type($fname));
398
				break;
399
			default:
400
				/**
401
				 * @see: http://www.php.net/manual/ru/function.finfo-open.php#112617
402
				 */
403
				$fh = fopen($fname, 'rb');
404
				if ($fh) {
405
					$bytes6 = fread($fh, 6);
406
					fclose($fh);
407
					switch (true) {
408
						case ($bytes6 === false):
409
							break;
410
						case (substr($bytes6, 0, 3) == "\xff\xd8\xff"):
411
							$out = 'image/jpeg';
412
							break;
413
						case ($bytes6 == "\x89PNG\x0d\x0a"):
414
							$out = 'image/png';
415
							break;
416
						case ($bytes6 == "GIF87a" || $bytes6 == "GIF89a"):
417
							$out = 'image/gif';
418
							break;
419
						default:
420
							$out = 'application/octet-stream';
421
					}
422
				}
423
		}
424
		return $out;
425
	}
426
}
427
428
if (!function_exists('image_size')) {
429
	/**
430
	 * Определение размеров картинки
431
	 *
432
	 * @param string $image путь к картинке
433
	 * @param string|null $mode какой размер ширину/высоту или все вместе
434
	 * @return array|int
435
	 */
436
	function image_size($image, $mode = null)
437
	{
438
		$width = $height = 0;
439
		if (is_scalar($image) && is_file($image)) {
440
			$size = @getimagesize($image);
441
			$width = isset($size[0]) ? $size[0] : 0;
442
			$height = isset($size[1]) ? $size[1] : 0;
443
		}
444
		switch ($mode) {
445
			case 'w':
446
			case 'width':
447
				$out = $width;
448
				break;
449
			case 'h':
450
			case 'height':
451
				$out = $height;
452
				break;
453
			default:
454
				$out = array($width, $height);
455
		}
456
		return $out;
457
	}
458
}
459
460
if (!function_exists('plural')) {
461
	/**
462
	 * Определение падежа слова в зависимости от числового значения
463
	 *
464
	 * @param int|string $number число
465
	 * @param array $titles массив слов в разных склонениях (1 яблоко, 2 яблока, 5 яблок)
466
	 * @return string
467
	 */
468
	function plural($number, array $titles = array())
469
	{
470
		$cases = array(2, 0, 1, 1, 1, 2);
471
		$number = (int)$number;
472
		$position = ($number % 100 > 4 && $number % 100 < 20) ? 2 : $cases[($number % 10 < 5) ? $number % 10 : 5];
473
		$out = isset($titles[$position]) ? $titles[$position] : '';
474
		return $out;
475
	}
476
}
477
478
if (!function_exists('validate_date')) {
479
	/**
480
	 * Проверка валидности даты
481
	 *
482
	 * Пример валидации даты через дополнительную проверку $validator
483
	 * function($date, $iterval){
484
	 * 		return ($iterval->format('%R') == '+');
485
	 * }
486
	 * Таким образом все даты которые уже прошли будут помечены как не валидные
487
	 *
488
	 * @param string $date проверяемая дата
489
	 * @param string $fromFormat в каком формате записана исходная дата
490
	 * @param string $toFormat в каком формате вернуть дату, если она валидна
491
	 * @param Closure $validator метод для дополнительной проверки даты
492
	 * @return null|string
493
	 */
494
	function validate_date($date, $fromFormat = 'Y-m-d', $toFormat = 'Y-m-d', Closure $validator = null) {
495
		$validTime = false;
496
		$datetime2 = null;
497
		if (is_scalar($date)) {
498
			$datetime1 = new \DateTime("NOW");
499
			$datetime2 = \DateTime::createFromFormat($fromFormat, $date);
500
			if ($datetime2 instanceof \DateTime) {
501
				$interval = $datetime1->diff($datetime2);
502
				$validTime = is_callable($validator) ? (bool)$validator($datetime2, $interval) : true;
503
			}
504
		}
505
		return $validTime ? $datetime2->format($toFormat) : null;
506
	}
507
}
508
if (!function_exists('format_bytes')) {
509
	/**
510
	 * Преобразование из байт в другие порядки (кило, мега, гига) с добавлением префикса
511
	 *
512
	 * @param string $bytes Обрабатываемое число
513
	 * @param integer $precision До какого числа после запятой округлять
514
	 * @param array $suffixes Массив суффиксов
515
	 * @return string
516
	 */
517
	function format_bytes($bytes, $precision = 2, $suffixes = array('Байт', 'Кбайт', 'Мбайт', 'Гбайт', 'Тбайт')) {
518
		$bytes = (float)$bytes;
519
		if(empty($bytes)) {
520
			return 0;
521
		}
522
		$base = log($bytes, 1024);
523
		return trim(round(pow(1024, $base - floor($base)), $precision) . ' ' .get_key($suffixes, (int)$base, '', 'is_scalar'));
0 ignored issues
show
Documentation introduced by
'is_scalar' is of type string, but the function expects a object<Closure>|null.

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...
524
	}
525
}
526
527
if(!function_exists('format_microtime')){
528
	/**
529
	 * Форматирование microtime времени
530
	 * @param string $time microtime время 
531
	 * @param int $len Кол-во символов после точки
532
	 */
533
	function format_microtime($time, $len = 4){
534
		return sprintf("%.".(int)$len."f", $time);
535
	}
536
}
537
if(!function_exists('ip_in_range')){
538
	/**
539
	 * Входит ли указанный IP в заданный диапазон
540
	 *
541
	 * @param string $ip IP клиента
542
	 * @param string $lower Начальный IP диапазона
543
	 * @param string $upper Конечный IP диапазона
544
	 * @return bool
545
	 */
546
	function in_ip_range($ip, $lower, $upper){
547
		return (ip2long($lower) <= ip2long($ip) && ip2long($upper) >= ip2long($ip)) ? TRUE : FALSE;
548
	}
549
}
550
551
if(!function_exists('make_csv')){
552
	/**
553
	 * Формирование правильной CSV строки
554
	 *
555
     * @see: https://stackoverflow.com/questions/3933668/convert-array-into-csv
556
	 * @param array $data Массив с данными
557
	 * @return string
558
     */
559
    function make_csv($data){
560
        // Create a stream opening it with read / write mode
561
        $stream = fopen('data://text/plain,' . "", 'w+');
562
563
        // Iterate over the data, writting each line to the text stream
564
        fputcsv($stream, $data);
565
566
        // Rewind the stream
567
        rewind($stream);
568
569
        // You can now echo it's content
570
        $out = stream_get_contents($stream);
571
572
        // Close the stream
573
        fclose($stream);
574
        return $out;
575
    }
576
}