forked from TerVel76/Akina-admin-lite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adm.php
1738 lines (1528 loc) · 62.3 KB
/
adm.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*--------------------------------------------------
| Akina Admin Panel
+--------------------------------------------------
| version 0.0.3
| By Vladek aka TerVel
| URL: https://github.com/TerVel76/akina
| URL: https://code.google.com/p/akina/
| Last Changed: 2015-07-15
+--------------------------------------------------
| OPEN SOURCE CONTRIBUTIONS
+--------------------------------------------------
| function write_ini_file() by Harikrishnan
| http://stackoverflow.com/questions/1268378/create-ini-file-write-values-in-php
| в том код был баг, исправил ;)
|
| functions from dir.php Version 0.4 Apr 06 2010
| A script to manage files on your web
| Questions, comments, bug reports to : yannickf@yahoo.com
| SourceForge project phpFileManager:
| http://sourceforge.net/project/?group_id=1640
|
| functions from phpFileManager 0.9.8
| By Fabricio Seger Kolling
| Copyright (c) 2004-2013 Fabrício Seger Kolling
| E-mail: dulldusk@gmail.com
| URL: http://phpfm.sf.net
+--------------------------------------------------
| It is the AUTHOR'S REQUEST that you keep intact the above header information
| and notify him if you conceive any BUGFIXES or IMPROVEMENTS to this program.
+--------------------------------------------------
| LICENSE
+--------------------------------------------------
| Licensed under the terms of any of the following licenses at your choice:
| - GNU General Public License Version 2 or later (the "GPL");
+--------------------------------------------------
| CONFIGURATION AND INSTALATION NOTES
+--------------------------------------------------
| This program does not include any instalation or configuration
| notes because it simply does not require them.
| Just throw this file anywhere in your webserver and enjoy !!
+--------------------------------------------------
*/
define('akina', 'photohost', true);
header('Content-Type: text/html; charset=utf-8');
// write_ini_file() запись массива в файл INI
function write_ini_file ($assoc_arr, $path, $has_sections=FALSE)
{
$content = "";
if ($has_sections)
{
foreach ($assoc_arr as $key=>$elem)
{
$content .= "[".$key."]\n";
foreach ($elem as $key2=>$elem2)
{
if(is_array($elem2))
{
for($i=0;$i<count($elem2);$i++)
{
$content .= $key2."[] = \"".$elem2[$i]."\"\n";
}
}
else if($elem2==='') $content .= $key2." = \n";
else $content .= $key2." = \"".$elem2."\"\n";
}
}
}
else
{
foreach ($assoc_arr as $key=>$elem)
{
if(is_array($elem))
{
for($i=0;$i<count($elem);$i++)
{
$content .= $key."[] = \"".$elem[$i]."\"\n";
}
}
else if($elem==='') $content .= $key." = \n";
else $content .= $key." = \"".$elem."\"\n";
}
}
if (!$handle = @fopen($path, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success;
}
// содержится файл конфигурации config.php поставляемый по "умолчанию"
function new_config()
{
/* --------------------------------------------------------------------------
Далее содержится файл конфигурации config.php поставляемый по "умолчанию"
По состоянию на v1.0.9h (r77) Jun 26, 2015
----------------------------------------------------------------------------- */
//////////////////////////////////////параметры изображений//////////////////////////////////////
$config['max_size_mb']=5;
$config['max_size_byte']=$config['max_size_mb']*1048576; // (bytes)
$config['max_height']=5000;
$config['max_width']=5000;
$config['view_one_width']="auto"; //ширина картинки на странице просмотра. картинка одна, большая
$config['view_multi_width']="auto"; //ширина картинок на странице просмотра при мультизагрузке
$config['quality']=100;
$config['mimes']=array('image/gif', 'image/pjpeg', 'image/jpeg', 'image/png', 'image/bmp', 'image/x-ms-bmp');
//расширения которые можно загружать (jpeg и jpe - это jpg)
$config['extensions']=array(
'gif',
'jpg',
'png',
'bmp',
);
$config['auto_resize']=0; //Уменьшить изображение, по умолчанию форма: 0 - выключена, 1 - включена
$config['width_resize_elements']=1024; //уменьшать изображения по ширине, по умолчанию в форме
//$config['height_resize_elements']=768; //уменьшать изображения по высоте, по умолчанию в форме
// для исключения искажения изображения добавляется только один параметр, по ширине - имеет приоритет.
$config['auto_preview']=0; //Создать превью, по умолчанию форма: 0 - выключена, 1 - включена
$config['width_preview_elements']=240; //превью по ширине, по умолчанию в форме
//$config['height_preview_elements']=180; //превью по высоте, по умолчанию в форме
// для исключения искажения изображения добавляется только один параметр, по ширине - имеет приоритет.
//////////////////////////////////////абсолютные пути//////////////////////////////////////
$config['site_dir']=getcwd();
$config['uploaddir']=$config['site_dir'].'/img/';
$config['thumbdir']=$config['site_dir'].'/thumbs/';
$config['working_dir']=$config['site_dir'].'/working/';
$config['working_thumb_dir']=$config['working_dir'].'thumbs/';
//////////////////////////////////////URL//////////////////////////////////////
preg_match('/\/(.*\/).*\.php/', $_SERVER['PHP_SELF'], $out);
$folder = isset($out[1]) ? $out[1]:'';
$config['site_url']='http://'.$_SERVER['HTTP_HOST'].'/'.$folder;
$config['thumbs_url']=$config['site_url'].'thumbs/';
$config['img_url']=$config['site_url'].'img/';
//////////////////////////////////////Шаблон//////////////////////////////////////
//доступные шаблоны 'bluestyle', 'graphene' , 'simple', 'whatsyoursolution'
$config['template_name']='whatsyoursolution';
$config['template_path']=$config['site_dir'].'/templates/'.$config['template_name'];
$config['template_url']=$config['site_url'].'templates/'.$config['template_name'];
$config['site_title']='Хостинг картинок AKINA'; //Title страницы, возможно динамическое обновление
$config['site_header_h1']='Фотохостинг Akina'; //Текст в заголовке сайта тэг H1, возможно динамическое обновление
$config['site_header_h2']='Хостинг картинок'; //Текст в заголовке сайта тэг H2, возможно динамическое обновление
$config['view_page']=1; //добавлять к коду изображения с превью ссылку на "Страницу просмотра" 0 - выключено, 1 - включено
//если выключено всегда будет ссылка вести прямо на оригинальную картинку
$config['show_upload_date']=1; //показывать дату/время загрузки изображения на "Странице просмотра" 0 - выключено, 1 - включено
//////////////////////////////////////CURL//////////////////////////////////////
$config['curl_timeout'] = 120;//таймаут для curl
$config['curl_user_agent']='User-Agent: Opera/9.80 (X11; Linux i686; U; ru) Presto/2.9.168 Version/11.50';
$config['curl_headers']=array(
'GET / HTTP/1.1',
'Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1',
'Accept-Language: ru,ru-RU;q=0.9,en;q=0.8',
'Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1',
'Accept-Encoding: deflate, gzip, x-gzip, identity, *;q=0',
'Cookie: cookies_enabled=1;',
'Cache-Control: no-cache',
'Connection: Keep-Alive, TE',
'TE: deflate, gzip, chunked, identity, trailers'
);
//////////////////////////////////////Даты - для создания каталогов//////////////////////////////////////
$config['current_month']=date ('Y-m');
$config['current_day']=date ('d');
$config['current_path']=$config['current_month'].'/'.$config['current_day'];
$debug = false; // [true|false] отладка, показывать ошибки PHP включено/выключено
//////////////////////////////////////Прочее//////////////////////////////////////
$config['random_str_quantity']=25;
$config['site_work']=true; // [true|false] сайт работает да/нет
$config['cache_time']=60*60; //в секундах, 1 час.
$config['cachefile']=$config['working_dir']."cachefile.dat"; //файл статистики "Изображений на фотохостинге: х; занимают х.х Kb; за сутки загружено: х"
/* --------------------------------------------------------------------------
Конец файла конфигурации config.php поставляемый по "умолчанию"
----------------------------------------------------------------------------- */
return ($config);
}
// сравнение настроек из существующего ocnfig.php и new_config()
function check_array($array,$arr_key)
{
GLOBAL $config,$new_config,$level;
// расцветка для подсветки элементов
$check_good="#33AA33";
$check_bad="#FF3333";
$check_empty="#666666";
$check_element="#FF7F00";
//GLOBAL $check_good,$check_bad,$check_empty,$check_element;
$chcontent="";
foreach ($array as $key => $value)
{
$check_b="<font color='$check_empty'>";
$check_e="</font>";
if (!is_array($value))
{
if (!empty($arr_key))
{
if (in_array($value, $config[$arr_key]))
{
$check_b="<font color='$check_good'>";
$check_e="</font>";
}
}
else
if (isset($config[$key]))
{
if ($config[$key]==$new_config[$key])
{
$check_b="<font color='$check_good'>";
$check_e="</font>";
}
else
{
$check_b="<font color='$check_bad'>";
$check_e="</font>";
}
}
for ($i=0;$i < $level+1 ;$i++) $chcontent.= " ";
if ($level) $ccf=''; else $ccf="<font color='$check_element'>\$config</font>";
$chcontent.= $ccf."['<font color='$check_element'>".$key."</font>'] => ".$check_b.$value." ".$check_e."<br />\n";
}
else
{
if (array_key_exists($key, $config))
{
$check_b="<font color='#00CC00'>";
$check_e="</font>";
}
for ($i=0;$i < $level+1 ;$i++) $chcontent.= " ";
$chcontent.= "<font color='$check_element'>\$config</font>['<font color='$check_element'>".$key."</font>'] => ".$check_b."Array".$check_e."<br />\n";
for ($i=0;$i < $level+1 ;$i++) $chcontent.= " ";
$chcontent.= " (<br />\n";
$level++;
$chcontent.= check_array($value,$key);
$level--;
for ($i=0;$i < $level+1 ;$i++) $chcontent.= " ";
$chcontent.= " )<br />\n";
}
}
return $chcontent;
}
// функция разделения URL на подкаталоги при переходе по ним
function split_dir($str)
{
$arr=explode('/', $str);
$f=1; $g=1;
$ret='<a href="{self_script}"><корень></a> ';
$p='';
if($str!='/')
{
foreach($arr as $v)
{
$ret.='<a href="{self_script}?cd='.$p.$v.'">'.$v.'</a>';
if($f==0)
$f=1;
else
$ret.=' / ';
$p.=$v;
if($g==0)
$g=1;
else
$p.='/';
}
}
return $ret;
}
// функция сравнения
function cmp( $a, $b )
{
GLOBAL $sort;
if( $a->inode == $b->inode )
return 0;
switch( $sort )
{
case "size":
return ($a->size > $b->size) ? -1 : 1;
case "type":
return strcmp($a->type, $b->type);
case "view":
return strcmp($a->view, $b->view);
case "atime":
return ($a->atime > $b->atime) ? -1 : 1;
case "ctime":
return ($a->ctime > $b->ctime) ? -1 : 1;
case "mtime":
return ($a->mtime > $b->mtime) ? -1 : 1;
case "group":
return strcmp($a->group, $b->group);
case "inode":
return ($a->inode > $b->inode) ? -1 : 1;
case "owner":
return strcmp($a->owner, $b->owner);
case "perms":
return ($a->perms > $b->perms) ? -1 : 1;
case "ext":
return strcmp($a->ext, $b->ext);
case "name":
return strcmp(strtolower($a->name), strtolower($b->name));
default:
return 1;
}
}
// вырезание лишнего мусора из GET запроса при переходе по каталогам
function escape_dir($str)
{
$ret=str_replace("/../", '/', $str);
$ret=str_replace("/./", '/', $ret);
$ret=str_replace("/..", '/', $str);
$ret=str_replace("/./", '/', $ret);
$ret=str_replace("\\", "", $ret);
return $ret;
}
// удобоваримыое отображение прав доступа к файлу/каталогу
function formperms($v,$own)
{
GLOBAL $uid;
$s=substr(sprintf('%o', $v), -4);
if ($own===$uid)
$ret="<font color='grey'>".$s[0]."</font><font color='green'>".$s[1]."</font><font color='grey'>".$s[2].$s[3]."</font>";
else
if ($s[3]==='7' || $s[3]==='6')
$ret="<font color='grey'>".$s[0].$s[1].$s[2]."</font><font color='green'>".$s[3]."</font>";
else
$ret="<font color='grey'>".$s[0].$s[1].$s[2]."</font><font color='red'><b>".$s[3]."<b></font>";
return $ret;
}
//кодирование переменных для предоставления в GET запрос
function genUrl( $ref, $args, $key = "", $val = "" )
{
$valist = "";
reset( $args );
if( $key != "" )
$args[ "$key" ] = $val;
if( !is_array( $args ) )
return $ref;
while( list( $key, $val ) = each( $args ) )
{
if( $val == "" )
continue;
if( $valist == "" )
$valist .= "?";
else
$valist .= "&";
$valist .= $key."=".rawurlencode($val);
}
return $ref.$valist;
}
// удаление файлов и каталогов
function total_delete($arg)
{
GLOBAL $error, $inform;
if (file_exists($arg))
{
@chmod($arg,0755);
if (is_dir($arg))
{
$handle = opendir($arg);
while($aux = readdir($handle))
{
if ($aux != "." && $aux != "..") total_delete($arg."/".$aux);
}
@closedir($handle);
if (@rmdir($arg))
{
$inform[]= "$arg - удален\n";
}
else
$error[]= "Невозможно удалить $arg\n";
}
else
if (@unlink($arg))
{
$inform[]= "$arg - удален\n";
}
else
$error[]= "Невозможно удалить $arg\n";
}
}
// класс с массивом структуры "текущего" каталога
class MyFile {
var $name;
var $fpath;
var $type;
var $ext;
var $size;
var $file;
var $atime;
var $ctime;
var $mtime;
var $group;
var $inode;
var $owner;
var $perms;
function set( $filename, $fpath )
{
GLOBAL $cd;
$this->name = $filename;
$this->fpath = $fpath ;
$this->file = $this->fpath."/".$this->name;
$this->type = filetype( $this->file );
// if ($this->type == "dir") $this->size = dirSize( $this->file ); else
$this->size = sprintf("%u", filesize($this->file)); //$this->size = filesize( $this->file );
$this->atime = fileatime( $this->file );
$this->ctime = filectime( $this->file );
$this->mtime = filemtime( $this->file );
$this->group = filegroup( $this->file );
$this->inode = fileinode( $this->file );
$this->owner = fileowner( $this->file );
$this->perms = fileperms( $this->file );
switch( $this->type )
{
case "link":
$this->ext = "link";
break;
case "file":
$list = explode( ".", $this->name );
$nb = sizeof( $list );
if( $nb > 0 )
$this->stype = $list[$nb-1];
else
$this->stype = "???";
$this->ext = $this->stype;
break;
default:
$this->ext = $this->type;
break;
}
}
function formatSize()
{
// return decodeSize($his->size);
return number_format( $this->size, 0, ".", "");
}
}
// phpinfo и другое
function server_info(){
if (!@phpinfo()) echo 'NoPhpinfo'."...";
echo "<br><br>";
$a=ini_get_all();
$output="<table border=1 cellspacing=0 cellpadding=4 align=center>";
$output.="<tr><th colspan=2>ini_get_all()</td></tr>";
while(list($key, $value)=each($a)) {
list($k, $v)= each($a[$key]);
$output.="<tr><td align=right>$key</td><td>$v</td></tr>";
}
$output.="</table>";
echo $output;
echo "<br><br>";
$output="<table border=1 cellspacing=0 cellpadding=4 align=center>";
$output.="<tr><th colspan=2>\$_SERVER</td></tr>";
foreach ($_SERVER as $k=>$v) {
$output.="<tr><td align=right>$k</td><td>$v</td></tr>";
}
$output.="</table>";
echo $output;
echo "<br><br>";
echo "<table border=1 cellspacing=0 cellpadding=4 align=center>";
$safe_mode=trim(ini_get("safe_mode"));
if ((strlen($safe_mode)==0)||($safe_mode==0)) $safe_mode=false;
else $safe_mode=true;
$is_windows_server = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
echo "<tr><td colspan=2>".php_uname();
echo "<tr><td>safe_mode<td>".($safe_mode?"on":"off");
if ($is_windows_server) echo "<tr><td>sisop<td>Windows<br>";
else echo "<tr><td>sisop<td>Linux<br>";
echo "</table><br><br><table border=1 cellspacing=0 cellpadding=4 align=center>";
$display_errors=ini_get("display_errors");
$ignore_user_abort = ignore_user_abort();
$max_execution_time = ini_get("max_execution_time");
$upload_max_filesize = ini_get("upload_max_filesize");
$memory_limit=ini_get("memory_limit");
$output_buffering=ini_get("output_buffering");
$default_socket_timeout=ini_get("default_socket_timeout");
$allow_url_fopen = ini_get("allow_url_fopen");
$magic_quotes_gpc = ini_get("magic_quotes_gpc");
ignore_user_abort(true);
ini_set("display_errors",0);
ini_set("max_execution_time",0);
ini_set("upload_max_filesize","10M");
ini_set("memory_limit","20M");
ini_set("output_buffering",0);
ini_set("default_socket_timeout",30);
ini_set("allow_url_fopen",1);
ini_set("magic_quotes_gpc",0);
echo "<tr><td> <td>Get<td>Set<td>Get";
echo "<tr><td>display_errors<td>$display_errors<td>0<td>".ini_get("display_errors");
echo "<tr><td>ignore_user_abort<td>".($ignore_user_abort?"on":"off")."<td>on<td>".(ignore_user_abort()?"on":"off");
echo "<tr><td>max_execution_time<td>$max_execution_time<td>0<td>".ini_get("max_execution_time");
echo "<tr><td>upload_max_filesize<td>$upload_max_filesize<td>10M<td>".ini_get("upload_max_filesize");
echo "<tr><td>memory_limit<td>$memory_limit<td>20M<td>".ini_get("memory_limit");
echo "<tr><td>output_buffering<td>$output_buffering<td>0<td>".ini_get("output_buffering");
echo "<tr><td>default_socket_timeout<td>$default_socket_timeout<td>30<td>".ini_get("default_socket_timeout");
echo "<tr><td>allow_url_fopen<td>$allow_url_fopen<td>1<td>".ini_get("allow_url_fopen");
echo "<tr><td>magic_quotes_gpc<td>$magic_quotes_gpc<td>0<td>".ini_get("magic_quotes_gpc");
echo "</table><br><br>";
echo "
<script language=\"Javascript\" type=\"text/javascript\">
<!--
window.moveTo((window.screen.width-800)/2,((window.screen.height-600)/2)-20);
window.focus();
//-->
</script>";
echo "</body>\n</html>";
}
//загружаем предустановки
if(!include_once('config.php')) die('Can\'t find config.php');
$init_php=false;
//инициализация и проверка
if (file_exists('init.php'))
{
$init_php=true;
if(!include_once('init.php')) die('Can\'t find init.php');
}
//загружаем функции
if(!include_once('functions.php')) die('Can\'t find functions.php');
if (!function_exists('check_perm')){
function check_perm($chk_obj,$errmod=false)
{
GLOBAL $error;
//проверка прав доступа к каталогам/файлам
$processUser = posix_getpwuid(posix_geteuid());
$uid=$processUser['uid']; //UID пользователя от имени которого работает WEB сервер
if(!file_exists($chk_obj))
{
if ($errmod) $error[]="$chk_obj не найден";
return false;
}
/* здесь перепроверка каталогов и вывод где ошибка */
$perms = substr(decoct(@fileperms($chk_obj)), 2);
$fown = @fileowner($chk_obj);
if (is_dir($chk_obj))
{
if (($uid!=$fown and $perms[2]!='7') || ($uid==$fown and $perms[0]!='7'))
{
if ($errmod) $error[]="Ошибка установки прав на каталог $chk_obj";
return false;
}
else
return true;
}
else
{
if (($uid!=$fown and $perms[3]!='6') || ($uid==$fown and $perms[1]!='6'))
{
if ($errmod) $error[]="Ошибка установки прав на файл $chk_obj";
return false;
}
else
return true;
}
}}
/* здесь перепроверка каталогов и вывод где ошибка */
check_perm($config['working_dir'],1);
check_perm($config['working_thumb_dir'],1);
check_perm($config['uploaddir'],1);
check_perm($config['thumbdir'],1);
//если старый конфиг не содержит IniFile
if (!isset($IniFile) and isset($config['working_dir']))
{ $IniFile=$config['working_dir'].'config.ini';
$OldConfigNoINI=1;
}
check_perm($IniFile,1);
preg_match('/\/(.*\/).*\.php/', $_SERVER['PHP_SELF'], $out);
$folder_adm = isset($out[1]) ? $out[1]:'';
if ((!isset($config['site_http_path'])) ||
((isset($config['site_http_path'])) && ($config['site_http_path']!='http://'.$_SERVER['HTTP_HOST'].'/'.$folder_adm))
)
$config['site_http_path']='http://'.$_SERVER['HTTP_HOST'].'/'.$folder_adm;
//$config['site_url']='http://'.$_SERVER['HTTP_HOST'].'/'.$folder_adm;
//$config['thumbs_url']=$config['site_url'].'thumbs/';
//$config['img_url']=$config['site_url'].'img/';
if (!isset($debug)) $debug=false;
$template = @file_get_contents($config['site_dir'].'/admin/admin.tpl')
or die('Template admin.tpl don\'t find.');
//проверка прав доступа к каталогам
$processUser = posix_getpwuid(posix_geteuid());
$uid=$processUser['uid']; //UID пользователя от имени которого работает WEB сервер
//предустановка для шаблона
$parse_tpl=array();
$parse_tpl['{site_title}']='ADMIN Lite Panel - Akina Фотохостинг.';
$parse_tpl['{site_header_h1}']='Akina. ADMIN Panel';
$parse_tpl['{site_header_h2}']='';
$parse_tpl['{menu}']='<li><a href="?">[Главное меню]</a></li>';
$parse_tpl['{content}']='';
$parse_tpl['{inner_js}']='';
$parse_stat='';
$passwd='';
// Стартуем сессию
session_start();
header("http/1.0 200 Ok");
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
if (!file_exists($IniFile))
{
$passwd=random_string(8, 'lower,numbers');
$IniData = array('admin' => array('pass' => $passwd));
if (!@write_ini_file($IniData, $IniFile, true)) $error[]="Ошибка записи в файл $IniFile [1]";
else
$parse_stat="--- угадайте пароль <font color='red'>:)</font> ---<br>\n";
}
else
{
if (!isset($ini_array)) $ini_array = @parse_ini_file($IniFile,true);
if (isset($ini_array['admin']['pass']))
{
$tmppasswd=$ini_array['admin']['pass'];
if ($tmppasswd[0]!='{')
{
$passwd="{".md5($tmppasswd);
$IniData = array('admin' => array('pass' => $passwd));
if (!@write_ini_file($IniData, $IniFile, true)) $error[]="Ошибка записи в файл $IniFile [2]";
}
else
$passwd=$tmppasswd;
unset($tmppasswd);
}
else
{
$passwd=random_string(8, 'lower,numbers');
$IniData = array('admin' => array('pass' => $passwd));
if (!@write_ini_file($IniData, $IniFile, true)) $error[]="Ошибка записи в файл $IniFile [3]";
else
$parse_stat="--- угадайте пароль <font color='red'>:)</font> ---<br>\n";
}
}
if(!isset($_SESSION['Admin_Ok']))
{
if((isset($_POST['act'])) and (isset($_POST['pass'])) and ("{".md5($_POST['pass'])==$passwd))
{
$_SESSION['Admin_Ok']=1;
$parse_tpl['{site_header_h1}']='Akina. Вход';
$parse_tpl['{site_header_h2}']='Вход выполнен успешно. Ждите.';
$parse_tpl['{content}']='Ждите перенаправления...';
$_SESSION['Preview']=1; //по умолчанию показываем превью картинок
$_SESSION['ViewLog']=1; //по умолчанию показываем протокол успешных операций
header( "refresh:0;url=".$_SERVER["PHP_SELF"] );
}
else
{
if((isset($_POST['pass'])) and ("{".md5($_POST['pass'])!=$passwd))
$error[]="<font color=red>Пароль не верный</font>";
if (isset($_SESSION['Admin_Ok'])) unset($_SESSION['Admin_Ok']);
$parse_tpl['{site_title}']='Akina. Вход';
$parse_tpl['{site_header_h2}']='Akina Вход';
$parse_tpl['{content}']='
<b>Akina Admin</b> приветствует вас!<br>'.$parse_stat.'<br><br>
<form action="?" method="post" class="configform">
<input name="act" type="hidden" value="ok">
Пароль: <input name="pass" type="password" value=""><br><br>
<input type="submit" value=" Вход " />
</form><br>';
}
}
else
{ //isset($_SESSION['Admin_Ok'])
if ( (isset($_SESSION['Files']) && (!isset($_GET['nofiles'])) ) || (isset($_GET['files'])) ) //файловая панель
{
clearstatcache();
if (isset($_POST['act']))
{
switch($_POST['act'])
{
case 'set' :
if (isset($_POST['prev']) && ($_POST['prev']=='1')) $_SESSION['Preview']=1;
else if (isset($_SESSION['Preview'])) unset($_SESSION['Preview']);
if (isset($_POST['log']) && ($_POST['log']=='1')) $_SESSION['ViewLog']=1;
else if (isset($_SESSION['ViewLog'])) unset($_SESSION['ViewLog']);
break;
default :
$parse_tpl['{content}'].="<font color=red>функция _POST не определана</font>\n";
header( "refresh:1;url=?" );
break;
}
}
elseif (isset($_GET['act']))
{
switch($_GET['act'])
{
default :
$parse_tpl['{content}'].="<font color=red>функция _GET не определана</font>\n";
header( "refresh:1;url=?" );
break;
}
}
if(isset($_GET['step']))
{
$step = $_GET['step'];
$args["step"] = $step;
}
else
$step = 100;
if(isset($_GET['cd']))
$cd = escape_dir($_GET['cd']);
else
$cd = '';
if(isset($_GET['sort']))
{
$sort = $_GET['sort'];
$args["sort"] = $sort;
}
else
$sort = "name";
$ref = "{self_script}";
if(isset($_GET['from']))
{
$from = $_GET['from'];
$args["from"] = $from;
}
else
$from = 0;
if(isset($_GET['to']))
{
$to = $_GET['to'];
$args["to"] = $to;
}
else
$to = $from + $step;
if (!isset($_SESSION['Files'])) $_SESSION['Files']=1;
if (isset($_SESSION['Preview'])) $chkdp="checked"; else $chkdp="";
if (isset($_SESSION['ViewLog'])) $chkdl="checked"; else $chkdl="";
$parse_tpl['{site_header_h2}']='Akina. Файлы на хостинге.';
$parse_tpl['{menu}'] ='<li><a href="?nofiles=1">[Главное меню]</a></li>';
$parse_tpl['{menu}'].='<li><a href="?act=setting&nofiles=1">[Настройки]</a></li>';
$parse_tpl['{menu}'].='<li><a href="?act=logoff&nofiles=1">[Выход]</a></li>';
$parse_tpl['{menu}'].="<li><INPUT TYPE='checkbox' ID='check_prev' NAME='prev' VALUE='1' ".$chkdp." title='Показывать Превью картинок'> Превью <INPUT TYPE='checkbox' ID='check_log' NAME='log' VALUE='1' ".$chkdl." title='Показывать Лог успешных операций'> Лог</li>";
$parse_tpl['{content}']="\n";
$template_dir= "";
// js подтверждения удаления
$parse_tpl['{inner_js}'].="
function confirmDelete()
{if (confirm('Вы подтверждаете удаление выделеных объектов?')) {return true;} else {return false;}}\n";
$parse_tpl['{inner_js}'].="
$(function() {
$('#check_prev').on('change', sendChBoxStatus);
$('#check_log').on('change', sendChBoxStatus);
function sendChBoxStatus() {
if (confirm('Does the status of this survey really changed?')) {
prev_val = $('#check_prev').is(':checked') ? 1 : 0;
log_val = $('#check_log').is(':checked') ? 1 : 0;
$.post( '".$_SERVER["PHP_SELF"]."', { act: 'set', prev: prev_val, log: log_val}, location.reload());
}
}
});";
// <FORM NAME='del' METHOD='post' ACTION='?cd=".$cd."'><INPUT TYPE='hidden' NAME='act' VALUE='set'><INPUT TYPE='checkbox' NAME='prev' VALUE='01' ".$chkdp." >Показывать Превью <INPUT TYPE='checkbox' NAME='log' VALUE='01' ".$chkdl." >Показывать Лог <INPUT TYPE='submit' VALUE=' Set '></form>
// js превью картинок
if (isset($_SESSION['Preview'])) $parse_tpl['{inner_js}'].="
// Image preview script powered by jQuery (http://www.jquery.com)
// written by Alen Grakalic (http://cssglobe.com)
// for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
this.imagePreview = function(){
/* CONFIG */
xOffset = 10;
yOffset = 10;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$(\"a.preview\").hover(function(e){
this.t = this.title;
this.title = \"\";
var c = (this.t != \"\") ? \"<br/>\" + this.t : \"\";
$(\"body\").append(\"<p id='preview'><img src='\"+ this.href +\"' alt='Image preview' />\"+ c +\"</p>\");
$(\"#preview\")
.css(\"top\",(e.pageY - xOffset) + \"px\")
.css(\"left\",(e.pageX + yOffset) + \"px\")
.fadeIn(\"fast\");
},
function(){
this.title = this.t;
$(\"#preview\").remove();
});
$(\"a.preview\").mousemove(function(e){
$(\"#preview\")
.css(\"top\",(e.pageY - xOffset) + \"px\")
.css(\"left\",(e.pageX + yOffset) + \"px\");
});
};
// starting the script on page load
$(document).ready(function(){
imagePreview();
});\n";
// debug
//echo "<!-- \n";
//if( isset($_POST)){echo "\nPOST \n"; print_r($_POST); echo "\n";}
//echo "cd: $cd\n";
//if( isset($_POST["nb"])){echo "\nPOST nb: \n"; print_r($_POST["nb"]); echo "\n";}
//echo "\n -->\n";
$fpath = $config['uploaddir'].$cd;
$args["cd"] = $cd;
if( isset( $_POST['nb'] ) ) //удаление файлов и каталогов
{
$inform[]= "Удаляем:<br>\n";
for( $i = 0; $i < $_POST['nb']; $i++ )
{
if( isset( $_POST["id_$i"] ) )
{
$file = $fpath."/".$_POST["id_$i"];
total_delete($file);
$file = $config['thumbdir'].$cd."/".$_POST["id_$i"];
total_delete($file);
}
}
}
$template_dir.= split_dir($cd)."<br><br>\n";
if (file_exists($fpath))
{
///////////////читаем каталог
$d = dir($fpath);
$n =0;
while( $entry=$d->read() )
{
$lFiles[ $n ] = new MyFile;
$lFiles[ $n ]->set( $entry, $fpath );
$n++;
}
$d->close();
///////////////закончили читать
if(($from-$step) >= 0 )
{
$template_dir.= "<a href='".genUrl( $ref, $args, "from", $from-$step )."' >« Prev</a> /\n";
}
if($to <= $n)
{
$template_dir.= "<a href='".genUrl( $ref, $args, "from", $to )."' >Next »</a><br/>\n";
}
//форма + шапка таблицы
$template_dir.= "<FORM NAME='del' METHOD='post' ACTION='".genUrl( $ref, $args )."'>\n";
$template_dir.= "<TABLE >\n";
$template_dir.= "<TR>\n";
$template_dir.= "<TH> ✓ </TH>\n";
//$template_dir.= "<TH><a href='".genUrl( $ref, $args, "sort", "type" )."'>Type</a></TH>\n";
$template_dir.= "<TH width=250><a href='".genUrl( $ref, $args, "sort", "name" )."'>Имя</a></TH>\n";
$template_dir.= "<TH width=70><a href='".genUrl( $ref, $args, "sort", "size" )."'>Размер</a></TH>\n";
//$template_dir.= "<TH><a href='".genUrl( $ref, $args, "sort", "ext" )."'>ext</a></TH>\n";
$template_dir.= "<TH width=118><a href='".genUrl( $ref, $args, "sort", "mtime" )."'>mtime</a></TH>\n";
$template_dir.= "<TH width=118><a href='".genUrl( $ref, $args, "sort", "atime" )."'>atime</a></TH>\n";
//$template_dir.= "<TH width=118><a href='".genUrl( $ref, $args, "sort", "ctime" )."'>создан</a></TH>\n";
$template_dir.= "<TH><a href='".genUrl( $ref, $args, "sort", "perms" )."'>perms</a></TH>\n";
//$template_dir.= "<TH><a href='".genUrl( $ref, $args, "sort", "group" )."'>group</a></TH>\n";
//$template_dir.= "<TH><a href='".genUrl( $ref, $args, "sort", "owner" )."'>owner</a></TH>\n";
//$template_dir.= "<TH><a href='".genUrl( $ref, $args, "sort", "inode" )."'>inode</a></TH>\n";
$template_dir.= "</TR>\n";
//конец шапки таблицы
//сортируем
@usort( $lFiles, cmp );
for( $i = 0; $i < $n; $i++ )
{
if( ( $i < $from ) || ( $i >= $to ) )
continue;
$k = $i;
if (( $lFiles[ $k ]->name != "lost+found" ) && ($lFiles[ $k ]->name[0] != "."))
{
$template_dir.= "<TR>\n";
$template_dir.= "<TD ID='td01'><INPUT TYPE='checkbox' NAME='id_$k' VALUE='".$lFiles[ $k ]->name."'></TD>\n";
if ($cd =="" )
$tcd = $lFiles[ $k ]->name;
else
$tcd = $cd."/".$lFiles[ $k ]->name;
//$dform = "d.m.Y, H:i";
$dform = "Y.m.d H:i";
// echo "<TD ID='td02'>".$lFiles[ $k ]->type."</TD>\n";
$template_dir.= "<TD ID='td03'> ";
if ( $lFiles[ $k ]->type == "dir" )
{
if ($cd =="" )
$tcd = $lFiles[ $k ]->name;