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
| <?php
function printPre($array, $die = false){
echo "<pre>";
print_r($array);
echo "</pre>";
if($die){
die();
}
}
function random_str($num = 30, $list) {
$promocode = substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'), 0, $num);
$promoList = file_get_contents($list);
if(preg_match('#'.$promocode.'#i', $promoList)){
random_str($num);
}
else {
return $promocode;
}
}
$dirFile = ['dir' => 0, 'file' => 0, 'path' => ''];
function showDir($dirs, $depth=0) {
global $dirFile;
foreach ($dirs as $item) {
$path = "";
if(is_dir($item)){
$dirFile['dir']++;
$dirFile['path'] .= basename($item)."/";
$icon = '<img width="20" height="20" src="https://img.icons8.com/cute-clipart/64/000000/folder-invoices.png">';
$path = $icon . basename($item);
}
else {
$dirFile['file']++;
$icon = '<img width="20" height="20" src="https://img.icons8.com/pastel-glyph/64/000000/regular-file.png">';
$path = "<a href='{$dirFile['path']}".basename($item)."' target='_blank'>".$icon . basename($item) . "</a>";
$dirFile['path'] = "images/";
}
echo str_repeat(' -- ',$depth*1) .$path."<br>"; //can use also "basename($item)" or "realpath($item)"
$subdir = glob($item . DIRECTORY_SEPARATOR . '*'); //use DIRECTORY_SEPARATOR to be OS independent
if (!empty($subdir)) { //if subdir array is not empty make function recursive
showDir($subdir, $depth+1); //execute the function again with current subdir, increment depth
}
}
}
//////////////////////////////////////////////////
//////////// ЗАПРОС ////////
//////////////////////////////////////////////////
function _get($url, $post = false){
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3');
curl_setopt ($ch, CURLOPT_REFERER, $url);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION,1);
//curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//curl_setopt ($ch, CURLOPT_COOKIEFILE,'cookie.txt');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_exec ($ch);
$result = curl_multi_getcontent ($ch);
curl_close ($ch);
$result = iconv('windows-1251', 'UTF-8', $result);
return $result;
}
//пост запросы
function request($settings ){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $settings['url'] ); // отправляем на
curl_setopt($ch, CURLOPT_HEADER, (isset($settings['header'])) ? 1 : 0);// пустые заголовки
curl_setopt($ch, CURLOPT_NOBODY, (isset($settings['nobody'])) ? 1 : 0);// без тела
curl_setopt($ch, CURLOPT_COOKIESESSION, (isset($settings['session'])) ? 1 : 0);// новая сессия
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // возвратить то что вернул сервер
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // следовать за редиректами
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);// таймаут4
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if(isset($settings['cookieFile'])){
curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/'.$settings['cookieFile']); // сохранять куки в файл
curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/'.$settings['cookieFile']);
}
if(isset($settings['cookieHeaders'])){
curl_setopt ($ch, CURLOPT_HTTPHEADER, $settings['cookieHeaders']);
}
if(isset($settings['post'])){
curl_setopt($ch, CURLOPT_POSTFIELDS, $settings['post']);
curl_setopt($ch, CURLOPT_POST, 1 ); // использовать данные в post
}
if(isset($settings['cookieStr'])){
curl_setopt ($ch, CURLOPT_COOKIE, $settings['cookieStr']);
}
if(isset($settings['proxy'])){
$proxy = explode(':', $settings['proxy']);
curl_setopt($ch, CURLOPT_PROXY, $proxy[0]);
curl_setopt($ch, CURLOPT_PROXYPORT, $proxy[1]);
}
$data = curl_exec($ch);
if(curl_exec($ch) === false){
echo 'Ошибка curl: ' . curl_error($ch);
}
curl_close($ch);
if(isset($settings['iconv'])){
//iconv('windows-1251', 'UTF-8', $result);
$data = iconv($settings['iconv']['from'], $settings['iconv']['to'], $data);
}
return $data;
}
//парс со страницы
function _getFromPage($start, $end, $result, $type){
if($end === false || $end == '' ) {
return str_replace($start, '', substr($result, strpos($result, $start)));
}
$start = preg_quote($start);
$end = preg_quote($end);
if($type == "array") {
preg_match_all('#'.$start.'(.*?)'.$end.'#s', $result, $events);
}
if($type == "string"){
preg_match('#'.$start.'(.*?)'.$end.'#s', $result, $events);
}
if(empty($events[1])) {return false;}
else { return $events[1];}
}
function checkProxy($proxy){
//$proxyauth = 'user:password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://dynupdate.no-ip.com/ip.php');
curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$status = explode("\n", $curl_scraped_page);
if(preg_match('/200/i', $status[0])){
return true;
}
else {
return false;
}
}
/*
if(file_exists($file)){
$dif = differenceBetween2dates(time(), filemtime($file));
if($dif['status']){
if($dif['hour'] >= 12){
//обновляем если прошло больше 12 часов с момента последнего обновления
createChapterFile('chapter.txt');
}
}
}
*/
function differenceBetween2dates($date1, $date2){
$r = array();
if(is_numeric($date1) && is_numeric($date2) ){
if($date1 >= $date2){
$sezar = ($date1 - $date2);
$h = $sezar/3600 ^ 0 ;
$m = ($sezar-$h*3600)/60 ^ 0 ;
$s = $sezar-$h*3600-$m*60 ;
$r['hour'] = ($h<10?"0".$h:$h);
$r['min'] = ($m<10?"0".$m:$m);
$r['sec'] = ($s<10?"0".$s:$s);
$r['status'] = true;
$r['message'] = ($h<10?"0".$h:$h)." ч. ".($m<10?"0".$m:$m)." мин. ".($s<10?"0".$s:$s)." сек.";
}
else {
$r['status'] = false;
$r['message'] = 'Дата-1 должна быть больше или равна Дата-2';
}
}
else {
$r['status'] = false;
$r['message'] = 'Дата-1 или Дата-2 не являются цифровыми';
}
return $r;
}
function get_headers_from_curl_response($response){
$headers = array();
$header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
$head_arr = explode("\r\n", $header_text);
for($i = 0;$i < count($head_arr);$i++){
if(preg_match('#Set-Cookie#i', $head_arr[$i])){
list ($key, $value) = explode(':', $head_arr[$i]);
if(!isset($headers[$key])) { $headers[$key] = ''; }
$headers[$key] .= $value;
}
}
return $headers;
}
///////////////////////
///работа с массивом///
///////////////////////
function editArr(&$item, $value, $rule){
if(is_string($rule)){
if(preg_match('#strip#i', $rule)){
$item = strip_tags($item);
}
if(preg_match('#trim#i', $rule)){
$item = trim($item);
$item = str_replace(array("\n", "\r"), '', $item);
}
if(preg_match('#href#i', $rule)){
$item = _getFromPage('href="', '"', $item, 'string');
}
}
if(is_array($rule)){
if(isset($rule['addBefore'])){
$item = $rule['addBefore'].$item;
}
if(isset($rule['addAfter'])){
$item = $item.$rule['addAfter'];
}
if(isset($rule['replace'])){
$item = preg_replace('`'.$rule['replace'][0].'`i', $rule['replace'][1], $item);
}
if(isset($rule['getFromPage'])){
preg_match('`'.$rule['getFromPage'][0].'(.*?)'.$rule['getFromPage'][1].'`s', $item, $events);
$item = $events[1];
}
if(isset($rule['convert'])){
$item = iconv($rule['convert'][0], $rule['convert'][1], $item);
}
}
}
/////////////////////
//работа со строкой//
/////////////////////
function editStr($item, $rule, $value = false){
if(preg_match('/strip/i', $rule)){
$item = strip_tags($item);
}
if(preg_match('/trim/i', $rule)){
$item = trim($item);
}
if(preg_match('/href/i', $rule)){
if(preg_match('/href="/i', $item)){
$item = _getFromPage('href="', '"', $item, 'string');
}
if(preg_match("/href='/i", $item)){
$item = _getFromPage("href='", "'", $item, 'string');
}
}
if(preg_match('/src/i', $rule)){
if(preg_match('/src="/i', $item)){
$item = _getFromPage('src="', '"', $item, 'string');
}
if(preg_match("/src='/i", $item)){
$item = _getFromPage("src='", "'", $item, 'string');
}
}
if(preg_match('/replace/i', $rule)){
$item = preg_replace('`'.$value.'`i', '', $item);
}
return $item;
}
//////////////////////////////
// Оптимизация изображений ///
//////////////////////////////
function compressImage($image_link, $ImageQuality){
//Open Source Image directory, loop through each Image and resize it.
$checkValidImage = @getimagesize($image_link);
//Continue only if 2 given parameters are true
if (file_exists($image_link) && $checkValidImage) {
//Image looks valid, resize.
resizeImage($image_link, $image_link, $checkValidImage[0], $checkValidImage[1], $ImageQuality);
}
}
//Function that resizes image.
function resizeImage($SrcImage, $DestImage, $MaxWidth, $MaxHeight, $ImageQuality){
list($iWidth, $iHeight, $type) = getimagesize($SrcImage);
$ImageScale = min($MaxWidth / $iWidth, $MaxHeight / $iHeight);
$NewWidth = ceil($ImageScale * $iWidth);
$NewHeight = ceil($ImageScale * $iHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
switch (strtolower(image_type_to_mime_type($type))) {
case 'image/jpeg': $NewImage = imagecreatefromjpeg($SrcImage); break;
case 'image/JPEG': $NewImage = imagecreatefromjpeg($SrcImage); break;
case 'image/png': $NewImage = imagecreatefrompng($SrcImage); break;
case 'image/PNG': $NewImage = imagecreatefrompng($SrcImage); break;
case 'image/gif': $NewImage = imagecreatefromgif($SrcImage); break;
default: return false;
}
// Resize Image
if (imagecopyresampled($NewCanves, $NewImage, 0, 0, 0, 0, $NewWidth, $NewHeight,
$iWidth, $iHeight)) {
// copy file
if (imagejpeg($NewCanves, $DestImage, $ImageQuality)) {
imagedestroy($NewCanves);
return true;
}
}
}
//РАЗМЕР ФАЙЛА
function get_filesize($file){
$data = get_headers($file, true);
$filesize = isset($data['Content-Length'])?(int) $data['Content-Length']:0;
if($filesize > 1024) {
$filesize = ($filesize/1024);
if($filesize > 1024) {
$filesize = ($filesize/1024);
if($filesize > 5) { return false; }
else{ return true; }
}
else { return true; }
}
else{ return true; }
}
////////////////////////
///транслит для алиас///
////////////////////////
function rus2translit($string) {
$converter = array(
'а' => 'a', 'б' => 'b', 'в' => 'v',
'г' => 'g', 'д' => 'd', 'е' => 'e',
'ё' => 'e', 'ж' => 'zh', 'з' => 'z',
'и' => 'i', 'й' => 'y', 'к' => 'k',
'л' => 'l', 'м' => 'm', 'н' => 'n',
'о' => 'o', 'п' => 'p', 'р' => 'r',
'с' => 's', 'т' => 't', 'у' => 'u',
'ф' => 'f', 'х' => 'h', 'ц' => 'c',
'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch',
'ь' => '', 'ы' => 'y', 'ъ' => '',
'э' => 'e', 'ю' => 'yu', 'я' => 'ya',
',' => '', '"' => '',
"'" => '',
'А' => 'A', 'Б' => 'B', 'В' => 'V',
'Г' => 'G', 'Д' => 'D', 'Е' => 'E',
'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z',
'И' => 'I', 'Й' => 'Y', 'К' => 'K',
'Л' => 'L', 'М' => 'M', 'Н' => 'N',
'О' => 'O', 'П' => 'P', 'Р' => 'R',
'С' => 'S', 'Т' => 'T', 'У' => 'U',
'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch',
'Ь' => '', 'Ы' => 'Y', 'Ъ' => '',
'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya',
);
return strtr($string, $converter);
}
function str2url($str) {
// переводим в транслит
$str = rus2translit($str);
// в нижний регистр
$str = strtolower($str);
// заменям все ненужное нам на "-"
$str = preg_replace('~[^-a-z0-9_]+~u', '-', $str);
// удаляем начальные и конечные '-'
$str = trim($str, "-");
return $str;
}
function getCSV($csv_file) {
$handle = fopen($csv_file, "r"); //Открываем csv для чтения
$array_line_full = array(); //Массив будет хранить данные из csv
//Проходим весь csv-файл, и читаем построчно. 3-ий параметр разделитель поля
while (($line = fgetcsv($handle, 0, ";")) !== FALSE) {
$array_line_full[] = $line; //Записываем строчки в массив
}
fclose($handle); //Закрываем файл
return $array_line_full; //Возвращаем прочтенные данные
}
function setCSV($dataArray, $csv_file) {
//$dataArray = array("1;2;3", "1;2;3");
//Открываем csv для до-записи,
//если указать w, то ифнормация которая была в csv будет затерта// "a"
$handle = fopen($csv_file, "w");
foreach ($dataArray as $value) { //Проходим массив
//Записываем, 3-ий параметр - разделитель поля
fputcsv($handle, explode(";", $value), ";");
}
fclose($handle); //Закрываем
}
function uploadFile($fromFile, $toFile){
$return = [];
//грузим изображение на хостинг
$img_name = basename($fromFile);
$toDir = dirname($toFile);
if(!is_dir($toDir)){
if (!mkdir($toDir, 0777, true)) {
return $return = ["status" => false, "message" => "Не удалось создать директорию."];
}
}
if(!file_exists($toFile)){
if(strlen($fromFile) > 5){
$headers = @get_headers($fromFile);
if (preg_match("/(200 OK)$/", $headers[0])) {
$img_content = file_get_contents($fromFile);
if($img_content !== false){
file_put_contents($toFile, $img_content);
return $return = ["status" => true, "message" => "Файл ".$toFile." успешно загружен"];
}
else {
return $return = ["status" => false, "message" => "Не удалось получить удаленный файл ".$fromFile."."];
}
}
else {
return $return = ["status" => false, "message" => "Удаленный файл ".$fromFile." не существует."];
}
}
else {
return $return = ["status" => false, "message" => "Название файла ".$fromFile." слишком короткое."];;
}
}
return $return = ["status" => true, "message" => "Файл ".$toFile." уже существует"];
}
//application/msword
function getFiletype($filelink){
$mime = get_headers($filelink);
if(is_array($mime)){
$found = preg_grep('/Content-Type/i', $mime);
$content_type = array_shift($found);
list($content_type, $content_value) = explode(':', $content_type);
$content_value = trim($content_value);
$types = array(".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".aac" => "audio/aac", ".abw" => "application/x-abiword",".arc" => "application/octet-stream",".avi" => "video/x-msvideo",".azw" => "application/vnd.amazon.ebook",".bin" => "application/octet-stream",".bz" => "application/x-bzip",".bz2" => "application/x-bzip2",".csh" => "application/x-csh",".css" => "text/css",".csv" => "text/csv",".doc" => "application/msword",".eot" => "application/vnd.ms-fontobject",".epub" => "application/epub+zip",".gif" => "image/gif",".html" => "text/html", ".ico" => "image/x-icon", ".ics" => "text/calendar", ".jar" => "application/java-archive",".jpg" => "image/jpeg",".js" => "application/javascript",".json" => "application/json",".midi" => "audio/midi",".mpeg" => "video/mpeg",".mpkg" => "application/vnd.apple.installer+xml",".odp" => "application/vnd.oasis.opendocument.presentation",".ods" => "application/vnd.oasis.opendocument.spreadsheet",".odt" => "application/vnd.oasis.opendocument.text",".oga" => "audio/ogg",".ogv" => "video/ogg",".ogx" => "application/ogg",".otf" => "font/otf",".png" => "image/png",".pdf" => "application/pdf",".ppt" => "application/vnd.ms-powerpoint",".rar" => "application/x-rar-compressed",".rtf" => "application/rtf",".sh" => "application/x-sh",".svg" => "image/svg+xml",".swf" => "application/x-shockwave-flash",".tar" => "application/x-tar",".tiff" => "image/tiff",".ts" => "video/vnd.dlna.mpeg-tts",".ttf" => "font/ttf",".vsd" => "application/vnd.visio",".wav" => "audio/x-wav",".weba" => "audio/webm",".webm" => "video/webm",".webp" => "image/webp",".woff" => "font/woff",".woff2" => "font/woff2",".xhtml" => "application/xhtml+xml",".xls" => "application/vnd.ms-excel",".xml" => "application/xml",".xul" => "application/vnd.mozilla.xul+xml",".zip" => "application/zip",".7z" => "application/x-7z-compressed");
foreach ($types as $key => $value) {
$s = preg_quote($value);
if(preg_match('#'.$s.'#i', $content_value)){
return array('status' => true, 'value' => $key);
}
}
return array('status' => false, 'value' => '.unknown');
}
return array('status' => false, 'value' => '.unknown');
}
?> |